How can I get Python 3.7 new dataclass field types?

前端 未结 3 1129
抹茶落季
抹茶落季 2020-12-18 17:38

Python 3.7 introduces new feature called data classes.

from dataclasses import dataclass

@dataclass
class MyClass:
    id: int = 0
    name: str = \'\'
         


        
3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 18:45

    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}
    

提交回复
热议问题