dataclasses

Utilities

Typed data models

Try dataclasses in PyRun

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.

Python Dataclasses
Try in Editor
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
Open editor with dataclasses example

Related Packages