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 The Compiler
Recipients The Compiler, gvanrossum, levkivskyi
Date 2021-03-10.14:38:40
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1615387121.09.0.336024174905.issue43463@roundup.psfhosted.org>
In-reply-to
Content
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`)
History
Date User Action Args
2021-03-10 14:38:41The Compilersetrecipients: + The Compiler, gvanrossum, levkivskyi
2021-03-10 14:38:41The Compilersetmessageid: <1615387121.09.0.336024174905.issue43463@roundup.psfhosted.org>
2021-03-10 14:38:41The Compilerlinkissue43463 messages
2021-03-10 14:38:40The Compilercreate