How can I get Python 3.7 new dataclass field types?

Kamyar picture Kamyar · Aug 21, 2018 · Viewed 30.1k times · Source

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?

Answer

user2357112 supports Monica picture user2357112 supports Monica · Aug 21, 2018

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}