annotations cause dataclass fields type side effects

Lukas Lösche lukas at some.engineering
Mon Aug 9 08:25:27 EDT 2021


I'm on Python 3.9.6 and trying to make sense of the following behaviour:

>>> from dataclasses import dataclass, fields
>>> @dataclass
... class Foobar:
... name: str
...
>>> fields(Foobar)[0].type
<class 'str'>
>>> type(fields(Foobar)[0].type)
<class 'type'>



>>> from __future__ import annotations
>>> from dataclasses import dataclass, fields
>>>
>>> @dataclass
... class Foobar:
... name: str
...
>>> fields(Foobar)[0].type
'str'
>>> type(fields(Foobar)[0].type)
<class 'str'>

I have a validation function that checks if the types of all fields in
a dataclass are what they are supposed to be. But as soon as I import
annotations from __future__ this validation breaks as the arg that I'm
passing to isinstance() is no longer a type class but a string.

What am I doing wrong?

Thanks,
-- Lukas


More information about the Python-list mailing list