[New-bugs-announce] [issue43463] typing.get_type_hints with TYPE_CHECKING imports / getting hints for single argument

Florian Bruhin report at bugs.python.org
Wed Mar 10 09:38:41 EST 2021


New submission from Florian Bruhin <python.org at the-compiler.org>:

Consider a file such as:

    # from __future__ import annotations
    from typing import TYPE_CHECKING, Union, get_type_hints

    if TYPE_CHECKING:
        import types

    def fun(a: 'types.SimpleNamespace', b: Union[int, str]):
        pass

    print(fun.__annotations__)
    print(get_type_hints(fun))

When running this, typing.get_type_hints fails (as you would expect):

    Traceback (most recent call last):
      File "/home/florian/tmp/x.py", line 11, in <module>
        print(get_type_hints(fun))
      File "/usr/lib/python3.9/typing.py", line 1449, in get_type_hints
        value = _eval_type(value, globalns, localns)
      File "/usr/lib/python3.9/typing.py", line 283, in _eval_type
        return t._evaluate(globalns, localns, recursive_guard)
      File "/usr/lib/python3.9/typing.py", line 539, in _evaluate
        eval(self.__forward_code__, globalns, localns),
      File "<string>", line 1, in <module>
    NameError: name 'types' is not defined

However, in my case I'm not actually interested in the type of 'a', I only need the type for 'b'. Before Python 3.10 (or the __future__ import), I can do so by getting it from __annotations__ directly.

With Python 3.10 (or the __future__ import), this doesn't seem to be possible anymore - I'd need to either evaluate the 'Union[int, str]' annotation manually (perhaps calling into private typing.py functions), or maybe work around the issue by passing some magical dict-like object as local/globals which ignores the NameError. Both of those seem suboptimal.

Thus, I'd like a way to either:

1) Ignore exceptions in get_type_hints and instead get something like a typing.Unresolvable['types.SimpleNamespace'] back
2) Have something like a typing.get_argument_type_hints(fun, 'b') instead, allowing me to get the arguments one by one rather than resolving the whole thing
3) Have a public API to resolve a string type annotation (i.e. the equivalent of `typing._eval_type`)

----------
components: Library (Lib)
messages: 388436
nosy: The Compiler, gvanrossum, levkivskyi
priority: normal
severity: normal
status: open
title: typing.get_type_hints with TYPE_CHECKING imports / getting hints for single argument
type: behavior
versions: Python 3.10, Python 3.9

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


More information about the New-bugs-announce mailing list