Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get type information about dataclass fields

Tags:

python

typing

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)

?

like image 466
bux Avatar asked Nov 15 '25 10:11

bux


1 Answers

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'>,)
like image 75
Konrad Hałas Avatar answered Nov 17 '25 09:11

Konrad Hałas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!