bux
bux

Reputation: 7799

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):

?

Upvotes: 4

Views: 2963

Answers (2)

theannouncer
theannouncer

Reputation: 1218

you could also try:

Foo.__annotations__

Which would be a dictionary of field name to field type.

{'bar': typing.List[int]}

Upvotes: 1

Konrad Hałas
Konrad Hałas

Reputation: 5162

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'>,)

Upvotes: 5

Related Questions