[New-bugs-announce] [issue44926] typing.get_type_hints() raises for type aliases with forward references

Maximilian Hils report at bugs.python.org
Mon Aug 16 13:15:16 EDT 2021


New submission from Maximilian Hils <python-bugs at maximilianhils.com>:

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.

----------
components: Library (Lib)
messages: 399660
nosy: mhils
priority: normal
severity: normal
status: open
title: typing.get_type_hints() raises for type aliases with forward references
type: crash
versions: Python 3.10, Python 3.7, Python 3.8, Python 3.9

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44926>
_______________________________________


More information about the New-bugs-announce mailing list