➜

This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author mhils
Recipients mhils
Date 2021-08-16.17:15:15
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <[email protected]>
In-reply-to
Content
Someone reported this rather interesting issue where typing.get_type_hints crashes on type aliases with forward references. The original report is at https://github.com/mitmproxy/pdoc/issues/290. Here's an extended minimal example:

foo.py:
```
import typing

FooList1: typing.TypeAlias = list["Foo"]
FooList2: typing.TypeAlias = typing.List["Foo"]

class Foo:
    pass

```

bar.py:
```
import typing
import foo

def func1(x: foo.FooList1):
    pass

def func2(x: foo.FooList2):
    pass

print(typing.get_type_hints(func1))  # {'x': list['Foo']}
print(typing.get_type_hints(func2))  # NameError: name 'Foo' is not defined.

```


Observations:

1. func1 doesn't crash, but also doesn't resolve the forward reference. I am not sure if this expected behavior.
   If it isn't, this should eventually run in the same problem as func2.
2. func2 crashes because "Foo" is evaluated in the context of bar.py (where class Foo is unknown) and not in the context of foo.py. ForwardRef._evaluate would
   somehow need to know in which context it was defined. #41249 (TypedDict inheritance doesn't work with get_type_hints) introduced 
   ForwardRef.__forward_module__, which would be a logical place for that information. I'm not sure if it is a good idea
   to use __forward_module__ more widely.
3. This may end up as quite a bit of complexity for an edge case, I'm fine if it is considered wontfix. 
   The reason I'm bringing it up is that PEP 613 (Explicit Type Aliases) decidedly allows forward references in type aliases.


For the record, PEP 563 (postponed evaluations) does not change the outcome here. However, postponed evaluations often make it possible to avoid the forward references by declaring the aliases last.
History
Date User Action Args
2021-08-16 17:15:16mhilssetrecipients: + mhils
2021-08-16 17:15:16mhilssetmessageid: <[email protected]>
2021-08-16 17:15:16mhilslinkissue44926 messages
2021-08-16 17:15:15mhilscreate