Python 3.7 introduces new feature called data classes.
from dataclasses import dataclass
@dataclass
class MyClass:
id: int = 0
name: str = ''
When using type hints (annotation) in function parameters, you can easily get annotated types using inspect module. How can I get dataclass field types?
Inspecting __annotations__
gives you the raw annotations, but those don't necessarily correspond to a dataclass's field types. Things like ClassVar and InitVar show up in __annotations__
, even though they're not fields, and inherited fields don't show up.
Instead, call dataclasses.fields
on the dataclass, and inspect the field objects:
field_types = {field.name: field.type for field in fields(MyClass)}
Neither __annotations__
nor fields
will resolve string annotations. If you want to resolve string annotations, the best way is probably typing.get_type_hints
. get_type_hints
will include ClassVars and InitVars, so we use fields
to filter those out:
resolved_hints = typing.get_type_hints(MyClass)
field_names = [field.name for field in fields(MyClass)]
resolved_field_types = {name: resolved_hints[name] for name in field_names}