FazBrowse GitHub Viewer | Trending |
URL:
| Home
Tools: [Download Repo ZIP]   [Original HTTPS Page]

[3.15] gh-156924: Try reifying lazy imports in `ForwarRef.evaluate()` (GH-156940) by miss-islington · Pull Request #157224 · python/cpython · GitHub

Repository navigation

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension .py  (2) .rst  (1) All 2 file types selected
Viewed files
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Unified
Split
Hide whitespace
Diff view
Unified
Split
Hide whitespace
21 changes: 18 additions & 3 deletions Lib/annotationlib.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -191,12 +191,27 @@ def evaluate(

arg = self.__forward_arg__
if arg.isidentifier() and not keyword.iskeyword(arg):
resolved = _sentinel
if arg in locals:
return locals[arg]
resolved = locals[arg]
elif arg in globals:
return globals[arg]
resolved = globals[arg]
elif hasattr(builtins, arg):
return getattr(builtins, arg)
resolved = getattr(builtins, arg)

if resolved is not _sentinel:
if isinstance(resolved, types.LazyImportType):
# We try reifying the lazy object. If this fails, we propagate
# the error in the VALUE format and leave the
# ForwardRef unresolved in the FORWARDREF format.
try:
return resolved.resolve()
except Exception:
if not is_forwardref_format:
raise
return self
else:
return resolved
elif is_forwardref_format:
return self
else:
Expand Down
112 changes: 112 additions & 0 deletions Lib/test/test_annotationlib.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
Expand Up @@ -2179,6 +2179,118 @@ def test_evaluate_forwardref_format(self):
support.EqualToForwardRef('"a" + 1'),
)

def test_evaluate_lazy_import(self):
ns = {}
exec(
textwrap.dedent(
"""
lazy from test.test_lazy_import.data.basic2 import x
lazy from test.test_lazy_import.data.broken_module import y

class A:
a: x

class B:
b: y
"""
),
ns,
)
self.addCleanup(
import_helper.unload, "test.test_lazy_import.data.basic2"
)
self.addCleanup(
import_helper.unload, "test.test_lazy_import.data.broken_module"
)
self.assertIs(type(ns["x"]), types.LazyImportType)
self.assertIs(type(ns["y"]), types.LazyImportType)

# The lazy import resolves successfully:
for format in (Format.VALUE, Format.FORWARDREF):
with self.subTest(format=format):
self.assertEqual(
ForwardRef("x").evaluate(globals=ns, format=format), 42
)
self.assertEqual(
ForwardRef("x").evaluate(locals=ns, format=format), 42
)
self.assertEqual(
get_annotations(ns["A"], format=Format.FORWARDREF), {"a": 42}
)

# The lazy import fails to resolve:
fr = ForwardRef("y")
with self.assertRaisesRegex(ValueError, "always fails to import"):
fr.evaluate(globals=ns, format=Format.VALUE)
with self.assertRaisesRegex(ValueError, "always fails to import"):
fr.evaluate(locals=ns, format=Format.VALUE)
self.assertIs(fr.evaluate(globals=ns, format=Format.FORWARDREF), fr)
self.assertIs(fr.evaluate(locals=ns, format=Format.FORWARDREF), fr)

annos = get_annotations(ns["B"], format=Format.FORWARDREF)
self.assertEqual(
annos,
{"b": support.EqualToForwardRef("y", is_class=True, owner=ns["B"])},
)
with self.assertRaisesRegex(ValueError, "always fails to import"):
annos["b"].evaluate(format=Format.VALUE)
with self.assertRaisesRegex(ValueError, "always fails to import"):
get_annotations(ns["B"], format=Format.VALUE)

def test_get_annotations_lazy_import(self):
ns = {}
exec(
textwrap.dedent(
"""
lazy from test.test_lazy_import.data.basic2 import x
lazy from test.test_lazy_import.data.broken_module import y

class A:
a: object.fail
b: x

class B:
a: object.fail
b: y
"""
),
ns,
)
self.addCleanup(
import_helper.unload, "test.test_lazy_import.data.basic2"
)
self.addCleanup(
import_helper.unload, "test.test_lazy_import.data.broken_module"
)
self.assertIs(type(ns["x"]), types.LazyImportType)
self.assertIs(type(ns["y"]), types.LazyImportType)

annos = get_annotations(ns["A"], format=Format.FORWARDREF)
self.assertEqual(
annos,
{
"a": support.EqualToForwardRef(
"object.fail", is_class=True, owner=ns["A"]
),
"b": 42,
},
)

annos = get_annotations(ns["B"], format=Format.FORWARDREF)
self.assertEqual(
annos,
{
"a": support.EqualToForwardRef(
"object.fail", is_class=True, owner=ns["B"]
),
"b": support.EqualToForwardRef(
"y", is_class=True, owner=ns["B"]
),
},
)
with self.assertRaisesRegex(ValueError, "always fails to import"):
annos["b"].evaluate(format=Format.VALUE)

def test_evaluate_notimplemented_format(self):
class C:
x: alias
Expand Down
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
:meth:`annotationlib.ForwardRef.evaluate` now resolves :ref:`lazy import
<lazy-imports>` proxies found in the namespace. With
:attr:`~annotationlib.Format.FORWARDREF`, a lazy import that fails to resolve
now results in a :class:`~annotationlib.ForwardRef` instead of the
:class:`lazy import proxy <types.LazyImportType>`, and with :attr:`~annotationlib.Format.VALUE` the underlying exception is
propagated.
Loading

Back | FazBrowse Home | New Git URL