@dataclass class Person: name: str age: int
Decorators & Metaclasses

Meaning

Defines a simple data class for a person with name and age.

Primary Function

Define a lightweight class for storing structured data with auto-generated __init__, __repr__, and equality methods.

Communicative Purpose

Communicate the structure of a Person record in code.

Pattern

@dataclass class {ClassName}: {field_name}: {type} ...

Core Structure

@dataclass decorator on a class containing typed fields.

Função primária

Define a lightweight class for storing structured data with auto-generated __init__, __repr__, and equality methods.

Propósito comunicativo

Communicate the structure of a Person record in code.

Situações de gatilho

When you need a simple container for related attributes without writing boilerplate.

Contextos

Used in data modeling, DTOs, configuration objects, or simple domain models.

Padrão

@dataclass class {ClassName}: {field_name}: {type} ...

Estrutura central

@dataclass decorator on a class containing typed fields.

Slots de substituição

{ClassName}, {field_name: type}, ...

Colocados típicos

  • dataclass
  • field
  • InitVar
  • field(default=...)
  • field(compare=False)

Substituições comuns

  • namedtuple
  • TypedDict
  • attrs.attrs

Erros comuns

Forgetting to import dataclass, omitting type hints, expecting immutability without frozen=True.

Similar / contraste

namedtuple (immutable, tuple-like), TypedDict (structural typing), attrs library (more features).

Interferências

Confusing dataclass with a regular class; assuming keyword-only arguments by default.

Família do chunk

  • dataclass
  • namedtuple
  • TypedDict
  • attrs

Nuance

Dataclasses automatically generate __init__, __repr__, __eq__, and other methods; they are mutable unless frozen=True.

Efeito pragmático

Signals that the class is a simple data container, reducing boilerplate.

Dica de memória

@dataclass class Person: name: str, age: int

Upgrade path

dataclass with frozen=True or using attrs library for more advanced features

Tipo de construção: @dataclass decorator applied to a class with typed fields.Tag de espaçamento: Medium-term

Log in to save chunks.