Skip to content

Commit e87dd95

Browse files
committed
Test partial evaluation of ForwardRefs in _Stringifier
1 parent 6a2fc4e commit e87dd95

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Lib/test/test_annotationlib.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,52 @@ def f(
142142
self.assertIsInstance(eta_anno, ForwardRef)
143143
self.assertEqual(eta_anno, support.EqualToForwardRef("some | ()", owner=f))
144144

145+
def test_partially_nonexistent(self):
146+
# These annotations start with a non-existent variable and then use
147+
# global types with defined values. This partially evaluates by putting
148+
# those globals into `fwdref.__extra_names__`.
149+
def f(
150+
x: obj | int,
151+
y: container[int:obj, int],
152+
z: dict_val | {str: int},
153+
alpha: set_val | {str, int},
154+
beta: obj | bool | int,
155+
gamma: obj | call_func(int, kwd=bool),
156+
):
157+
pass
158+
159+
def func(*args, **kwargs):
160+
return Union[*args, *(kwargs.values())]
161+
162+
anno = get_annotations(f, format=Format.FORWARDREF)
163+
globals_ = {
164+
"obj": str, "container": list, "dict_val": {1: 2}, "set_val": {1, 2},
165+
"call_func": func
166+
}
167+
168+
x_anno = anno["x"]
169+
self.assertIsInstance(x_anno, ForwardRef)
170+
self.assertEqual(x_anno.evaluate(globals=globals_), str | int)
171+
172+
y_anno = anno["y"]
173+
self.assertIsInstance(y_anno, ForwardRef)
174+
self.assertEqual(y_anno.evaluate(globals=globals_), list[int:str, int])
175+
176+
z_anno = anno["z"]
177+
self.assertIsInstance(z_anno, ForwardRef)
178+
self.assertEqual(z_anno.evaluate(globals=globals_), {1: 2} | {str: int})
179+
180+
alpha_anno = anno["alpha"]
181+
self.assertIsInstance(alpha_anno, ForwardRef)
182+
self.assertEqual(alpha_anno.evaluate(globals=globals_), {1, 2} | {str, int})
183+
184+
beta_anno = anno["beta"]
185+
self.assertIsInstance(beta_anno, ForwardRef)
186+
self.assertEqual(beta_anno.evaluate(globals=globals_), str | bool | int)
187+
188+
gamma_anno = anno["gamma"]
189+
self.assertIsInstance(gamma_anno, ForwardRef)
190+
self.assertEqual(gamma_anno.evaluate(globals=globals_), str | func(int, kwd=bool))
145191

146192
def test_partially_nonexistent_union(self):
147193
# Test unions with '|' syntax equal unions with typing.Union[] with some forwardrefs

0 commit comments

Comments
 (0)