Author joperez
Recipients BTaskaya, eric.smith, gvanrossum, joperez, levkivskyi, lukasz.langa, vstinner
Date 2020-07-22.20:16:13
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1595448974.26.0.905372860878.issue41370@roundup.psfhosted.org>
In-reply-to
Content
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)
History
Date User Action Args
2020-07-22 20:16:14joperezsetrecipients: + joperez, gvanrossum, vstinner, eric.smith, lukasz.langa, levkivskyi, BTaskaya
2020-07-22 20:16:14joperezsetmessageid: <1595448974.26.0.905372860878.issue41370@roundup.psfhosted.org>
2020-07-22 20:16:14joperezlinkissue41370 messages
2020-07-22 20:16:13joperezcreate