Dataclass with Type Hints Fields in Python
Create a data class with typed fields and default values, then instantiate and inspect it.
Python code
16 linesfrom dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
email: str = "unknown@example.com"
is_active: bool = True
if __name__ == "__main__":
person = Person(name="Alice", age=30)
print(person)
print(f"Name: {person.name}, Age: {person.age}, Email: {person.email}, Active: {person.is_active}")
print(f"Type of name: {type(person.name)}, Type of age: {type(person.age)}")
Output
Person(name='Alice', age=30, email='unknown@example.com', is_active=True)
Name: Alice, Age: 30, Email: unknown@example.com, Active: True
Type of name: <class 'str'>, Type of age: <class 'int'>
How it works
The @dataclass decorator automatically generates __init__, __repr__, and __eq__ methods based on the annotated fields. Default values are provided when the constructor omits them. Type hints like str and int are for static analysis (mypy, pyright) and do not enforce runtime type checks. The generated __repr__ shows the class name and field values, making debugging easy.
Common mistakes
- Assuming type hints enforce runtime type validation—they don't.
- Putting a field with a default before one without a default (leads to SyntaxError).
- Forgetting to import `dataclass` from the `dataclasses` module.
Variations
- Use `@dataclass(frozen=True)` to make instances immutable.
- Add `@dataclass(slots=True)` for a memory-efficient class.
Real-world use cases
- Modeling domain entities like a User or Product with typed fields in a web application.
- Defining structured request/response DTOs in a service layer with clean repr and equality.
- Representing rows from a CSV or database query with typed attributes for processing.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
- Format Data with Type Hints in Python easy
Keep learning
Related tutorials and quizzes for this topic.