Skip to content

Lazy imports and resolving type hints #156924

Description

@Viicos

Feature or enhancement

Proposal:

annotationlib implements an optimization to resolve forward references in ForwardRef.evaluate(), by doing a simple lookup in the namespace:

if arg.isidentifier() and not keyword.iskeyword(arg):
if arg in locals:
return locals[arg]
elif arg in globals:
return globals[arg]
elif hasattr(builtins, arg):
return getattr(builtins, arg)
elif is_forwardref_format:
return self
else:
raise NameError(_NAME_ERROR_MSG.format(name=arg), name=arg)
else:
code = self.__forward_code__
try:
return eval(code, globals=globals, locals=locals)
except Exception:
if not is_forwardref_format:
raise

This gives slightly inconsistent results with lazy imports that fail to resolve:

# lazy_mod.py

Alias = list

raise Exception()
from annotationlib import Format, get_annotations

lazy from lazy_mod import Alias

class A:
    a: Alias

class B:
    a: Alias[int]

get_annotations(A, format=Format.FORWARDREF)
#> {'a': <lazy_import 'failing_mod.Alias'>}
get_annotations(B, format=Format.FORWARDREF)
#> {'a': ForwardRef('Alias[int]', is_class=True, owner=<class '__main__.B'>)}

I'm wondering if for A, it should instead wrap a's annotation in a ForwardRef, so that users can then call evaluate() on it (e.g. with Format.VALUE) so that the exception from lazy_mod gets raised accordingly. Alternatively, the lazy import instance could be kept as is, but it would be great to document the resolve() method on types.LazyImportType.

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

No response

Linked PRs

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions