Dataclasses
In Python 3.7, a new dataclasses
module has been added to the standard library.This module allows defining and customizing simple boilerplate-free classes.They can be defined using the @dataclasses.dataclass
decorator:
- from dataclasses import dataclass, field
- @dataclass
- class Application:
- name: str
- plugins: List[str] = field(default_factory=list)
- test = Application("Testing...") # OK
- bad = Application("Testing...", "with plugin") # Error: List[str] expected
Mypy will detect special methods (such as lt
) depending on the flags used todefine dataclasses. For example:
- from dataclasses import dataclass
- @dataclass(order=True)
- class OrderedPoint:
- x: int
- y: int
- @dataclass(order=False)
- class UnorderedPoint:
- x: int
- y: int
- OrderedPoint(1, 2) < OrderedPoint(3, 4) # OK
- UnorderedPoint(1, 2) < UnorderedPoint(3, 4) # Error: Unsupported operand types
Dataclasses can be generic and can be used in any other way a normalclass can be used:
- from dataclasses import dataclass
- from typing import Generic, TypeVar
- T = TypeVar('T')
- @dataclass
- class BoxedData(Generic[T]):
- data: T
- label: str
- def unbox(bd: BoxedData[T]) -> T:
- ...
- val = unbox(BoxedData(42, "<important>")) # OK, inferred type is int
For more information see official docsand PEP 557.
Caveats/Known Issues
Some functions in the dataclasses
module, such as replace()
and asdict()
,have imprecise (too permissive) types. This will be fixed in future releases.
Mypy does not yet recognize aliases of dataclasses.dataclass
, and willprobably never recognize dynamically computed decorators. The following examplesdo not work:
- from dataclasses import dataclass
- dataclass_alias = dataclass
- def dataclass_wrapper(cls):
- return dataclass(cls)
- @dataclass_alias
- class AliasDecorated:
- """
- Mypy doesn't recognize this as a dataclass because it is decorated by an
- alias of `dataclass` rather than by `dataclass` itself.
- """
- attribute: int
- @dataclass_wrapper
- class DynamicallyDecorated:
- """
- Mypy doesn't recognize this as a dataclass because it is decorated by a
- function returning `dataclass` rather than by `dataclass` itself.
- """
- attribute: int
- AliasDecorated(attribute=1) # error: Unexpected keyword argument
- DynamicallyDecorated(attribute=1) # error: Unexpected keyword argument