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
Feature or enhancement
Proposal:
annotationlibimplements an optimization to resolve forward references inForwardRef.evaluate(), by doing a simple lookup in the namespace:cpython/Lib/annotationlib.py
Lines 193 to 210 in 112560e
This gives slightly inconsistent results with lazy imports that fail to resolve:
I'm wondering if for
A, it should instead wrapa's annotation in aForwardRef, so that users can then callevaluate()on it (e.g. withFormat.VALUE) so that the exception fromlazy_modgets raised accordingly. Alternatively, the lazy import instance could be kept as is, but it would be great to document theresolve()method ontypes.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
ForwarRef.evaluate()#156940