Search code examples
pythontyping

Get type information about dataclass fields


For a given dataclass, how to get infos about fields type ?

Example:

>>> from dataclasses import dataclass, fields
>>> import typing
>>> @dataclass
... class Foo:
...     bar: typing.List[int]

I can have fields info with the repr:

>>> fields(Foo)
(Field(name='bar',type=typing.List[int],default=<dataclasses._MISSING_TYPE object at 0x7fef9aafd9b0>,default_factory=<dataclasses._MISSING_TYPE object at 0x7fef9aafd9b0>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),_field_type=_FIELD),)

I can have a type repr of my bar field

>>> fields(Foo)[0].type
typing.List[int]

How to retrieve (as python objects, not as string repr):

  • the type (typing.List)
  • type type of items in the typing.List (int)

?


Solution

  • type property of a data class field it's not a string representation, it's a type.

    Python 3.6:

    >>> type(fields(Foo)[0].type)
    <class 'typing.GenericMeta'>
    

    Python 3.7:

    >>> type(fields(Foo)[0].type)
    <class 'typing._GenericAlias'>
    

    In this case you can retrieve inner type with __args__ property:

    >>> fields(Foo)[0].type.__args__
    (<class 'int'>,)