Message374105
PEP 585 current implementation (3.10.0a0) differs from current Generic implementation about ForwardRef, as illustrated bellow:
```python
from dataclasses import dataclass, field
from typing import get_type_hints, List, ForwardRef
@dataclass
class Node:
children: list["Node"] = field(default_factory=list)
children2: List["Node"] = field(default_factory=list)
assert get_type_hints(Node) == {"children": list["Node"], "children2": List[Node]}
assert List["Node"].__args__ == (ForwardRef("Node"),)
assert list["Node"].__args__ == ("Node",) # No ForwardRef here, so no evaluation by get_type_hints
```
There is indeed no kind of ForwardRef for `list` arguments. As shown in the example, this affects the result of get_type_hints for recursive types handling.
He could be "fixed" in 2 lines in `typing._eval_type` with something like this :
```python
def _eval_type(t, globalns, localns, recursive_guard=frozenset()):
if isinstance(t, str):
t = ForwardRef(t)
if isinstance(t, ForwardRef):
...
```
but it's kind of hacky/dirty.
It's true that this issue will not concern legacy code, 3.9 still being not released. So developers of libraries using get_type_hints could add in their documentation that `from __future__ import annotations` is mandatory for recursive types with PEP 585 (I think I will do it).
By the way, Guido has quickly given his opinion about it in PR 21553: "We probably will not ever support this: importing ForwardRef from the built-in generic alias code would be problematic, and once from __future__ import annotations is always on there's no need to quote the argument anyway." (So feel free to close this issue) |
|
Date |
User |
Action |
Args |
2020-07-22 20:16:14 | joperez | set | recipients:
+ joperez, gvanrossum, vstinner, eric.smith, lukasz.langa, levkivskyi, BTaskaya |
2020-07-22 20:16:14 | joperez | set | messageid: <1595448974.26.0.905372860878.issue41370@roundup.psfhosted.org> |
2020-07-22 20:16:14 | joperez | link | issue41370 messages |
2020-07-22 20:16:13 | joperez | create | |
|