[issue39442] from __future__ import annotations makes dataclasses.Field.type a string, not type
Marco Barisione
report at bugs.python.org
Fri Apr 8 04:18:41 EDT 2022
Marco Barisione <marco at barisione.org> added the comment:
This is particularly annoying if you are using `Annotated` with a dataclass.
For instance:
```
from __future__ import annotations
import dataclasses
from typing import Annotated, get_type_hints
@dataclasses.dataclass
class C:
v: Annotated[int, "foo"]
v_type = dataclasses.fields(C)[0].type
print(repr(v_type)) # "Annotated[int, 'foo']"
print(repr(get_type_hints(C)["v"])) # <class 'int'>
print(repr(eval(v_type))) # typing.Annotated[int, 'foo']
```
In the code above it looks like the only way to get the `Annotated` so you get get its args is using `eval`. The problem is that, in non-trivial, examples, `eval` would not be simple to use as you need to consider globals and locals, see https://peps.python.org/pep-0563/#resolving-type-hints-at-runtime.
----------
nosy: +barisione
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue39442>
_______________________________________
More information about the Python-bugs-list
mailing list