Skip to content
Python

Dataclass

Simplify class definitions with dataclass.

By EZ4Code Team
dataclassclass

Code

from dataclasses import dataclass, field
from typing import List

@dataclass
class User:
    name: str
    age: int
    email: str = ""
    tags: List[str] = field(default_factory=list)

    def __post_init__(self):
        if self.age < 0:
            raise ValueError("Age cannot be negative")

user = User("Alice", 30, "[email protected]")
print(user)  # Auto-generated __repr__

# Convert to dict
from dataclasses import asdict
print(asdict(user))

Explanation

dataclass auto-generates __init__, __repr__, etc., reducing boilerplate.

More Python Snippets