dataclasses
UtilitiesTyped data models
What is dataclasses?
The dataclasses module is part of the Python standard library (Python 3.7+). It provides a decorator and functions for automatically generating special methods like __init__, __repr__, __eq__, and __hash__ for classes that are primarily used to store data. Dataclasses reduce boilerplate while keeping your models readable and maintainable.
Because dataclasses are part of Python's standard library, they work instantly in PyRun without any additional imports or micropip downloads. They're the most lightweight way to define structured data models in Python, and are especially useful for learning object-oriented programming or building small apps.
Code Example
Typed models with sorting and asdict serialisation.
from dataclasses import dataclass, field, asdict
from typing import List
@dataclass(order=True)
class Student:
name: str
grade: float
subjects: List[str] = field(default_factory=list)
def gpa_letter(self) -> str:
if self.grade >= 90: return 'A'
if self.grade >= 80: return 'B'
if self.grade >= 70: return 'C'
return 'D'
students = [
Student("Alice", 94.5, ["Math", "Physics"]),
Student("Bob", 78.2, ["History", "English"]),
Student("Charlie", 88.0, ["CS", "Math", "Bio"]),
]
for s in sorted(students, reverse=True):
print(f"{s.name:<10} GPA={s.grade:.1f} ({s.gpa_letter()}) — {', '.join(s.subjects)}")
print("\nAs dicts:")
for row in students:
print(asdict(row))Why run dataclasses in PyRun?
- ✦ Zero setup — no pip install, no virtual environment, no Python download
- ✦ Instant results — powered by WebAssembly, runs locally in your browser
- ✦ Share your code — generate a link and anyone can run it instantly
- ✦ Works offline — after first load, PyRun runs without internet
Related Packages
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Loops
Learn how to use Python loops to iterate over data. Master for loops, while loops, break, continue, and loop best practices with interactive examples.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python String Methods
A complete reference guide for Python string manipulation. Master formatting, searching, splitting, replacing, and checking string properties.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.