Dataclass with Type Hints Fields in Python

Create a data class with typed fields and default values, then instantiate and inspect it.

Easy Python 3.9+ Aug 9, 2026 Testing & modern typing 12 views 0 copies

Python code

16 lines
Python 3.9+
from 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

stdout
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

  1. Use `@dataclass(frozen=True)` to make instances immutable.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Testing & modern typing

Related tutorials and quizzes for this topic.