LoLBench / cpython_12 /tests /private /eval_tests.patch
lolbench26's picture
Publish LoLBench Harbor tasks from artifact branch (part 2)
a4edccc verified
Raw History Blame Contribute Delete
57.8 kB
diff --git a/Lib/test/test_annotationlib.py b/Lib/test/test_annotationlib.py
new file mode 100644
index 0000000..e6cd7b3
--- /dev/null
+++ b/Lib/test/test_annotationlib.py
@@ -0,0 +1,771 @@
+"""Tests for the annotations module."""
+
+import annotationlib
+import functools
+import pickle
+import unittest
+from typing import Unpack
+
+from test.test_inspect import inspect_stock_annotations
+from test.test_inspect import inspect_stringized_annotations
+from test.test_inspect import inspect_stringized_annotations_2
+from test.test_inspect import inspect_stringized_annotations_pep695
+
+
+def times_three(fn):
+ @functools.wraps(fn)
+ def wrapper(a, b):
+ return fn(a * 3, b * 3)
+
+ return wrapper
+
+
+class TestFormat(unittest.TestCase):
+ def test_enum(self):
+ self.assertEqual(annotationlib.Format.VALUE.value, 1)
+ self.assertEqual(annotationlib.Format.VALUE, 1)
+
+ self.assertEqual(annotationlib.Format.FORWARDREF.value, 2)
+ self.assertEqual(annotationlib.Format.FORWARDREF, 2)
+
+ self.assertEqual(annotationlib.Format.SOURCE.value, 3)
+ self.assertEqual(annotationlib.Format.SOURCE, 3)
+
+
+class TestForwardRefFormat(unittest.TestCase):
+ def test_closure(self):
+ def inner(arg: x):
+ pass
+
+ anno = annotationlib.get_annotations(
+ inner, format=annotationlib.Format.FORWARDREF
+ )
+ fwdref = anno["arg"]
+ self.assertIsInstance(fwdref, annotationlib.ForwardRef)
+ self.assertEqual(fwdref.__forward_arg__, "x")
+ with self.assertRaises(NameError):
+ fwdref.evaluate()
+
+ x = 1
+ self.assertEqual(fwdref.evaluate(), x)
+
+ anno = annotationlib.get_annotations(
+ inner, format=annotationlib.Format.FORWARDREF
+ )
+ self.assertEqual(anno["arg"], x)
+
+ def test_function(self):
+ def f(x: int, y: doesntexist):
+ pass
+
+ anno = annotationlib.get_annotations(f, format=annotationlib.Format.FORWARDREF)
+ self.assertIs(anno["x"], int)
+ fwdref = anno["y"]
+ self.assertIsInstance(fwdref, annotationlib.ForwardRef)
+ self.assertEqual(fwdref.__forward_arg__, "doesntexist")
+ with self.assertRaises(NameError):
+ fwdref.evaluate()
+ self.assertEqual(fwdref.evaluate(globals={"doesntexist": 1}), 1)
+
+
+class TestSourceFormat(unittest.TestCase):
+ def test_closure(self):
+ x = 0
+
+ def inner(arg: x):
+ pass
+
+ anno = annotationlib.get_annotations(inner, format=annotationlib.Format.SOURCE)
+ self.assertEqual(anno, {"arg": "x"})
+
+ def test_function(self):
+ def f(x: int, y: doesntexist):
+ pass
+
+ anno = annotationlib.get_annotations(f, format=annotationlib.Format.SOURCE)
+ self.assertEqual(anno, {"x": "int", "y": "doesntexist"})
+
+ def test_expressions(self):
+ def f(
+ add: a + b,
+ sub: a - b,
+ mul: a * b,
+ matmul: a @ b,
+ truediv: a / b,
+ mod: a % b,
+ lshift: a << b,
+ rshift: a >> b,
+ or_: a | b,
+ xor: a ^ b,
+ and_: a & b,
+ floordiv: a // b,
+ pow_: a**b,
+ lt: a < b,
+ le: a <= b,
+ eq: a == b,
+ ne: a != b,
+ gt: a > b,
+ ge: a >= b,
+ invert: ~a,
+ neg: -a,
+ pos: +a,
+ getitem: a[b],
+ getattr: a.b,
+ call: a(b, *c, d=e), # **kwargs are not supported
+ *args: *a,
+ ):
+ pass
+
+ anno = annotationlib.get_annotations(f, format=annotationlib.Format.SOURCE)
+ self.assertEqual(
+ anno,
+ {
+ "add": "a + b",
+ "sub": "a - b",
+ "mul": "a * b",
+ "matmul": "a @ b",
+ "truediv": "a / b",
+ "mod": "a % b",
+ "lshift": "a << b",
+ "rshift": "a >> b",
+ "or_": "a | b",
+ "xor": "a ^ b",
+ "and_": "a & b",
+ "floordiv": "a // b",
+ "pow_": "a ** b",
+ "lt": "a < b",
+ "le": "a <= b",
+ "eq": "a == b",
+ "ne": "a != b",
+ "gt": "a > b",
+ "ge": "a >= b",
+ "invert": "~a",
+ "neg": "-a",
+ "pos": "+a",
+ "getitem": "a[b]",
+ "getattr": "a.b",
+ "call": "a(b, *c, d=e)",
+ "args": "*a",
+ },
+ )
+
+ def test_reverse_ops(self):
+ def f(
+ radd: 1 + a,
+ rsub: 1 - a,
+ rmul: 1 * a,
+ rmatmul: 1 @ a,
+ rtruediv: 1 / a,
+ rmod: 1 % a,
+ rlshift: 1 << a,
+ rrshift: 1 >> a,
+ ror: 1 | a,
+ rxor: 1 ^ a,
+ rand: 1 & a,
+ rfloordiv: 1 // a,
+ rpow: 1**a,
+ ):
+ pass
+
+ anno = annotationlib.get_annotations(f, format=annotationlib.Format.SOURCE)
+ self.assertEqual(
+ anno,
+ {
+ "radd": "1 + a",
+ "rsub": "1 - a",
+ "rmul": "1 * a",
+ "rmatmul": "1 @ a",
+ "rtruediv": "1 / a",
+ "rmod": "1 % a",
+ "rlshift": "1 << a",
+ "rrshift": "1 >> a",
+ "ror": "1 | a",
+ "rxor": "1 ^ a",
+ "rand": "1 & a",
+ "rfloordiv": "1 // a",
+ "rpow": "1 ** a",
+ },
+ )
+
+ def test_nested_expressions(self):
+ def f(
+ nested: list[Annotated[set[int], "set of ints", 4j]],
+ set: {a + b}, # single element because order is not guaranteed
+ dict: {a + b: c + d, "key": e + g},
+ list: [a, b, c],
+ tuple: (a, b, c),
+ slice: (a[b:c], a[b:c:d], a[:c], a[b:], a[:], a[::d], a[b::d]),
+ extended_slice: a[:, :, c:d],
+ unpack1: [*a],
+ unpack2: [*a, b, c],
+ ):
+ pass
+
+ anno = annotationlib.get_annotations(f, format=annotationlib.Format.SOURCE)
+ self.assertEqual(
+ anno,
+ {
+ "nested": "list[Annotated[set[int], 'set of ints', 4j]]",
+ "set": "{a + b}",
+ "dict": "{a + b: c + d, 'key': e + g}",
+ "list": "[a, b, c]",
+ "tuple": "(a, b, c)",
+ "slice": "(a[b:c], a[b:c:d], a[:c], a[b:], a[:], a[::d], a[b::d])",
+ "extended_slice": "a[:, :, c:d]",
+ "unpack1": "[*a]",
+ "unpack2": "[*a, b, c]",
+ },
+ )
+
+ def test_unsupported_operations(self):
+ format_msg = "Cannot stringify annotation containing string formatting"
+
+ def f(fstring: f"{a}"):
+ pass
+
+ with self.assertRaises(TypeError):
+ annotationlib.get_annotations(f, format=annotationlib.Format.SOURCE)
+
+ def f(fstring_format: f"{a:02d}"):
+ pass
+
+ with self.assertRaises(TypeError):
+ annotationlib.get_annotations(f, format=annotationlib.Format.SOURCE)
+
+
+class TestForwardRefClass(unittest.TestCase):
+ def test_special_attrs(self):
+ # Forward refs provide a different introspection API. __name__ and
+ # __qualname__ make little sense for forward refs as they can store
+ # complex typing expressions.
+ fr = annotationlib.ForwardRef("set[Any]")
+ self.assertFalse(hasattr(fr, "__name__"))
+ self.assertFalse(hasattr(fr, "__qualname__"))
+ self.assertEqual(fr.__module__, "annotationlib")
+ # Forward refs are currently unpicklable once they contain a code object.
+ fr.__forward_code__ # fill the cache
+ for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+ with self.assertRaises(TypeError):
+ pickle.dumps(fr, proto)
+
+
+class TestGetAnnotations(unittest.TestCase):
+ def test_builtin_type(self):
+ self.assertEqual(annotationlib.get_annotations(int), {})
+ self.assertEqual(annotationlib.get_annotations(object), {})
+
+ def test_custom_metaclass(self):
+ class Meta(type):
+ pass
+
+ class C(metaclass=Meta):
+ x: int
+
+ self.assertEqual(annotationlib.get_annotations(C), {"x": int})
+
+ def test_missing_dunder_dict(self):
+ class NoDict(type):
+ @property
+ def __dict__(cls):
+ raise AttributeError
+
+ b: str
+
+ class C1(metaclass=NoDict):
+ a: int
+
+ self.assertEqual(annotationlib.get_annotations(C1), {"a": int})
+ self.assertEqual(
+ annotationlib.get_annotations(C1, format=annotationlib.Format.FORWARDREF),
+ {"a": int},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(C1, format=annotationlib.Format.SOURCE),
+ {"a": "int"},
+ )
+ self.assertEqual(annotationlib.get_annotations(NoDict), {"b": str})
+ self.assertEqual(
+ annotationlib.get_annotations(NoDict, format=annotationlib.Format.FORWARDREF),
+ {"b": str},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(NoDict, format=annotationlib.Format.SOURCE),
+ {"b": "str"},
+ )
+
+ def test_format(self):
+ def f1(a: int):
+ pass
+
+ def f2(a: undefined):
+ pass
+
+ self.assertEqual(
+ annotationlib.get_annotations(f1, format=annotationlib.Format.VALUE),
+ {"a": int},
+ )
+ self.assertEqual(annotationlib.get_annotations(f1, format=1), {"a": int})
+
+ fwd = annotationlib.ForwardRef("undefined")
+ self.assertEqual(
+ annotationlib.get_annotations(f2, format=annotationlib.Format.FORWARDREF),
+ {"a": fwd},
+ )
+ self.assertEqual(annotationlib.get_annotations(f2, format=2), {"a": fwd})
+
+ self.assertEqual(
+ annotationlib.get_annotations(f1, format=annotationlib.Format.SOURCE),
+ {"a": "int"},
+ )
+ self.assertEqual(annotationlib.get_annotations(f1, format=3), {"a": "int"})
+
+ with self.assertRaises(ValueError):
+ annotationlib.get_annotations(f1, format=0)
+
+ with self.assertRaises(ValueError):
+ annotationlib.get_annotations(f1, format=4)
+
+ def test_custom_object_with_annotations(self):
+ class C:
+ def __init__(self):
+ self.__annotations__ = {"x": int, "y": str}
+
+ self.assertEqual(annotationlib.get_annotations(C()), {"x": int, "y": str})
+
+ def test_custom_format_eval_str(self):
+ def foo():
+ pass
+
+ with self.assertRaises(ValueError):
+ annotationlib.get_annotations(
+ foo, format=annotationlib.Format.FORWARDREF, eval_str=True
+ )
+ annotationlib.get_annotations(
+ foo, format=annotationlib.Format.SOURCE, eval_str=True
+ )
+
+ def test_stock_annotations(self):
+ def foo(a: int, b: str):
+ pass
+
+ for format in (annotationlib.Format.VALUE, annotationlib.Format.FORWARDREF):
+ with self.subTest(format=format):
+ self.assertEqual(
+ annotationlib.get_annotations(foo, format=format),
+ {"a": int, "b": str},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(foo, format=annotationlib.Format.SOURCE),
+ {"a": "int", "b": "str"},
+ )
+
+ foo.__annotations__ = {"a": "foo", "b": "str"}
+ for format in annotationlib.Format:
+ with self.subTest(format=format):
+ self.assertEqual(
+ annotationlib.get_annotations(foo, format=format),
+ {"a": "foo", "b": "str"},
+ )
+
+ self.assertEqual(
+ annotationlib.get_annotations(foo, eval_str=True, locals=locals()),
+ {"a": foo, "b": str},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(foo, eval_str=True, globals=locals()),
+ {"a": foo, "b": str},
+ )
+
+ def test_stock_annotations_in_module(self):
+ isa = inspect_stock_annotations
+
+ for kwargs in [
+ {},
+ {"eval_str": False},
+ {"format": annotationlib.Format.VALUE},
+ {"format": annotationlib.Format.FORWARDREF},
+ {"format": annotationlib.Format.VALUE, "eval_str": False},
+ {"format": annotationlib.Format.FORWARDREF, "eval_str": False},
+ ]:
+ with self.subTest(**kwargs):
+ self.assertEqual(
+ annotationlib.get_annotations(isa, **kwargs), {"a": int, "b": str}
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.MyClass, **kwargs),
+ {"a": int, "b": str},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function, **kwargs),
+ {"a": int, "b": str, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function2, **kwargs),
+ {"a": int, "b": "str", "c": isa.MyClass, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function3, **kwargs),
+ {"a": "int", "b": "str", "c": "MyClass"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(annotationlib, **kwargs), {}
+ ) # annotations module has no annotations
+ self.assertEqual(
+ annotationlib.get_annotations(isa.UnannotatedClass, **kwargs), {}
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.unannotated_function, **kwargs),
+ {},
+ )
+
+ for kwargs in [
+ {"eval_str": True},
+ {"format": annotationlib.Format.VALUE, "eval_str": True},
+ ]:
+ with self.subTest(**kwargs):
+ self.assertEqual(
+ annotationlib.get_annotations(isa, **kwargs), {"a": int, "b": str}
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.MyClass, **kwargs),
+ {"a": int, "b": str},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function, **kwargs),
+ {"a": int, "b": str, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function2, **kwargs),
+ {"a": int, "b": str, "c": isa.MyClass, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function3, **kwargs),
+ {"a": int, "b": str, "c": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(annotationlib, **kwargs), {}
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.UnannotatedClass, **kwargs), {}
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.unannotated_function, **kwargs),
+ {},
+ )
+
+ self.assertEqual(
+ annotationlib.get_annotations(isa, format=annotationlib.Format.SOURCE),
+ {"a": "int", "b": "str"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(
+ isa.MyClass, format=annotationlib.Format.SOURCE
+ ),
+ {"a": "int", "b": "str"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(
+ isa.function, format=annotationlib.Format.SOURCE
+ ),
+ {"a": "int", "b": "str", "return": "MyClass"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(
+ isa.function2, format=annotationlib.Format.SOURCE
+ ),
+ {"a": "int", "b": "str", "c": "MyClass", "return": "MyClass"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(
+ isa.function3, format=annotationlib.Format.SOURCE
+ ),
+ {"a": "int", "b": "str", "c": "MyClass"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(
+ annotationlib, format=annotationlib.Format.SOURCE
+ ),
+ {},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(
+ isa.UnannotatedClass, format=annotationlib.Format.SOURCE
+ ),
+ {},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(
+ isa.unannotated_function, format=annotationlib.Format.SOURCE
+ ),
+ {},
+ )
+
+ def test_stock_annotations_on_wrapper(self):
+ isa = inspect_stock_annotations
+
+ wrapped = times_three(isa.function)
+ self.assertEqual(wrapped(1, "x"), isa.MyClass(3, "xxx"))
+ self.assertIsNot(wrapped.__globals__, isa.function.__globals__)
+ self.assertEqual(
+ annotationlib.get_annotations(wrapped),
+ {"a": int, "b": str, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(
+ wrapped, format=annotationlib.Format.FORWARDREF
+ ),
+ {"a": int, "b": str, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(wrapped, format=annotationlib.Format.SOURCE),
+ {"a": "int", "b": "str", "return": "MyClass"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(wrapped, eval_str=True),
+ {"a": int, "b": str, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(wrapped, eval_str=False),
+ {"a": int, "b": str, "return": isa.MyClass},
+ )
+
+ def test_stringized_annotations_in_module(self):
+ isa = inspect_stringized_annotations
+ for kwargs in [
+ {},
+ {"eval_str": False},
+ {"format": annotationlib.Format.VALUE},
+ {"format": annotationlib.Format.FORWARDREF},
+ {"format": annotationlib.Format.SOURCE},
+ {"format": annotationlib.Format.VALUE, "eval_str": False},
+ {"format": annotationlib.Format.FORWARDREF, "eval_str": False},
+ {"format": annotationlib.Format.SOURCE, "eval_str": False},
+ ]:
+ with self.subTest(**kwargs):
+ self.assertEqual(
+ annotationlib.get_annotations(isa, **kwargs),
+ {"a": "int", "b": "str"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.MyClass, **kwargs),
+ {"a": "int", "b": "str"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function, **kwargs),
+ {"a": "int", "b": "str", "return": "MyClass"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function2, **kwargs),
+ {"a": "int", "b": "'str'", "c": "MyClass", "return": "MyClass"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function3, **kwargs),
+ {"a": "'int'", "b": "'str'", "c": "'MyClass'"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.UnannotatedClass, **kwargs), {}
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.unannotated_function, **kwargs),
+ {},
+ )
+
+ for kwargs in [
+ {"eval_str": True},
+ {"format": annotationlib.Format.VALUE, "eval_str": True},
+ ]:
+ with self.subTest(**kwargs):
+ self.assertEqual(
+ annotationlib.get_annotations(isa, **kwargs), {"a": int, "b": str}
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.MyClass, **kwargs),
+ {"a": int, "b": str},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function, **kwargs),
+ {"a": int, "b": str, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function2, **kwargs),
+ {"a": int, "b": "str", "c": isa.MyClass, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.function3, **kwargs),
+ {"a": "int", "b": "str", "c": "MyClass"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.UnannotatedClass, **kwargs), {}
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(isa.unannotated_function, **kwargs),
+ {},
+ )
+
+ def test_stringized_annotations_in_empty_module(self):
+ isa2 = inspect_stringized_annotations_2
+ self.assertEqual(annotationlib.get_annotations(isa2), {})
+ self.assertEqual(annotationlib.get_annotations(isa2, eval_str=True), {})
+ self.assertEqual(annotationlib.get_annotations(isa2, eval_str=False), {})
+
+ def test_stringized_annotations_on_wrapper(self):
+ isa = inspect_stringized_annotations
+ wrapped = times_three(isa.function)
+ self.assertEqual(wrapped(1, "x"), isa.MyClass(3, "xxx"))
+ self.assertIsNot(wrapped.__globals__, isa.function.__globals__)
+ self.assertEqual(
+ annotationlib.get_annotations(wrapped),
+ {"a": "int", "b": "str", "return": "MyClass"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(wrapped, eval_str=True),
+ {"a": int, "b": str, "return": isa.MyClass},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(wrapped, eval_str=False),
+ {"a": "int", "b": "str", "return": "MyClass"},
+ )
+
+ def test_stringized_annotations_on_class(self):
+ isa = inspect_stringized_annotations
+ # test that local namespace lookups work
+ self.assertEqual(
+ annotationlib.get_annotations(isa.MyClassWithLocalAnnotations),
+ {"x": "mytype"},
+ )
+ self.assertEqual(
+ annotationlib.get_annotations(
+ isa.MyClassWithLocalAnnotations, eval_str=True
+ ),
+ {"x": int},
+ )
+
+ def test_modify_annotations(self):
+ def f(x: int):
+ pass
+
+ self.assertEqual(annotationlib.get_annotations(f), {"x": int})
+ self.assertEqual(
+ annotationlib.get_annotations(f, format=annotationlib.Format.FORWARDREF),
+ {"x": int},
+ )
+
+ f.__annotations__["x"] = str
+ # The modification is reflected in VALUE (the default)
+ self.assertEqual(annotationlib.get_annotations(f), {"x": str})
+ # ... but not in FORWARDREF, which uses __annotate__
+ self.assertEqual(
+ annotationlib.get_annotations(f, format=annotationlib.Format.FORWARDREF),
+ {"x": int},
+ )
+
+ def test_pep695_generic_class_with_future_annotations(self):
+ ann_module695 = inspect_stringized_annotations_pep695
+ A_annotations = annotationlib.get_annotations(ann_module695.A, eval_str=True)
+ A_type_params = ann_module695.A.__type_params__
+ self.assertIs(A_annotations["x"], A_type_params[0])
+ self.assertEqual(A_annotations["y"].__args__[0], Unpack[A_type_params[1]])
+ self.assertIs(A_annotations["z"].__args__[0], A_type_params[2])
+
+ def test_pep695_generic_class_with_future_annotations_and_local_shadowing(self):
+ B_annotations = annotationlib.get_annotations(
+ inspect_stringized_annotations_pep695.B, eval_str=True
+ )
+ self.assertEqual(B_annotations, {"x": int, "y": str, "z": bytes})
+
+ def test_pep695_generic_class_with_future_annotations_name_clash_with_global_vars(self):
+ ann_module695 = inspect_stringized_annotations_pep695
+ C_annotations = annotationlib.get_annotations(ann_module695.C, eval_str=True)
+ self.assertEqual(
+ set(C_annotations.values()),
+ set(ann_module695.C.__type_params__)
+ )
+
+ def test_pep_695_generic_function_with_future_annotations(self):
+ ann_module695 = inspect_stringized_annotations_pep695
+ generic_func_annotations = annotationlib.get_annotations(
+ ann_module695.generic_function, eval_str=True
+ )
+ func_t_params = ann_module695.generic_function.__type_params__
+ self.assertEqual(
+ generic_func_annotations.keys(), {"x", "y", "z", "zz", "return"}
+ )
+ self.assertIs(generic_func_annotations["x"], func_t_params[0])
+ self.assertEqual(generic_func_annotations["y"], Unpack[func_t_params[1]])
+ self.assertIs(generic_func_annotations["z"].__origin__, func_t_params[2])
+ self.assertIs(generic_func_annotations["zz"].__origin__, func_t_params[2])
+
+ def test_pep_695_generic_function_with_future_annotations_name_clash_with_global_vars(self):
+ self.assertEqual(
+ set(
+ annotationlib.get_annotations(
+ inspect_stringized_annotations_pep695.generic_function_2,
+ eval_str=True
+ ).values()
+ ),
+ set(
+ inspect_stringized_annotations_pep695.generic_function_2.__type_params__
+ )
+ )
+
+ def test_pep_695_generic_method_with_future_annotations(self):
+ ann_module695 = inspect_stringized_annotations_pep695
+ generic_method_annotations = annotationlib.get_annotations(
+ ann_module695.D.generic_method, eval_str=True
+ )
+ params = {
+ param.__name__: param
+ for param in ann_module695.D.generic_method.__type_params__
+ }
+ self.assertEqual(
+ generic_method_annotations,
+ {"x": params["Foo"], "y": params["Bar"], "return": None}
+ )
+
+ def test_pep_695_generic_method_with_future_annotations_name_clash_with_global_vars(self):
+ self.assertEqual(
+ set(
+ annotationlib.get_annotations(
+ inspect_stringized_annotations_pep695.D.generic_method_2,
+ eval_str=True
+ ).values()
+ ),
+ set(
+ inspect_stringized_annotations_pep695.D.generic_method_2.__type_params__
+ )
+ )
+
+ def test_pep_695_generic_method_with_future_annotations_name_clash_with_global_and_local_vars(self):
+ self.assertEqual(
+ annotationlib.get_annotations(
+ inspect_stringized_annotations_pep695.E, eval_str=True
+ ),
+ {"x": str},
+ )
+
+ def test_pep_695_generics_with_future_annotations_nested_in_function(self):
+ results = inspect_stringized_annotations_pep695.nested()
+
+ self.assertEqual(
+ set(results.F_annotations.values()),
+ set(results.F.__type_params__)
+ )
+ self.assertEqual(
+ set(results.F_meth_annotations.values()),
+ set(results.F.generic_method.__type_params__)
+ )
+ self.assertNotEqual(
+ set(results.F_meth_annotations.values()),
+ set(results.F.__type_params__)
+ )
+ self.assertEqual(
+ set(results.F_meth_annotations.values()).intersection(results.F.__type_params__),
+ set()
+ )
+
+ self.assertEqual(results.G_annotations, {"x": str})
+
+ self.assertEqual(
+ set(results.generic_func_annotations.values()),
+ set(results.generic_func.__type_params__)
+ )
diff --git a/Lib/test/test_dataclasses/__init__.py b/Lib/test/test_dataclasses/__init__.py
index ffb8bbe75c..b93c99d8c9 100644
--- a/Lib/test/test_dataclasses/__init__.py
+++ b/Lib/test/test_dataclasses/__init__.py
@@ -4807,6 +4807,16 @@ def test_make_dataclass(self):
self.assertTrue(fields(B)[0].kw_only)
self.assertFalse(fields(B)[1].kw_only)
+ def test_deferred_annotations(self):
+ @dataclass
+ class A:
+ x: undefined
+ y: ClassVar[undefined]
+
+ fs = fields(A)
+ self.assertEqual(len(fs), 1)
+ self.assertEqual(fs[0].name, 'x')
+
if __name__ == '__main__':
unittest.main()
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index 492a16a8c7..837f3795f0 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -741,6 +741,26 @@ def wrapper(*args): pass
self.assertEqual(wrapper.__annotations__, {})
self.assertEqual(wrapper.__type_params__, ())
+ def test_update_wrapper_annotations(self):
+ def inner(x: int): pass
+ def wrapper(*args): pass
+
+ functools.update_wrapper(wrapper, inner)
+ self.assertEqual(wrapper.__annotations__, {'x': int})
+ self.assertIs(wrapper.__annotate__, inner.__annotate__)
+
+ def with_forward_ref(x: undefined): pass
+ def wrapper(*args): pass
+
+ functools.update_wrapper(wrapper, with_forward_ref)
+
+ self.assertIs(wrapper.__annotate__, with_forward_ref.__annotate__)
+ with self.assertRaises(NameError):
+ wrapper.__annotations__
+
+ undefined = str
+ self.assertEqual(wrapper.__annotations__, {'x': undefined})
+
class TestWraps(TestUpdateWrapper):
@@ -3059,6 +3079,27 @@ def _(arg: typing.List[float] | bytes):
self.assertEqual(f(""), "default")
self.assertEqual(f(b""), "default")
+ def test_forward_reference(self):
+ @functools.singledispatch
+ def f(arg, arg2=None):
+ return "default"
+
+ @f.register
+ def _(arg: str, arg2: undefined = None):
+ return "forward reference"
+
+ self.assertEqual(f(1), "default")
+ self.assertEqual(f(""), "forward reference")
+
+ def test_unresolved_forward_reference(self):
+ @functools.singledispatch
+ def f(arg):
+ return "default"
+
+ with self.assertRaises(TypeError):
+ @f.register
+ def _(arg: undefined):
+ return "forward reference"
class CachedCostItem:
_cost = 1
diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py
index 5b7a639c02..6a841587f4 100644
--- a/Lib/test/test_grammar.py
+++ b/Lib/test/test_grammar.py
@@ -3,6 +3,7 @@
from test.support import check_syntax_error
from test.support import import_helper
+import annotationlib
import inspect
import unittest
import sys
@@ -459,7 +460,7 @@ def test_var_annot_simple_exec(self):
gns = {}; lns = {}
exec("'docstring'\n"
"x: int = 5\n", gns, lns)
- self.assertEqual(lns["__annotate__"](1), {'x': int})
+ self.assertEqual(lns["__annotate__"](annotationlib.Format.VALUE), {'x': int})
with self.assertRaises(KeyError):
gns['__annotate__']
diff --git a/Lib/test/test_inspect/test_inspect.py b/Lib/test/test_inspect/test_inspect.py
index d39c3ccdc8..5521528a52 100644
--- a/Lib/test/test_inspect/test_inspect.py
+++ b/Lib/test/test_inspect/test_inspect.py
@@ -45,10 +45,7 @@
from test.test_inspect import inspect_fodder as mod
from test.test_inspect import inspect_fodder2 as mod2
-from test.test_inspect import inspect_stock_annotations
from test.test_inspect import inspect_stringized_annotations
-from test.test_inspect import inspect_stringized_annotations_2
-from test.test_inspect import inspect_stringized_annotations_pep695
# Functions tested in this suite:
@@ -126,7 +123,7 @@ def istest(self, predicate, exp):
self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp))
def test__all__(self):
- support.check__all__(self, inspect, not_exported=("modulesbyfile",))
+ support.check__all__(self, inspect, not_exported=("modulesbyfile",), extra=("get_annotations",))
def generator_function_example(self):
for i in range(2):
@@ -1595,216 +1592,6 @@ class C(metaclass=M):
attrs = [a[0] for a in inspect.getmembers(C)]
self.assertNotIn('missing', attrs)
- def test_get_annotations_with_stock_annotations(self):
- def foo(a:int, b:str): pass
- self.assertEqual(inspect.get_annotations(foo), {'a': int, 'b': str})
-
- foo.__annotations__ = {'a': 'foo', 'b':'str'}
- self.assertEqual(inspect.get_annotations(foo), {'a': 'foo', 'b': 'str'})
-
- self.assertEqual(inspect.get_annotations(foo, eval_str=True, locals=locals()), {'a': foo, 'b': str})
- self.assertEqual(inspect.get_annotations(foo, eval_str=True, globals=locals()), {'a': foo, 'b': str})
-
- isa = inspect_stock_annotations
- self.assertEqual(inspect.get_annotations(isa), {'a': int, 'b': str})
- self.assertEqual(inspect.get_annotations(isa.MyClass), {'a': int, 'b': str})
- self.assertEqual(inspect.get_annotations(isa.function), {'a': int, 'b': str, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(isa.function2), {'a': int, 'b': 'str', 'c': isa.MyClass, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(isa.function3), {'a': 'int', 'b': 'str', 'c': 'MyClass'})
- self.assertEqual(inspect.get_annotations(inspect), {}) # inspect module has no annotations
- self.assertEqual(inspect.get_annotations(isa.UnannotatedClass), {})
- self.assertEqual(inspect.get_annotations(isa.unannotated_function), {})
-
- self.assertEqual(inspect.get_annotations(isa, eval_str=True), {'a': int, 'b': str})
- self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=True), {'a': int, 'b': str})
- self.assertEqual(inspect.get_annotations(isa.function, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(isa.function2, eval_str=True), {'a': int, 'b': str, 'c': isa.MyClass, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(isa.function3, eval_str=True), {'a': int, 'b': str, 'c': isa.MyClass})
- self.assertEqual(inspect.get_annotations(inspect, eval_str=True), {})
- self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=True), {})
- self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=True), {})
-
- self.assertEqual(inspect.get_annotations(isa, eval_str=False), {'a': int, 'b': str})
- self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=False), {'a': int, 'b': str})
- self.assertEqual(inspect.get_annotations(isa.function, eval_str=False), {'a': int, 'b': str, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(isa.function2, eval_str=False), {'a': int, 'b': 'str', 'c': isa.MyClass, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(isa.function3, eval_str=False), {'a': 'int', 'b': 'str', 'c': 'MyClass'})
- self.assertEqual(inspect.get_annotations(inspect, eval_str=False), {})
- self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=False), {})
- self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=False), {})
-
- def times_three(fn):
- @functools.wraps(fn)
- def wrapper(a, b):
- return fn(a*3, b*3)
- return wrapper
-
- wrapped = times_three(isa.function)
- self.assertEqual(wrapped(1, 'x'), isa.MyClass(3, 'xxx'))
- self.assertIsNot(wrapped.__globals__, isa.function.__globals__)
- self.assertEqual(inspect.get_annotations(wrapped), {'a': int, 'b': str, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(wrapped, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(wrapped, eval_str=False), {'a': int, 'b': str, 'return': isa.MyClass})
-
- def test_get_annotations_with_stringized_annotations(self):
- isa = inspect_stringized_annotations
- self.assertEqual(inspect.get_annotations(isa), {'a': 'int', 'b': 'str'})
- self.assertEqual(inspect.get_annotations(isa.MyClass), {'a': 'int', 'b': 'str'})
- self.assertEqual(inspect.get_annotations(isa.function), {'a': 'int', 'b': 'str', 'return': 'MyClass'})
- self.assertEqual(inspect.get_annotations(isa.function2), {'a': 'int', 'b': "'str'", 'c': 'MyClass', 'return': 'MyClass'})
- self.assertEqual(inspect.get_annotations(isa.function3), {'a': "'int'", 'b': "'str'", 'c': "'MyClass'"})
- self.assertEqual(inspect.get_annotations(isa.UnannotatedClass), {})
- self.assertEqual(inspect.get_annotations(isa.unannotated_function), {})
-
- self.assertEqual(inspect.get_annotations(isa, eval_str=True), {'a': int, 'b': str})
- self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=True), {'a': int, 'b': str})
- self.assertEqual(inspect.get_annotations(isa.function, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(isa.function2, eval_str=True), {'a': int, 'b': 'str', 'c': isa.MyClass, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(isa.function3, eval_str=True), {'a': 'int', 'b': 'str', 'c': 'MyClass'})
- self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=True), {})
- self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=True), {})
-
- self.assertEqual(inspect.get_annotations(isa, eval_str=False), {'a': 'int', 'b': 'str'})
- self.assertEqual(inspect.get_annotations(isa.MyClass, eval_str=False), {'a': 'int', 'b': 'str'})
- self.assertEqual(inspect.get_annotations(isa.function, eval_str=False), {'a': 'int', 'b': 'str', 'return': 'MyClass'})
- self.assertEqual(inspect.get_annotations(isa.function2, eval_str=False), {'a': 'int', 'b': "'str'", 'c': 'MyClass', 'return': 'MyClass'})
- self.assertEqual(inspect.get_annotations(isa.function3, eval_str=False), {'a': "'int'", 'b': "'str'", 'c': "'MyClass'"})
- self.assertEqual(inspect.get_annotations(isa.UnannotatedClass, eval_str=False), {})
- self.assertEqual(inspect.get_annotations(isa.unannotated_function, eval_str=False), {})
-
- isa2 = inspect_stringized_annotations_2
- self.assertEqual(inspect.get_annotations(isa2), {})
- self.assertEqual(inspect.get_annotations(isa2, eval_str=True), {})
- self.assertEqual(inspect.get_annotations(isa2, eval_str=False), {})
-
- def times_three(fn):
- @functools.wraps(fn)
- def wrapper(a, b):
- return fn(a*3, b*3)
- return wrapper
-
- wrapped = times_three(isa.function)
- self.assertEqual(wrapped(1, 'x'), isa.MyClass(3, 'xxx'))
- self.assertIsNot(wrapped.__globals__, isa.function.__globals__)
- self.assertEqual(inspect.get_annotations(wrapped), {'a': 'int', 'b': 'str', 'return': 'MyClass'})
- self.assertEqual(inspect.get_annotations(wrapped, eval_str=True), {'a': int, 'b': str, 'return': isa.MyClass})
- self.assertEqual(inspect.get_annotations(wrapped, eval_str=False), {'a': 'int', 'b': 'str', 'return': 'MyClass'})
-
- # test that local namespace lookups work
- self.assertEqual(inspect.get_annotations(isa.MyClassWithLocalAnnotations), {'x': 'mytype'})
- self.assertEqual(inspect.get_annotations(isa.MyClassWithLocalAnnotations, eval_str=True), {'x': int})
-
- def test_pep695_generic_class_with_future_annotations(self):
- ann_module695 = inspect_stringized_annotations_pep695
- A_annotations = inspect.get_annotations(ann_module695.A, eval_str=True)
- A_type_params = ann_module695.A.__type_params__
- self.assertIs(A_annotations["x"], A_type_params[0])
- self.assertEqual(A_annotations["y"].__args__[0], Unpack[A_type_params[1]])
- self.assertIs(A_annotations["z"].__args__[0], A_type_params[2])
-
- def test_pep695_generic_class_with_future_annotations_and_local_shadowing(self):
- B_annotations = inspect.get_annotations(
- inspect_stringized_annotations_pep695.B, eval_str=True
- )
- self.assertEqual(B_annotations, {"x": int, "y": str, "z": bytes})
-
- def test_pep695_generic_class_with_future_annotations_name_clash_with_global_vars(self):
- ann_module695 = inspect_stringized_annotations_pep695
- C_annotations = inspect.get_annotations(ann_module695.C, eval_str=True)
- self.assertEqual(
- set(C_annotations.values()),
- set(ann_module695.C.__type_params__)
- )
-
- def test_pep_695_generic_function_with_future_annotations(self):
- ann_module695 = inspect_stringized_annotations_pep695
- generic_func_annotations = inspect.get_annotations(
- ann_module695.generic_function, eval_str=True
- )
- func_t_params = ann_module695.generic_function.__type_params__
- self.assertEqual(
- generic_func_annotations.keys(), {"x", "y", "z", "zz", "return"}
- )
- self.assertIs(generic_func_annotations["x"], func_t_params[0])
- self.assertEqual(generic_func_annotations["y"], Unpack[func_t_params[1]])
- self.assertIs(generic_func_annotations["z"].__origin__, func_t_params[2])
- self.assertIs(generic_func_annotations["zz"].__origin__, func_t_params[2])
-
- def test_pep_695_generic_function_with_future_annotations_name_clash_with_global_vars(self):
- self.assertEqual(
- set(
- inspect.get_annotations(
- inspect_stringized_annotations_pep695.generic_function_2,
- eval_str=True
- ).values()
- ),
- set(
- inspect_stringized_annotations_pep695.generic_function_2.__type_params__
- )
- )
-
- def test_pep_695_generic_method_with_future_annotations(self):
- ann_module695 = inspect_stringized_annotations_pep695
- generic_method_annotations = inspect.get_annotations(
- ann_module695.D.generic_method, eval_str=True
- )
- params = {
- param.__name__: param
- for param in ann_module695.D.generic_method.__type_params__
- }
- self.assertEqual(
- generic_method_annotations,
- {"x": params["Foo"], "y": params["Bar"], "return": None}
- )
-
- def test_pep_695_generic_method_with_future_annotations_name_clash_with_global_vars(self):
- self.assertEqual(
- set(
- inspect.get_annotations(
- inspect_stringized_annotations_pep695.D.generic_method_2,
- eval_str=True
- ).values()
- ),
- set(
- inspect_stringized_annotations_pep695.D.generic_method_2.__type_params__
- )
- )
-
- def test_pep_695_generic_method_with_future_annotations_name_clash_with_global_and_local_vars(self):
- self.assertEqual(
- inspect.get_annotations(
- inspect_stringized_annotations_pep695.E, eval_str=True
- ),
- {"x": str},
- )
-
- def test_pep_695_generics_with_future_annotations_nested_in_function(self):
- results = inspect_stringized_annotations_pep695.nested()
-
- self.assertEqual(
- set(results.F_annotations.values()),
- set(results.F.__type_params__)
- )
- self.assertEqual(
- set(results.F_meth_annotations.values()),
- set(results.F.generic_method.__type_params__)
- )
- self.assertNotEqual(
- set(results.F_meth_annotations.values()),
- set(results.F.__type_params__)
- )
- self.assertEqual(
- set(results.F_meth_annotations.values()).intersection(results.F.__type_params__),
- set()
- )
-
- self.assertEqual(results.G_annotations, {"x": str})
-
- self.assertEqual(
- set(results.generic_func_annotations.values()),
- set(results.generic_func.__type_params__)
- )
-
class TestFormatAnnotation(unittest.TestCase):
def test_typing_replacement(self):
diff --git a/Lib/test/test_type_annotations.py b/Lib/test/test_type_annotations.py
index a9be1f5aa8..91082e6b23 100644
--- a/Lib/test/test_type_annotations.py
+++ b/Lib/test/test_type_annotations.py
@@ -1,12 +1,9 @@
+import annotationlib
import textwrap
import types
import unittest
from test.support import run_code, check_syntax_error
-VALUE = 1
-FORWARDREF = 2
-SOURCE = 3
-
class TypeAnnotationTests(unittest.TestCase):
@@ -376,12 +373,12 @@ class X:
self.assertIsInstance(annotate, types.FunctionType)
self.assertEqual(annotate.__name__, "__annotate__")
with self.assertRaises(NotImplementedError):
- annotate(FORWARDREF)
+ annotate(annotationlib.Format.FORWARDREF)
with self.assertRaises(NotImplementedError):
- annotate(SOURCE)
+ annotate(annotationlib.Format.SOURCE)
with self.assertRaises(NotImplementedError):
annotate(None)
- self.assertEqual(annotate(VALUE), {"x": int})
+ self.assertEqual(annotate(annotationlib.Format.VALUE), {"x": int})
def test_comprehension_in_annotation(self):
# This crashed in an earlier version of the code
@@ -398,7 +395,7 @@ def f(x: int) -> int: pass
f = ns["f"]
self.assertIsInstance(f.__annotate__, types.FunctionType)
annos = {"x": "int", "return": "int"}
- self.assertEqual(f.__annotate__(VALUE), annos)
+ self.assertEqual(f.__annotate__(annotationlib.Format.VALUE), annos)
self.assertEqual(f.__annotations__, annos)
def test_name_clash_with_format(self):
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index a931da5590..290b3c63a7 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -1,3 +1,4 @@
+import annotationlib
import contextlib
import collections
import collections.abc
@@ -45,7 +46,7 @@
import weakref
import types
-from test.support import captured_stderr, cpython_only, infinite_recursion, requires_docstrings, import_helper
+from test.support import captured_stderr, cpython_only, infinite_recursion, requires_docstrings, import_helper, run_code
from test.typinganndata import ann_module695, mod_generics_cache, _typed_dict_helper
@@ -7812,6 +7813,48 @@ class XMethBad2(NamedTuple):
def _source(self):
return 'no chance for this as well'
+ def test_annotation_type_check(self):
+ # These are rejected by _type_check
+ with self.assertRaises(TypeError):
+ class X(NamedTuple):
+ a: Final
+ with self.assertRaises(TypeError):
+ class Y(NamedTuple):
+ a: (1, 2)
+
+ # Conversion by _type_convert
+ class Z(NamedTuple):
+ a: None
+ b: "str"
+ annos = {'a': type(None), 'b': ForwardRef("str")}
+ self.assertEqual(Z.__annotations__, annos)
+ self.assertEqual(Z.__annotate__(annotationlib.Format.VALUE), annos)
+ self.assertEqual(Z.__annotate__(annotationlib.Format.FORWARDREF), annos)
+ self.assertEqual(Z.__annotate__(annotationlib.Format.SOURCE), {"a": "None", "b": "str"})
+
+ def test_future_annotations(self):
+ code = """
+ from __future__ import annotations
+ from typing import NamedTuple
+ class X(NamedTuple):
+ a: int
+ b: None
+ """
+ ns = run_code(textwrap.dedent(code))
+ X = ns['X']
+ self.assertEqual(X.__annotations__, {'a': ForwardRef("int"), 'b': ForwardRef("None")})
+
+ def test_deferred_annotations(self):
+ class X(NamedTuple):
+ y: undefined
+
+ self.assertEqual(X._fields, ('y',))
+ with self.assertRaises(NameError):
+ X.__annotations__
+
+ undefined = int
+ self.assertEqual(X.__annotations__, {'y': int})
+
def test_multiple_inheritance(self):
class A:
pass
@@ -8126,7 +8169,11 @@ def test_basics_functional_syntax(self):
self.assertEqual(Emp.__name__, 'Emp')
self.assertEqual(Emp.__module__, __name__)
self.assertEqual(Emp.__bases__, (dict,))
- self.assertEqual(Emp.__annotations__, {'name': str, 'id': int})
+ annos = {'name': str, 'id': int}
+ self.assertEqual(Emp.__annotations__, annos)
+ self.assertEqual(Emp.__annotate__(annotationlib.Format.VALUE), annos)
+ self.assertEqual(Emp.__annotate__(annotationlib.Format.FORWARDREF), annos)
+ self.assertEqual(Emp.__annotate__(annotationlib.Format.SOURCE), {'name': 'str', 'id': 'int'})
self.assertEqual(Emp.__total__, True)
self.assertEqual(Emp.__required_keys__, {'name', 'id'})
self.assertIsInstance(Emp.__required_keys__, frozenset)
@@ -8487,6 +8534,8 @@ class A[T](TypedDict):
self.assertEqual(A.__bases__, (Generic, dict))
self.assertEqual(A.__orig_bases__, (TypedDict, Generic[T]))
self.assertEqual(A.__mro__, (A, Generic, dict, object))
+ self.assertEqual(A.__annotations__, {'a': T})
+ self.assertEqual(A.__annotate__(annotationlib.Format.SOURCE), {'a': 'T'})
self.assertEqual(A.__parameters__, (T,))
self.assertEqual(A[str].__parameters__, ())
self.assertEqual(A[str].__args__, (str,))
@@ -8498,6 +8547,8 @@ class A(TypedDict, Generic[T]):
self.assertEqual(A.__bases__, (Generic, dict))
self.assertEqual(A.__orig_bases__, (TypedDict, Generic[T]))
self.assertEqual(A.__mro__, (A, Generic, dict, object))
+ self.assertEqual(A.__annotations__, {'a': T})
+ self.assertEqual(A.__annotate__(annotationlib.Format.SOURCE), {'a': 'T'})
self.assertEqual(A.__parameters__, (T,))
self.assertEqual(A[str].__parameters__, ())
self.assertEqual(A[str].__args__, (str,))
@@ -8508,6 +8559,8 @@ class A2(Generic[T], TypedDict):
self.assertEqual(A2.__bases__, (Generic, dict))
self.assertEqual(A2.__orig_bases__, (Generic[T], TypedDict))
self.assertEqual(A2.__mro__, (A2, Generic, dict, object))
+ self.assertEqual(A2.__annotations__, {'a': T})
+ self.assertEqual(A2.__annotate__(annotationlib.Format.SOURCE), {'a': 'T'})
self.assertEqual(A2.__parameters__, (T,))
self.assertEqual(A2[str].__parameters__, ())
self.assertEqual(A2[str].__args__, (str,))
@@ -8518,6 +8571,8 @@ class B(A[KT], total=False):
self.assertEqual(B.__bases__, (Generic, dict))
self.assertEqual(B.__orig_bases__, (A[KT],))
self.assertEqual(B.__mro__, (B, Generic, dict, object))
+ self.assertEqual(B.__annotations__, {'a': T, 'b': KT})
+ self.assertEqual(B.__annotate__(annotationlib.Format.SOURCE), {'a': 'T', 'b': 'KT'})
self.assertEqual(B.__parameters__, (KT,))
self.assertEqual(B.__total__, False)
self.assertEqual(B.__optional_keys__, frozenset(['b']))
@@ -8542,6 +8597,11 @@ class C(B[int]):
'b': KT,
'c': int,
})
+ self.assertEqual(C.__annotate__(annotationlib.Format.SOURCE), {
+ 'a': 'T',
+ 'b': 'KT',
+ 'c': 'int',
+ })
with self.assertRaises(TypeError):
C[str]
@@ -8561,6 +8621,11 @@ class Point3D(Point2DGeneric[T], Generic[T, KT]):
'b': T,
'c': KT,
})
+ self.assertEqual(Point3D.__annotate__(annotationlib.Format.SOURCE), {
+ 'a': 'T',
+ 'b': 'T',
+ 'c': 'KT',
+ })
self.assertEqual(Point3D[int, str].__origin__, Point3D)
with self.assertRaises(TypeError):
@@ -8592,6 +8657,11 @@ class WithImplicitAny(B):
'b': KT,
'c': int,
})
+ self.assertEqual(WithImplicitAny.__annotate__(annotationlib.Format.SOURCE), {
+ 'a': 'T',
+ 'b': 'KT',
+ 'c': 'int',
+ })
with self.assertRaises(TypeError):
WithImplicitAny[str]
@@ -8748,6 +8818,54 @@ class AllTheThings(TypedDict):
},
)
+ def test_annotations(self):
+ # _type_check is applied
+ with self.assertRaisesRegex(TypeError, "Plain typing.Final is not valid as type argument"):
+ class X(TypedDict):
+ a: Final
+
+ # _type_convert is applied
+ class Y(TypedDict):
+ a: None
+ b: "int"
+ fwdref = ForwardRef('int', module='test.test_typing')
+ self.assertEqual(Y.__annotations__, {'a': type(None), 'b': fwdref})
+ self.assertEqual(Y.__annotate__(annotationlib.Format.FORWARDREF), {'a': type(None), 'b': fwdref})
+
+ # _type_check is also applied later
+ class Z(TypedDict):
+ a: undefined
+
+ with self.assertRaises(NameError):
+ Z.__annotations__
+
+ undefined = Final
+ with self.assertRaisesRegex(TypeError, "Plain typing.Final is not valid as type argument"):
+ Z.__annotations__
+
+ undefined = None
+ self.assertEqual(Z.__annotations__, {'a': type(None)})
+
+ def test_deferred_evaluation(self):
+ class A(TypedDict):
+ x: NotRequired[undefined]
+ y: ReadOnly[undefined]
+ z: Required[undefined]
+
+ self.assertEqual(A.__required_keys__, frozenset({'y', 'z'}))
+ self.assertEqual(A.__optional_keys__, frozenset({'x'}))
+ self.assertEqual(A.__readonly_keys__, frozenset({'y'}))
+ self.assertEqual(A.__mutable_keys__, frozenset({'x', 'z'}))
+
+ with self.assertRaises(NameError):
+ A.__annotations__
+
+ self.assertEqual(
+ A.__annotate__(annotationlib.Format.SOURCE),
+ {'x': 'NotRequired[undefined]', 'y': 'ReadOnly[undefined]',
+ 'z': 'Required[undefined]'},
+ )
+
class RequiredTests(BaseTestCase):
@@ -10075,7 +10193,6 @@ def test_special_attrs(self):
typing.ClassVar: 'ClassVar',
typing.Concatenate: 'Concatenate',
typing.Final: 'Final',
- typing.ForwardRef: 'ForwardRef',
typing.Literal: 'Literal',
typing.NewType: 'NewType',
typing.NoReturn: 'NoReturn',
@@ -10087,7 +10204,7 @@ def test_special_attrs(self):
typing.TypeVar: 'TypeVar',
typing.Union: 'Union',
typing.Self: 'Self',
- # Subscribed special forms
+ # Subscripted special forms
typing.Annotated[Any, "Annotation"]: 'Annotated',
typing.Annotated[int, 'Annotation']: 'Annotated',
typing.ClassVar[Any]: 'ClassVar',
@@ -10102,7 +10219,6 @@ def test_special_attrs(self):
typing.Union[Any]: 'Any',
typing.Union[int, float]: 'Union',
# Incompatible special forms (tested in test_special_attrs2)
- # - typing.ForwardRef('set[Any]')
# - typing.NewType('TypeName', Any)
# - typing.ParamSpec('SpecialAttrsP')
# - typing.TypeVar('T')
@@ -10121,18 +10237,6 @@ def test_special_attrs(self):
TypeName = typing.NewType('SpecialAttrsTests.TypeName', Any)
def test_special_attrs2(self):
- # Forward refs provide a different introspection API. __name__ and
- # __qualname__ make little sense for forward refs as they can store
- # complex typing expressions.
- fr = typing.ForwardRef('set[Any]')
- self.assertFalse(hasattr(fr, '__name__'))
- self.assertFalse(hasattr(fr, '__qualname__'))
- self.assertEqual(fr.__module__, 'typing')
- # Forward refs are currently unpicklable.
- for proto in range(pickle.HIGHEST_PROTOCOL + 1):
- with self.assertRaises(TypeError):
- pickle.dumps(fr, proto)
-
self.assertEqual(SpecialAttrsTests.TypeName.__name__, 'TypeName')
self.assertEqual(
SpecialAttrsTests.TypeName.__qualname__,