{"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_22.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport sys\nimport types\nimport unittest\nfrom unittest import mock\nfrom test.support import import_module\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.6.0","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport sys\nimport types\nimport unittest\nfrom unittest import mock\nfrom test.support import import_module\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n try:\n g.__anext__().__next__()\n except StopAsyncIteration:\n res.append('STOP')\n break\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n else:\n res.append('EMPTY StopIteration')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n self.assertEqual(ai.__anext__().__next__(), ('result',))\n\n try:\n ai.__anext__().__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n self.assertEqual(ai.__anext__().__next__(), ('result',))\n\n try:\n ai.__anext__().__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n self.assertEqual(ai.__anext__().__next__(), ('result',))\n\n try:\n ai.__anext__().__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n\n self.assertTrue(inspect.isawaitable(g.aclose()))\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.6.0","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport sys\nimport types\nimport unittest\nfrom unittest import mock\nfrom test.support import import_module\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01, loop=self.loop)\n yield 2\n await asyncio.sleep(0.01, loop=self.loop)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01, loop=self.loop)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01, loop=loop)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01, loop=self.loop)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01, loop=self.loop)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n t = self.loop.create_task(it.__anext__())\n await asyncio.sleep(0.01, loop=self.loop)\n await gen.aclose()\n return t\n\n t = self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n t.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01, loop=self.loop))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n\n await asyncio.sleep(0.1, loop=self.loop)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n v = yield 1\n await asyncio.sleep(0.01, loop=self.loop)\n yield v * 2\n await asyncio.sleep(0.01, loop=self.loop)\n return\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay, loop=self.loop)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay, loop=self.loop),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01, loop=self.loop)\n yield v * 2\n await asyncio.sleep(0.01, loop=self.loop)\n # return\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay, loop=self.loop),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01, loop=self.loop)\n # return\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout, loop=self.loop)\n yield 1\n finally:\n await asyncio.sleep(0, loop=self.loop)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n self.assertEqual(finalized, 2)\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))\n\n def test_async_gen_asyncio_shutdown_02(self):\n logged = 0\n\n def logger(loop, context):\n nonlocal logged\n self.assertIn('asyncgen', context)\n expected = 'an error occurred during closing of asynchronous'\n if expected in context['message']:\n logged += 1\n\n async def waiter(timeout):\n try:\n await asyncio.sleep(timeout, loop=self.loop)\n yield 1\n finally:\n 1 / 0\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t = self.loop.create_task(wait())\n self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))\n\n self.loop.set_exception_handler(logger)\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(logged, 1)\n\n # Silence warnings\n t.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.6.0","license":"PSF-2.0"} {"cut":"val","version":"3.6","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import sys\nimport types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, ZeroDivisionError)\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, TypeError)\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.6.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_18.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"async def c(): return f'{await 1+foo()}'","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_18.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_01.py","code":"from contextvars import ContextVar\nfrom types import MappingProxyType\nimport re\nimport collections\nimport time\n\n# Okay\nContextVar(\"cv\")\nContextVar(\"cv\", default=())\nContextVar(\"cv\", default=(1, 2, 3))\nContextVar(\"cv\", default=\"foo\")\nContextVar(\"cv\", default=tuple())\nContextVar(\"cv\", default=frozenset())\nContextVar(\"cv\", default=MappingProxyType({}))\nContextVar(\"cv\", default=re.compile(\"foo\"))\nContextVar(\"cv\", default=float(1))\nContextVar(\"cv\", default=frozenset[str]())\nContextVar[frozenset[str]](\"cv\", default=frozenset[str]())\n\n# Bad\nContextVar(\"cv\", default=[])\nContextVar(\"cv\", default={})\nContextVar(\"cv\", default=list())\nContextVar(\"cv\", default=set())\nContextVar(\"cv\", default=dict())\nContextVar(\"cv\", default=[char for char in \"foo\"])\nContextVar(\"cv\", default={char for char in \"foo\"})\nContextVar(\"cv\", default={char: idx for idx, char in enumerate(\"foo\")})\nContextVar(\"cv\", default=collections.deque())\nContextVar(\"cv\", default=set[str]())\nContextVar[set[str]](\"cv\", default=set[str]())\n\ndef bar() -> list[int]:\n return [1, 2, 3]\n\nContextVar(\"cv\", default=bar())\nContextVar(\"cv\", default=time.time())\n\ndef baz(): ...\nContextVar(\"cv\", default=baz())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_02.py","code":"from contextvars import ContextVar\n\nfrom fastapi import Query\nContextVar(\"cv\", default=Query(None))\n\nfrom something_else import Depends\nContextVar(\"cv\", default=Depends())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039_extended.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_01.py","code":"import typing\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, Sequence\n\nKNOWINGLY_MUTABLE_DEFAULT = []\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = []\n immutable_annotation: typing.Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: typing.ClassVar[list[int]] = []\n\n\n@dataclass\nclass B:\n mutable_default: list[int] = []\n immutable_annotation: Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: ClassVar[list[int]] = []\n\n# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n@dataclass\nclass AWithQuotes:\n mutable_default: 'list[int]' = []\n immutable_annotation: 'typing.Sequence[int]' = []\n without_annotation = []\n correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: 'list[int]' = field(default_factory=list)\n class_variable: 'typing.ClassVar[list[int]]'= []\n\n\n# Mutable defaults wrapped in field() calls\n@dataclass\nclass C:\n mutable_default: list[int] = field(default=[]) # RUF008\n mutable_default2: dict[str, int] = field(default={}) # RUF008\n mutable_default3: set[int] = field(default=set()) # RUF008\n mutable_default4: dict[str, int] = field(default=dict()) # RUF008\n correct_factory: list[int] = field(default_factory=list) # okay\n immutable_default: tuple[int, ...] = field(default=()) # okay\n immutable_default2: str = field(default=\"hello\") # okay\n immutable_default3: int = field(default=1) # okay\n non_mutable_var: list[int] = field(default=KNOWINGLY_MUTABLE_DEFAULT) # okay\n class_variable: ClassVar[list[int]] = field(default=[]) # okay\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_02.py","code":"# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n\nfrom __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Example():\n \"\"\"Class that uses ClassVar.\"\"\"\n\n options: ClassVar[dict[str, str]] = {}\n\n\nif typing.TYPE_CHECKING:\n from typing import ClassVar\n\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_03.py","code":"import datetime\nimport re\nimport typing\nfrom dataclasses import dataclass, field\nfrom fractions import Fraction\nfrom pathlib import Path\nfrom typing import ClassVar, NamedTuple\n\n\ndef default_function() -> list[int]:\n return []\n\n\nclass ImmutableType(NamedTuple):\n something: int = 8\n\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\n fine_path: Path = Path()\n fine_date: datetime.date = datetime.date(2042, 1, 1)\n fine_timedelta: datetime.timedelta = datetime.timedelta(hours=7)\n fine_tuple: tuple[int] = tuple([1])\n fine_regex: re.Pattern = re.compile(r\".*\")\n fine_float: float = float(\"-inf\")\n fine_int: int = int(12)\n fine_complex: complex = complex(1, 2)\n fine_str: str = str(\"foo\")\n fine_bool: bool = bool(\"foo\")\n fine_fraction: Fraction = Fraction(1, 2)\n\n\nDEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES = ImmutableType(40)\nDEFAULT_A_FOR_ALL_DATACLASSES = A([1, 2, 3])\n\n\n@dataclass\nclass B:\n hidden_mutable_default: list[int] = default_function()\n another_dataclass: A = A()\n not_optimal: ImmutableType = ImmutableType(20)\n good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES\n okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES\n\n fine_dataclass_function: list[int] = field(default_factory=list)\n\n\nclass IntConversionDescriptor:\n def __init__(self, *, default):\n self._default = default\n\n def __set_name__(self, owner, name):\n self._name = \"_\" + name\n\n def __get__(self, obj, type):\n if obj is None:\n return self._default\n\n return getattr(obj, self._name, self._default)\n\n def __set__(self, obj, value):\n setattr(obj, self._name, int(value))\n\n\n@dataclass\nclass InventoryItem:\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\n\n\n# Regression tests for:\n# https://github.com/astral-sh/ruff/issues/6447\nfrom typing import NewType\n\nListOfStrings = NewType(\"ListOfStrs\", list[str])\nStringsToInts = NewType(\"IntsToStrings\", dict[str, int])\n\nSpecialString = NewType(name=\"SpecialString\", tp=str)\nNegativeInteger = NewType(\"NegInt\", tp=int)\n\nInvalid1 = NewType(*Foo)\nInvalid2 = NewType(\"Invalid2\", name=Foo)\nInvalid3 = NewType(\"Invalid3\", name=Foo, lorem=\"ipsum\")\n\n@dataclass\nclass DataclassWithNewTypeFields:\n # Errors\n a: ListOfStrings = ListOfStrings([])\n b: StringsToInts = StringsToInts()\n c: Invalid1 = Invalid1()\n d: Invalid2 = Invalid2()\n e: Invalid3 = Invalid3()\n\n # No errors\n e: SpecialString = SpecialString(\"Lorem ipsum\")\n f: NegativeInteger = NegativeInteger(-110)\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/15772\ndef f() -> int:\n return 0\n\n@dataclass\nclass ShouldMatchB008RuleOfImmutableTypeAnnotationIgnored:\n this_is_not_fine: list[int] = default_function()\n # ignored\n this_is_fine: int = f()\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/17424\n@dataclass(frozen=True)\nclass C:\n foo: int = 1\n\n\n@dataclass\nclass D:\n c: C = C()\n\n\n@dataclass\nclass E:\n c: C = C()\n\n# https://github.com/astral-sh/ruff/issues/20266\n@dataclass(frozen=True)\nclass C:\n @dataclass(frozen=True)\n class D:\n foo: int = 1\n\n d: D = D() # OK","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_04.py","code":"from dataclasses import dataclass \nfrom typing import TYPE_CHECKING\n\n\ndef default_function() ->list[int]:\n return []\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\nif TYPE_CHECKING:\n from typing import ClassVar\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_05.py","code":"from dataclasses import InitVar, KW_ONLY, MISSING, dataclass, field\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n # Errors\n no_annotation = r\"foo\"\n missing = MISSING\n field = field()\n\n # No errors\n __slots__ = (\"foo\", \"bar\")\n __radd__ = __add__\n _private_attr = 100\n\n with_annotation: str\n with_annotation_and_default: int = 42\n with_annotation_and_field_specifier: bytes = field()\n\n class_var_no_arguments: ClassVar = 42\n class_var_with_arguments: ClassVar[int] = 42\n\n init_var_no_arguments: InitVar = \"lorem\"\n init_var_with_arguments: InitVar[str] = \"ipsum\"\n\n kw_only: KW_ONLY\n tu, ple, [unp, ack, ing] = (0, 1, 2, [3, 4, 5])\n mul, [ti, ple] = (a, ssign), ment = {1: b\"3\", \"2\": 4}, [6j, 5]\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_06.py","code":"from dataclasses import dataclass\nfrom enum import Enum, Flag, IntEnum, IntFlag, StrEnum, ReprEnum\n\nimport attr\nimport attrs\n\n\n## Errors\n\n@dataclass\nclass E(Enum): ...\n\n\n@dataclass # Foobar\nclass E(Flag): ...\n\n\n@dataclass()\nclass E(IntEnum): ...\n\n\n@dataclass() # Foobar\nclass E(IntFlag): ...\n\n\n@dataclass(\n frozen=True\n)\nclass E(StrEnum): ...\n\n\n@dataclass( # Foobar\n frozen=True\n)\nclass E(ReprEnum): ...\n\n\n@dataclass(\n frozen=True\n) # Foobar\nclass E(Enum): ...\n\n\n## No errors\n\n@attrs.define\nclass E(Enum): ...\n\n\n@attrs.frozen\nclass E(Enum): ...\n\n\n@attrs.mutable\nclass E(Enum): ...\n\n\n@attr.s\nclass E(Enum): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_07.py","code":"\"\"\"\nTests the handling of descriptors within a dataclass.\n\"\"\"\n\n# This portion of the dataclass spec is under-specified in the documentation,\n# but its behavior can be determined from the runtime implementation.\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, TypeVar, assert_type, overload\n\nT = TypeVar(\"T\")\n\n\nclass Desc1:\n @overload\n def __get__(self, __obj: None, __owner: Any) -> \"Desc1\":\n ...\n\n @overload\n def __get__(self, __obj: object, __owner: Any) -> int:\n ...\n\n def __get__(self, __obj: object | None, __owner: Any) -> \"int | Desc1\":\n raise NotImplementedError\n\n def __set__(self, __obj: object, __value: int) -> None:\n ...\n\n\n@dataclass\nclass DC1:\n y: Desc1 = Desc1()\n\n\ndc1 = DC1(3)\n\nassert_type(dc1.y, int)\nassert_type(DC1.y, Desc1)\n\n\nclass Desc2(Generic[T]):\n @overload\n def __get__(self, instance: None, owner: Any) -> list[T]:\n ...\n\n @overload\n def __get__(self, instance: object, owner: Any) -> T:\n ...\n\n def __get__(self, instance: object | None, owner: Any) -> list[T] | T:\n raise NotImplementedError\n\n\n@dataclass\nclass DC2:\n x: Desc2[int]\n y: Desc2[str]\n z: Desc2[str] = Desc2()\n\n\nassert_type(DC2.x, list[int])\nassert_type(DC2.y, list[str])\nassert_type(DC2.z, list[str])\n\ndc2 = DC2(Desc2(), Desc2(), Desc2())\nassert_type(dc2.x, int)\nassert_type(dc2.y, str)\nassert_type(dc2.z, str)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_descriptors.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_08.py","code":"\"\"\"\nTests validation of frozen dataclass instances.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#frozen-instances\n\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass DC1:\n a: float\n b: str\n\ndc1 = DC1(1, \"\")\n\ndc1.a = 1 # E: dataclass is frozen\ndc1.b = \"\" # E: dataclass is frozen\n\n\n# This should generate an error because a non-frozen dataclass\n# cannot inherit from a frozen dataclass.\n@dataclass # E[DC2]\nclass DC2(DC1): # E[DC2]\n pass\n\n@dataclass\nclass DC3:\n a: int\n\n# This should generate an error because a frozen dataclass\n# cannot inherit from a non-frozen dataclass.\n@dataclass(frozen=True) # E[DC4]\nclass DC4(DC3): # E[DC4]\n pass\n\n\n@dataclass(frozen=True)\nclass DC1Child(DC1):\n # This should be allowed because attributes within a frozen\n # dataclass are covariant rather than invariant.\n a: int\n","source":"typing_tests","origin":"conformance/tests/dataclasses_frozen.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_09.py","code":"\"\"\"\nTests the synthesis of the __hash__ method in a dataclass.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Callable, Hashable, assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n\n\nassert_type(DC1.__hash__, None)\n\n# These should generate errors because DC1 isn't hashable.\nDC1(0).__hash__() # E\nv1: Hashable = DC1(0) # E\n\n\n@dataclass(eq=True, frozen=True)\nclass DC2:\n a: int\n\n\ndc2_hash: Callable[..., int] = DC2.__hash__ # OK\nDC2(0).__hash__() # OK\nv2: Hashable = DC2(0) # OK\n\n\n@dataclass(eq=True)\nclass DC3:\n a: int\n\n\nassert_type(DC3.__hash__, None)\n\n# These should generate errors because DC3 isn't hashable.\nDC3(0).__hash__() # E\nv3: Hashable = DC3(0) # E\n\n\n@dataclass(frozen=True)\nclass DC4:\n a: int\n\n\ndc4_hash: Callable[..., int] = DC4.__hash__ # OK\nDC4(0).__hash__() # OK\nv4: Hashable = DC4(0) # OK\n\n\n@dataclass(eq=True, unsafe_hash=True)\nclass DC5:\n a: int\n\n\ndc5_hash: Callable[..., int] = DC5.__hash__ # OK\nDC5(0).__hash__() # OK\nv5: Hashable = DC5(0) # OK\n\n\n@dataclass(eq=True)\nclass DC6:\n a: int\n\n def __hash__(self) -> int:\n return 0\n\n\ndc6_hash: Callable[..., int] = DC6.__hash__ # OK\nDC6(0).__hash__() # OK\nv6: Hashable = DC6(0) # OK\n\n\n@dataclass(frozen=True)\nclass DC7:\n a: int\n\n def __eq__(self, other) -> bool:\n return self.a == other.a\n\n\ndc7_hash: Callable[..., int] = DC7.__hash__ # OK\nDC7(0).__hash__() # OK\nv7: Hashable = DC7(0) # OK\n","source":"typing_tests","origin":"conformance/tests/dataclasses_hash.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_10.py","code":"\"\"\"\nTests inheritance rules for dataclasses.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#inheritance\n\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar\n\n\n@dataclass\nclass DC1:\n a: int\n b: str = \"\"\n\n\n@dataclass\nclass DC2(DC1):\n b: str = \"\"\n a: int = 1\n\n\ndc2_1 = DC2(1, \"\")\n\ndc2_2 = DC2()\n\n\n@dataclass\nclass DC3:\n x: float = 15.0\n y: str = \"\"\n\n\n@dataclass\nclass DC4(DC3):\n z: tuple[int] = (10,)\n x: float = 15\n\n\ndc4_1 = DC4(0.0, \"\", (1,))\n\n\n@dataclass\nclass DC5:\n # While this generates an error at runtime for the stdlib dataclass,\n # other libraries that use dataclass_transform don't have similar\n # restrictions. It is therefore not required that a type checker\n # report an error here.\n x: list[int] = [] # E?\n\n\n@dataclass\nclass DC6:\n x: int\n y: ClassVar[int] = 1\n\n\n@dataclass\nclass DC7(DC6):\n # This should generate an error because a ClassVar cannot override\n # an instance variable of the same name.\n x: ClassVar[int] # E\n\n # This should generate an error because an instance variable cannot\n # override a class variable of the same name.\n y: int # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_11.py","code":"\"\"\"\nTests the keyword-only feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY, field\n\n\n@dataclass\nclass DC1:\n a: str\n _: KW_ONLY\n b: int = 0\n\n\nDC1(\"hi\")\nDC1(a=\"hi\")\nDC1(a=\"hi\", b=1)\nDC1(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC1(\"hi\", 1) # E\n\n\n@dataclass\nclass DC2:\n b: int = field(kw_only=True, default=3)\n a: str\n\n\nDC2(\"hi\")\nDC2(a=\"hi\")\nDC2(a=\"hi\", b=1)\nDC2(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC2(\"hi\", 1) # E\n\n\n@dataclass(kw_only=True)\nclass DC3:\n a: str = field(kw_only=False)\n b: int = 0\n\n\nDC3(\"hi\")\nDC3(a=\"hi\")\nDC3(a=\"hi\", b=1)\nDC3(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC3(\"hi\", 1) # E\n\n\n@dataclass\nclass DC4(DC3):\n c: float\n\n\nDC4(\"\", 0.2, b=3)\nDC4(a=\"\", b=3, c=0.2)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_kwonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_12.py","code":"\"\"\"\nTests the match_args feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY\nfrom typing import assert_type, Literal\n\n# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method\n\n@dataclass(match_args=True)\nclass DC1:\n x: int\n _: KW_ONLY\n y: str\n\nassert_type(DC1.__match_args__, tuple[Literal['x']])\n\n# The match_args default is True\n\n@dataclass\nclass DC2:\n x: int\n\nassert_type(DC2.__match_args__, tuple[Literal['x']])\n\n# __match_args__ is created even if __init__() is not generated\n\n@dataclass(match_args=True, init=False)\nclass DC3:\n x: int = 0\n\nassert_type(DC3.__match_args__, tuple[Literal['x']])\n\n# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.\n\n@dataclass(match_args=False)\nclass DC4:\n x: int\n\nDC4.__match_args__ # E\n\n@dataclass(match_args=True)\nclass DC5:\n __match_args__ = ()\n x: int\n\nassert_type(DC5.__match_args__, tuple[()])\n","source":"typing_tests","origin":"conformance/tests/dataclasses_match_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_13.py","code":"\"\"\"\nTests the synthesized comparison methods for dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass DC1:\n a: str\n b: int\n\n\n@dataclass(order=True)\nclass DC2:\n a: str\n b: int\n\n\ndc1_1 = DC1(\"\", 0)\ndc1_2 = DC1(\"\", 0)\n\nif dc1_1 < dc1_2:\n pass\n\nif dc1_1 <= dc1_2:\n pass\n\nif dc1_1 > dc1_2:\n pass\n\nif dc1_1 >= dc1_2:\n pass\n\nif dc1_1 == dc1_2:\n pass\n\nif dc1_1 != dc1_2:\n pass\n\nif dc1_1 == None:\n pass\n\nif dc1_1 != None:\n pass\n\ndc2_1 = DC2(\"hi\", 2)\n\n# This should generate an error because the types are\n# incompatible.\nif dc1_1 < dc2_1: # E:\n pass\n\nif dc1_1 != dc2_1:\n pass\n","source":"typing_tests","origin":"conformance/tests/dataclasses_order.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_14.py","code":"\"\"\"\nTests type checking of the __post_init__ method in a dataclass.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#post-init-processing\n\nfrom dataclasses import InitVar, dataclass, field, replace\nfrom typing import assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n b: int\n x: InitVar[int]\n c: int\n y: InitVar[str]\n\n def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y\n pass\n\n\ndc1 = DC1(1, 2, 3, 4, \"\")\n\nassert_type(dc1.a, int)\nassert_type(dc1.b, int)\nassert_type(dc1.c, int)\nprint(dc1.x) # E: cannot access InitVar\nprint(dc1.y) # E: cannot access InitVar\n\n@dataclass\nclass DC2:\n x: InitVar[int]\n y: InitVar[str]\n\n def __post_init__(self, x: int) -> None: # E: missing y\n pass\n\n\n@dataclass\nclass DC3:\n _name: InitVar[str] = field()\n name: str = field(init=False)\n\n def __post_init__(self, _name: str):\n ...\n\n\n@dataclass\nclass DC4(DC3):\n _age: InitVar[int] = field()\n age: int = field(init=False)\n\n def __post_init__(self, _name: str, _age: int):\n ...\n","source":"typing_tests","origin":"conformance/tests/dataclasses_postinit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_15.py","code":"\"\"\"\nTests the slots functionality of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass\n\n# This should generate an error because __slots__ is already defined.\n@dataclass(slots=True) # E[DC1]\nclass DC1: # E[DC1]\n x: int\n\n __slots__ = ()\n\n\n@dataclass(slots=True)\nclass DC2:\n x: int\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass(slots=False)\nclass DC3:\n x: int\n\n __slots__ = (\"x\",)\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass\nclass DC4:\n __slots__ = (\"y\", \"x\")\n x: int\n y: str\n\n\nDC4(1, \"bar\")\n\n\n@dataclass(slots=True)\nclass DC5:\n a: int\n\n\nDC5.__slots__\nDC5(1).__slots__\n\n\n@dataclass\nclass DC6:\n a: int\n\n\n# This should generate an error because __slots__ is not defined.\nDC6.__slots__ # E\n\n# This should generate an error because __slots__ is not defined.\nDC6(1).__slots__ # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_slots.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_16.py","code":"\"\"\"\nTests basic handling of the dataclass factory.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html\n# Also, see https://peps.python.org/pep-0557/\n\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar, assert_type\nimport sys\n\nT = TypeVar(\"T\")\n\n\n@dataclass(order=True)\nclass InventoryItem:\n x = 0\n name: str\n unit_price: float\n quantity_on_hand: int = 0\n\n def total_cost(self) -> float:\n return self.unit_price * self.quantity_on_hand\n\n\nv1 = InventoryItem(\"soap\", 2.3)\n\n\nclass InventoryItemInitProto(Protocol):\n def __call__(\n self, name: str, unit_price: float, quantity_on_hand: int = ...\n ) -> None: ...\n\n\n# Validate the type of the synthesized __init__ method.\nx1: InventoryItemInitProto = v1.__init__\n\n# Make sure the following additional methods were synthesized.\nprint(v1.__repr__)\nprint(v1.__eq__)\nprint(v1.__ne__)\nprint(v1.__lt__)\nprint(v1.__le__)\nprint(v1.__gt__)\nprint(v1.__ge__)\n\nassert_type(v1.name, str)\nassert_type(v1.unit_price, float)\nassert_type(v1.quantity_on_hand, int)\n\nv2 = InventoryItem(\"name\") # E: missing unit_price\nv3 = InventoryItem(\"name\", \"price\") # E: incorrect type for unit_price\nv4 = InventoryItem(\"name\", 3.1, 3, 4) # E: too many arguments\n\n\n# > TypeError will be raised if a field without a default value follows a\n# > field with a default value. This is true either when this occurs in a\n# > single class, or as a result of class inheritance.\n@dataclass # E[DC1]\nclass DC1:\n a: int = 0 # E[DC1]: field with default should follow a field with no default.\n b: int # E[DC1]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC2]\nclass DC2:\n a: int = field(default=1) # E[DC2]: field with default should follow a field with no default.\n b: int # E[DC2]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC3]\nclass DC3:\n a: InitVar[int] = 0 # E[DC3]: field with default should follow a field with no default.\n b: int # E[DC3]: field with no default cannot follow field with default.\n\n\n@dataclass\nclass DC4:\n a: int = field(init=False)\n b: int\n\n\nv5 = DC4(0)\nv6 = DC4(0, 1) # E: too many parameters\n\n\n@dataclass\nclass DC5:\n a: int = field(default_factory=str) # E: type mismatch\n\n\ndef f(s: str) -> int:\n return int(s)\n\n\n@dataclass\nclass DC6:\n a: ClassVar[int] = 0\n b: str\n c: Callable[[str], int] = f\n\n\ndc6 = DC6(\"\")\nassert_type(dc6.a, int)\nassert_type(DC6.a, int)\nassert_type(dc6.b, str)\nassert_type(dc6.c, Callable[[str], int])\n\n\n@dataclass\nclass DC7:\n x: int\n\n\n@dataclass(init=False)\nclass DC8(DC7):\n y: int\n\n def __init__(self, a: DC7, y: int):\n self.__dict__ = a.__dict__\n self.y = y\n\n\na = DC7(3)\nb = DC8(a, 5)\n\n# This should generate an error because there is an extra parameter\nDC7(3, 4) # E\n\n# This should generate an error because there is one too few parameters\nDC8(a) # E\n\n\n@dataclass\nclass DC9:\n a: str = field(init=False, default=\"s\")\n b: bool = field()\n\n\n@dataclass\nclass DC10(DC9):\n a: str = field()\n b: bool = field()\n\n\n@dataclass(init=False)\nclass DC11:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC11(3)\n\n\n@dataclass(init=True)\nclass DC12:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC12(3)\n\n\n@dataclass(init=False)\nclass DC13:\n x: int\n x_squared: int\n\n\n# This should generate an error because there is no matching\n# override __init__ method and no synthesized __init__.\nDC13(3) # E\n\n\n@dataclass\nclass DC14:\n prop_1: str = field(init=False)\n prop_2: str = field(default=\"hello\")\n prop_3: str = field(default_factory=lambda: \"hello\")\n\n\n@dataclass\nclass DC15(DC14):\n prop_2: str = \"\"\n\n\ndc15 = DC15(prop_2=\"test\")\n\nassert_type(dc15.prop_1, str)\nassert_type(dc15.prop_2, str)\nassert_type(dc15.prop_3, str)\n\n\nclass DataclassProto(Protocol):\n __dataclass_fields__: ClassVar[dict[str, Any]]\n\n\nv7: DataclassProto = dc15\n\n\n@dataclass\nclass DC16(Generic[T]):\n value: T\n\n\nassert_type(DC16(1), DC16[int])\n\n\nclass DC17(DC16[str]):\n pass\n\n\nassert_type(DC17(\"\"), DC17)\n\n\n@dataclass\nclass DC18:\n x: int = field()\n # This may generate a type checker error because an unannotated field\n # will result in a runtime exception.\n y = field() # E?\n\n\n# > Dataclass fields may be conditional, via checks of the same\n# > statically-known conditions that a type-checker understands elsewhere,\n# > such as Python version:\n\n@dataclass\nclass DC19:\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nDC19(1, 2)\nDC19(1, 2, 3) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport types\nimport unittest\nfrom test.support import import_module\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport types\nimport unittest\nfrom test.support import import_module\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n try:\n g.__anext__().__next__()\n except StopAsyncIteration:\n res.append('STOP')\n break\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n else:\n res.append('EMPTY StopIteration')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n self.assertEqual(ai.__anext__().__next__(), ('result',))\n\n try:\n ai.__anext__().__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n self.assertEqual(ai.__anext__().__next__(), ('result',))\n\n try:\n ai.__anext__().__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n self.assertEqual(ai.__anext__().__next__(), ('result',))\n\n try:\n ai.__anext__().__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n\n self.assertTrue(inspect.isawaitable(g.aclose()))\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport types\nimport unittest\nfrom test.support import import_module\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01, loop=self.loop)\n yield 2\n await asyncio.sleep(0.01, loop=self.loop)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01, loop=self.loop)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01, loop=loop)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01, loop=self.loop)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01, loop=self.loop)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n t = self.loop.create_task(it.__anext__())\n await asyncio.sleep(0.01, loop=self.loop)\n await gen.aclose()\n return t\n\n t = self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n t.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01, loop=self.loop))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n\n await asyncio.sleep(0.1, loop=self.loop)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n v = yield 1\n await asyncio.sleep(0.01, loop=self.loop)\n yield v * 2\n await asyncio.sleep(0.01, loop=self.loop)\n return\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay, loop=self.loop)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay, loop=self.loop),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01, loop=self.loop)\n yield v * 2\n await asyncio.sleep(0.01, loop=self.loop)\n # return\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay, loop=self.loop),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01, loop=self.loop)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01, loop=self.loop)\n # return\n finally:\n await asyncio.sleep(0.01, loop=self.loop)\n await asyncio.sleep(0.01, loop=self.loop)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout, loop=self.loop)\n yield 1\n finally:\n await asyncio.sleep(0, loop=self.loop)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n self.assertEqual(finalized, 2)\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))\n\n def test_async_gen_asyncio_shutdown_02(self):\n logged = 0\n\n def logger(loop, context):\n nonlocal logged\n self.assertIn('asyncgen', context)\n expected = 'an error occurred during closing of asynchronous'\n if expected in context['message']:\n logged += 1\n\n async def waiter(timeout):\n try:\n await asyncio.sleep(timeout, loop=self.loop)\n yield 1\n finally:\n 1 / 0\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t = self.loop.create_task(wait())\n self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))\n\n self.loop.set_exception_handler(logger)\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(logged, 1)\n\n # Silence warnings\n t.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.1, loop=self.loop))\n\n def test_async_gen_expression_01(self):\n async def arange(n):\n for i in range(n):\n await asyncio.sleep(0.01, loop=self.loop)\n yield i\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 async for i in arange(n))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(10)])\n\n def test_async_gen_expression_02(self):\n async def wrap(n):\n await asyncio.sleep(0.01, loop=self.loop)\n return n\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 for i in range(n) if await wrap(i))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(1, 10)])\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"breakpoint","pep":"553","introduced_in":"3.7","form":"modern","file":"breakpoint/modern_01.py","code":"import ast\nimport builtins\nimport collections\nimport decimal\nimport fractions\nimport io\nimport locale\nimport os\nimport pickle\nimport platform\nimport random\nimport re\nimport sys\nimport traceback\nimport types\nimport unittest\nimport warnings\nfrom contextlib import ExitStack\nfrom operator import neg\nfrom test.support import (\n EnvironmentVarGuard, TESTFN, check_warnings, swap_attr, unlink)\nfrom test.support.script_helper import assert_python_ok\nfrom unittest.mock import MagicMock, patch\n\n\nclass TestBreakpoint(unittest.TestCase):\n def setUp(self):\n # These tests require a clean slate environment. For example, if the\n # test suite is run with $PYTHONBREAKPOINT set to something else, it\n # will mess up these tests. Similarly for sys.breakpointhook.\n # Cleaning the slate here means you can't use breakpoint() to debug\n # these tests, but I think that's okay. Just use pdb.set_trace() if\n # you must.\n self.resources = ExitStack()\n self.addCleanup(self.resources.close)\n self.env = self.resources.enter_context(EnvironmentVarGuard())\n del self.env['PYTHONBREAKPOINT']\n self.resources.enter_context(\n swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))\n\n def test_breakpoint(self):\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once()\n\n def test_breakpoint_with_breakpointhook_set(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_breakpointhook_reset(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n # Reset the hook and it will not be called again.\n sys.breakpointhook = sys.__breakpointhook__\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_args_and_keywords(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint(1, 2, 3, four=4, five=5)\n my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)\n\n def test_breakpoint_with_passthru_error(self):\n def my_breakpointhook():\n pass\n sys.breakpointhook = my_breakpointhook\n self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_builtin(self):\n self.env['PYTHONBREAKPOINT'] = 'int'\n with patch('builtins.int') as mock:\n breakpoint('7')\n mock.assert_called_once_with('7')\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_other(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_noop_0(self):\n self.env['PYTHONBREAKPOINT'] = '0'\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_not_called()\n\n def test_envar_good_path_empty_string(self):\n # PYTHONBREAKPOINT='' is the same as it not being set.\n self.env['PYTHONBREAKPOINT'] = ''\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_unimportable(self):\n for envar in (\n '.', '..', '.foo', 'foo.', '.int', 'int.'\n 'nosuchbuiltin',\n 'nosuchmodule.nosuchcallable',\n ):\n with self.subTest(envar=envar):\n self.env['PYTHONBREAKPOINT'] = envar\n mock = self.resources.enter_context(patch('pdb.set_trace'))\n w = self.resources.enter_context(check_warnings(quiet=True))\n breakpoint()\n self.assertEqual(\n str(w.message),\n f'Ignoring unimportable $PYTHONBREAKPOINT: \"{envar}\"')\n self.assertEqual(w.category, RuntimeWarning)\n mock.assert_not_called()\n\n def test_envar_ignored_when_hook_is_set(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n sys.breakpointhook = int\n breakpoint()\n mock.assert_not_called()\n","source":"cpython_tests","origin":"Lib/test/test_builtin.py::TestBreakpoint","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, ZeroDivisionError)\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, TypeError)\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_03.py","code":"import concurrent.futures\nimport contextvars\nimport functools\nimport gc\nimport random\nimport time\nimport unittest\nimport weakref\n\n\nclass ContextTest(unittest.TestCase):\n def test_context_var_new_1(self):\n with self.assertRaisesRegex(TypeError, 'takes exactly 1'):\n contextvars.ContextVar()\n\n with self.assertRaisesRegex(TypeError, 'must be a str'):\n contextvars.ContextVar(1)\n\n c = contextvars.ContextVar('a')\n self.assertNotEqual(hash(c), hash('a'))\n\n def test_context_var_new_2(self):\n self.assertIsNone(contextvars.ContextVar[int])\n\n @isolated_context\n def test_context_var_repr_1(self):\n c = contextvars.ContextVar('a')\n self.assertIn('a', repr(c))\n\n c = contextvars.ContextVar('a', default=123)\n self.assertIn('123', repr(c))\n\n lst = []\n c = contextvars.ContextVar('a', default=lst)\n lst.append(c)\n self.assertIn('...', repr(c))\n self.assertIn('...', repr(lst))\n\n t = c.set(1)\n self.assertIn(repr(c), repr(t))\n self.assertNotIn(' used ', repr(t))\n c.reset(t)\n self.assertIn(' used ', repr(t))\n\n def test_context_subclassing_1(self):\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContextVar(contextvars.ContextVar):\n # Potentially we might want ContextVars to be subclassable.\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContext(contextvars.Context):\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyToken(contextvars.Token):\n pass\n\n def test_context_new_1(self):\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1, a=1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(a=1)\n contextvars.Context(**{})\n\n def test_context_typerrors_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx[1]\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n 1 in ctx\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx.get(1)\n\n def test_context_get_context_1(self):\n ctx = contextvars.copy_context()\n self.assertIsInstance(ctx, contextvars.Context)\n\n def test_context_run_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required'):\n ctx.run()\n\n def test_context_run_2(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n kwargs['spam'] = 'foo'\n args += ('bar',)\n return args, kwargs\n\n for f in (func, functools.partial(func)):\n # partial doesn't support FASTCALL\n\n self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))\n self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, a=2),\n (('bar',), {'a': 2, 'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, 11, a=2),\n ((11, 'bar'), {'a': 2, 'spam': 'foo'}))\n\n a = {}\n self.assertEqual(\n ctx.run(f, 11, **a),\n ((11, 'bar'), {'spam': 'foo'}))\n self.assertEqual(a, {})\n\n def test_context_run_3(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2, a=123)\n\n @isolated_context\n def test_context_run_4(self):\n ctx1 = contextvars.Context()\n ctx2 = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func2():\n self.assertIsNone(var.get(None))\n\n def func1():\n self.assertIsNone(var.get(None))\n var.set('spam')\n ctx2.run(func2)\n self.assertEqual(var.get(None), 'spam')\n\n cur = contextvars.copy_context()\n self.assertEqual(len(cur), 1)\n self.assertEqual(cur[var], 'spam')\n return cur\n\n returned_ctx = ctx1.run(func1)\n self.assertEqual(ctx1, returned_ctx)\n self.assertEqual(returned_ctx[var], 'spam')\n self.assertIn(var, returned_ctx)\n\n def test_context_run_5(self):\n ctx = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func():\n self.assertIsNone(var.get(None))\n var.set('spam')\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n\n self.assertIsNone(var.get(None))\n\n def test_context_run_6(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('a', default=0)\n\n def fun():\n self.assertEqual(c.get(), 0)\n self.assertIsNone(ctx.get(c))\n\n c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(ctx.get(c), 42)\n\n ctx.run(fun)\n\n def test_context_run_7(self):\n ctx = contextvars.Context()\n\n def fun():\n with self.assertRaisesRegex(RuntimeError, 'is already entered'):\n ctx.run(fun)\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_1(self):\n c = contextvars.ContextVar('c')\n with self.assertRaises(LookupError):\n c.get()\n\n self.assertIsNone(c.get(None))\n\n t0 = c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n self.assertIs(t0.old_value, t0.MISSING)\n self.assertIs(t0.old_value, contextvars.Token.MISSING)\n self.assertIs(t0.var, c)\n\n t = c.set('spam')\n self.assertEqual(c.get(), 'spam')\n self.assertEqual(c.get(None), 'spam')\n self.assertEqual(t.old_value, 42)\n c.reset(t)\n\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n\n c.set('spam2')\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t)\n self.assertEqual(c.get(), 'spam2')\n\n ctx1 = contextvars.copy_context()\n self.assertIn(c, ctx1)\n\n c.reset(t0)\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t0)\n self.assertIsNone(c.get(None))\n\n self.assertIn(c, ctx1)\n self.assertEqual(ctx1[c], 'spam2')\n self.assertEqual(ctx1.get(c, 'aa'), 'spam2')\n self.assertEqual(len(ctx1), 1)\n self.assertEqual(list(ctx1.items()), [(c, 'spam2')])\n self.assertEqual(list(ctx1.values()), ['spam2'])\n self.assertEqual(list(ctx1.keys()), [c])\n self.assertEqual(list(ctx1), [c])\n\n ctx2 = contextvars.copy_context()\n self.assertNotIn(c, ctx2)\n with self.assertRaises(KeyError):\n ctx2[c]\n self.assertEqual(ctx2.get(c, 'aa'), 'aa')\n self.assertEqual(len(ctx2), 0)\n self.assertEqual(list(ctx2), [])\n\n @isolated_context\n def test_context_getset_2(self):\n v1 = contextvars.ContextVar('v1')\n v2 = contextvars.ContextVar('v2')\n\n t1 = v1.set(42)\n with self.assertRaisesRegex(ValueError, 'by a different'):\n v2.reset(t1)\n\n @isolated_context\n def test_context_getset_3(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n def fun():\n self.assertEqual(c.get(), 42)\n with self.assertRaises(KeyError):\n ctx[c]\n self.assertIsNone(ctx.get(c))\n self.assertEqual(ctx.get(c, 'spam'), 'spam')\n self.assertNotIn(c, ctx)\n self.assertEqual(list(ctx.keys()), [])\n\n t = c.set(1)\n self.assertEqual(list(ctx.keys()), [c])\n self.assertEqual(ctx[c], 1)\n\n c.reset(t)\n self.assertEqual(list(ctx.keys()), [])\n with self.assertRaises(KeyError):\n ctx[c]\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_4(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n tok = ctx.run(c.set, 1)\n\n with self.assertRaisesRegex(ValueError, 'different Context'):\n c.reset(tok)\n\n @isolated_context\n def test_context_getset_5(self):\n c = contextvars.ContextVar('c', default=42)\n c.set([])\n\n def fun():\n c.set([])\n c.get().append(42)\n self.assertEqual(c.get(), [42])\n\n contextvars.copy_context().run(fun)\n self.assertEqual(c.get(), [])\n\n def test_context_copy_1(self):\n ctx1 = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def ctx1_fun():\n c.set(10)\n\n ctx2 = ctx1.copy()\n self.assertEqual(ctx2[c], 10)\n\n c.set(20)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 10)\n\n ctx2.run(ctx2_fun)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 30)\n\n def ctx2_fun():\n self.assertEqual(c.get(), 10)\n c.set(30)\n self.assertEqual(c.get(), 30)\n\n ctx1.run(ctx1_fun)\n\n @isolated_context\n def test_context_threads_1(self):\n cvar = contextvars.ContextVar('cvar')\n\n def sub(num):\n for i in range(10):\n cvar.set(num + i)\n time.sleep(random.uniform(0.001, 0.05))\n self.assertEqual(cvar.get(), num + i)\n return num\n\n tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)\n try:\n results = list(tp.map(sub, range(10)))\n finally:\n tp.shutdown()\n self.assertEqual(results, list(range(10)))\n","source":"cpython_tests","origin":"Lib/test/test_context.py::ContextTest","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_17.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFieldNoAnnotation(unittest.TestCase):\n def test_field_without_annotation(self):\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n @dataclass\n class C:\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base(self):\n @dataclass\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base_not_dataclass(self):\n # Same test, but with the base class not a dataclass.\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFieldNoAnnotation","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_18.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDocString(unittest.TestCase):\n def assertDocStrEqual(self, a, b):\n # Because 3.6 and 3.7 differ in how inspect.signature work\n # (see bpo #32108), for the time being just compare them with\n # whitespace stripped.\n self.assertEqual(a.replace(' ', ''), b.replace(' ', ''))\n\n def test_existing_docstring_not_overridden(self):\n @dataclass\n class C:\n \"\"\"Lorem ipsum\"\"\"\n x: int\n\n self.assertEqual(C.__doc__, \"Lorem ipsum\")\n\n def test_docstring_no_fields(self):\n @dataclass\n class C:\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C()\")\n\n def test_docstring_one_field(self):\n @dataclass\n class C:\n x: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int)\")\n\n def test_docstring_two_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int)\")\n\n def test_docstring_three_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n z: str\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int, z:str)\")\n\n def test_docstring_one_field_with_default(self):\n @dataclass\n class C:\n x: int = 3\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int=3)\")\n\n def test_docstring_one_field_with_default_none(self):\n @dataclass\n class C:\n x: Union[int, type(None)] = None\n\n self.assertDocStrEqual(C.__doc__, \"C(x:Union[int, NoneType]=None)\")\n\n def test_docstring_list_field(self):\n @dataclass\n class C:\n x: List[int]\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int])\")\n\n def test_docstring_list_field_with_default_factory(self):\n @dataclass\n class C:\n x: List[int] = field(default_factory=list)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int]=)\")\n\n def test_docstring_deque_field(self):\n @dataclass\n class C:\n x: deque\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque)\")\n\n def test_docstring_deque_field_with_default_factory(self):\n @dataclass\n class C:\n x: deque = field(default_factory=deque)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque=)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDocString","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_19.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestInit(unittest.TestCase):\n def test_base_has_init(self):\n class B:\n def __init__(self):\n self.z = 100\n pass\n\n # Make sure that declaring this class doesn't raise an error.\n # The issue is that we can't override __init__ in our class,\n # but it should be okay to add __init__ to us if our base has\n # an __init__.\n @dataclass\n class C(B):\n x: int = 0\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertNotIn('z', vars(c))\n\n # Make sure that if we don't add an init, the base __init__\n # gets called.\n @dataclass(init=False)\n class C(B):\n x: int = 10\n c = C()\n self.assertEqual(c.x, 10)\n self.assertEqual(c.z, 100)\n\n def test_no_init(self):\n dataclass(init=False)\n class C:\n i: int = 0\n self.assertEqual(C().i, 0)\n\n dataclass(init=False)\n class C:\n i: int = 2\n def __init__(self):\n self.i = 3\n self.assertEqual(C().i, 3)\n\n def test_overwriting_init(self):\n # If the class has __init__, use it no matter the value of\n # init=.\n\n @dataclass\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(3).x, 6)\n\n @dataclass(init=True)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(4).x, 8)\n\n @dataclass(init=False)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(5).x, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestInit","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_20.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestRepr(unittest.TestCase):\n def test_repr(self):\n @dataclass\n class B:\n x: int\n\n @dataclass\n class C(B):\n y: int = 10\n\n o = C(4)\n self.assertEqual(repr(o), 'TestRepr.test_repr..C(x=4, y=10)')\n\n @dataclass\n class D(C):\n x: int = 20\n self.assertEqual(repr(D()), 'TestRepr.test_repr..D(x=20, y=10)')\n\n @dataclass\n class C:\n @dataclass\n class D:\n i: int\n @dataclass\n class E:\n pass\n self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr..C.D(i=0)')\n self.assertEqual(repr(C.E()), 'TestRepr.test_repr..C.E()')\n\n def test_no_repr(self):\n # Test a class with no __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n self.assertIn('test_dataclasses.TestRepr.test_no_repr..C object at',\n repr(C(3)))\n\n # Test a class with a __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'C-class'\n self.assertEqual(repr(C(3)), 'C-class')\n\n def test_overwriting_repr(self):\n # If the class has __repr__, use it no matter the value of\n # repr=.\n\n @dataclass\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=True)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestRepr","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_21.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestEq(unittest.TestCase):\n def test_no_eq(self):\n # Test a class with no __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n self.assertNotEqual(C(0), C(0))\n c = C(3)\n self.assertEqual(c, c)\n\n # Test a class with an __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 10\n self.assertEqual(C(3), 10)\n\n def test_overwriting_eq(self):\n # If the class has __eq__, use it no matter the value of\n # eq=.\n\n @dataclass\n class C:\n x: int\n def __eq__(self, other):\n return other == 3\n self.assertEqual(C(1), 3)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=True)\n class C:\n x: int\n def __eq__(self, other):\n return other == 4\n self.assertEqual(C(1), 4)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 5\n self.assertEqual(C(1), 5)\n self.assertNotEqual(C(1), 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestEq","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_22.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestOrdering(unittest.TestCase):\n def test_functools_total_ordering(self):\n # Test that functools.total_ordering works with this class.\n @total_ordering\n @dataclass\n class C:\n x: int\n def __lt__(self, other):\n # Perform the test \"backward\", just to make\n # sure this is being called.\n return self.x >= other\n\n self.assertLess(C(0), -1)\n self.assertLessEqual(C(0), -1)\n self.assertGreater(C(0), 1)\n self.assertGreaterEqual(C(0), 1)\n\n def test_no_order(self):\n # Test that no ordering functions are added by default.\n @dataclass(order=False)\n class C:\n x: int\n # Make sure no order methods are added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__lt__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n # Test that __lt__ is still called\n @dataclass(order=False)\n class C:\n x: int\n def __lt__(self, other):\n return False\n # Make sure other methods aren't added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n def test_overwriting_order(self):\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __lt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __lt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __le__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __le__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __gt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __gt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __ge__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __ge__(self):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestOrdering","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_23.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestHash(unittest.TestCase):\n def test_unsafe_hash(self):\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n y: str\n self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))\n\n def test_hash_rules(self):\n def non_bool(value):\n # Map to something else that's True, but not a bool.\n if value is None:\n return None\n if value:\n return (3,)\n return 0\n\n def test(case, unsafe_hash, eq, frozen, with_hash, result):\n with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,\n frozen=frozen):\n if result != 'exception':\n if with_hash:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n else:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n pass\n\n # See if the result matches what's expected.\n if result == 'fn':\n # __hash__ contains the function we generated.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNotNone(C.__dict__['__hash__'])\n\n elif result == '':\n # __hash__ is not present in our class.\n if not with_hash:\n self.assertNotIn('__hash__', C.__dict__)\n\n elif result == 'none':\n # __hash__ is set to None.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNone(C.__dict__['__hash__'])\n\n elif result == 'exception':\n # Creating the class should cause an exception.\n # This only happens with with_hash==True.\n assert(with_hash)\n with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n\n else:\n assert False, f'unknown result {result!r}'\n\n # There are 8 cases of:\n # unsafe_hash=True/False\n # eq=True/False\n # frozen=True/False\n # And for each of these, a different result if\n # __hash__ is defined or not.\n for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([\n (False, False, False, '', ''),\n (False, False, True, '', ''),\n (False, True, False, 'none', ''),\n (False, True, True, 'fn', ''),\n (True, False, False, 'fn', 'exception'),\n (True, False, True, 'fn', 'exception'),\n (True, True, False, 'fn', 'exception'),\n (True, True, True, 'fn', 'exception'),\n ], 1):\n test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)\n test(case, unsafe_hash, eq, frozen, True, res_defined_hash)\n\n # Test non-bool truth values, too. This is just to\n # make sure the data-driven table in the decorator\n # handles non-bool values.\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)\n\n\n def test_eq_only(self):\n # If a class defines __eq__, __hash__ is automatically added\n # and set to None. This is normal Python behavior, not\n # related to dataclasses. Make sure we don't interfere with\n # that (see bpo=32546).\n\n @dataclass\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1))\n self.assertNotEqual(C(1), C(4))\n\n # And make sure things work in this case if we specify\n # unsafe_hash=True.\n @dataclass(unsafe_hash=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1.0))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n # And check that the classes __eq__ is being used, despite\n # specifying eq=True.\n @dataclass(unsafe_hash=True, eq=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == 3 and self.i == other.i\n self.assertEqual(C(3), C(3))\n self.assertNotEqual(C(1), C(1))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n def test_0_field_hash(self):\n @dataclass(frozen=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n @dataclass(unsafe_hash=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n def test_1_field_hash(self):\n @dataclass(frozen=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n def test_hash_no_args(self):\n # Test dataclasses with no hash= argument. This exists to\n # make sure that if the @dataclass parameter name is changed\n # or the non-default hashing behavior changes, the default\n # hashability keeps working the same way.\n\n class Base:\n def __hash__(self):\n return 301\n\n # If frozen or eq is None, then use the default value (do not\n # specify any value in the decorator).\n for frozen, eq, base, expected in [\n (None, None, object, 'unhashable'),\n (None, None, Base, 'unhashable'),\n (None, False, object, 'object'),\n (None, False, Base, 'base'),\n (None, True, object, 'unhashable'),\n (None, True, Base, 'unhashable'),\n (False, None, object, 'unhashable'),\n (False, None, Base, 'unhashable'),\n (False, False, object, 'object'),\n (False, False, Base, 'base'),\n (False, True, object, 'unhashable'),\n (False, True, Base, 'unhashable'),\n (True, None, object, 'tuple'),\n (True, None, Base, 'tuple'),\n (True, False, object, 'object'),\n (True, False, Base, 'base'),\n (True, True, object, 'tuple'),\n (True, True, Base, 'tuple'),\n ]:\n\n with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):\n # First, create the class.\n if frozen is None and eq is None:\n @dataclass\n class C(base):\n i: int\n elif frozen is None:\n @dataclass(eq=eq)\n class C(base):\n i: int\n elif eq is None:\n @dataclass(frozen=frozen)\n class C(base):\n i: int\n else:\n @dataclass(frozen=frozen, eq=eq)\n class C(base):\n i: int\n\n # Now, make sure it hashes as expected.\n if expected == 'unhashable':\n c = C(10)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(c)\n\n elif expected == 'base':\n self.assertEqual(hash(C(10)), 301)\n\n elif expected == 'object':\n # I'm not sure what test to use here. object's\n # hash isn't based on id(), so calling hash()\n # won't tell us much. So, just check the\n # function used is object's.\n self.assertIs(C.__hash__, object.__hash__)\n\n elif expected == 'tuple':\n self.assertEqual(hash(C(42)), hash((42,)))\n\n else:\n assert False, f'unknown value for expected={expected!r}'\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestHash","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_24.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFrozen(unittest.TestCase):\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n c = C(10)\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertEqual(c.i, 10)\n\n def test_inherit(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n @dataclass(frozen=True)\n class D(C):\n j: int\n\n d = D(0, 10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n with self.assertRaises(FrozenInstanceError):\n d.j = 6\n self.assertEqual(d.i, 0)\n self.assertEqual(d.j, 10)\n\n # Test both ways: with an intermediate normal (non-dataclass)\n # class and without an intermediate class.\n def test_inherit_nonfrozen_from_frozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass(frozen=True)\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(I):\n pass\n\n def test_inherit_frozen_from_nonfrozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one'):\n @dataclass(frozen=True)\n class D(I):\n pass\n\n def test_inherit_from_normal_class(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n class C:\n pass\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n @dataclass(frozen=True)\n class D(I):\n i: int\n\n d = D(10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n\n def test_non_frozen_normal_derived(self):\n # See bpo-32953.\n\n @dataclass(frozen=True)\n class D:\n x: int\n y: int = 10\n\n class S(D):\n pass\n\n s = S(3)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n s.cached = True\n\n # But can't change the frozen attributes.\n with self.assertRaises(FrozenInstanceError):\n s.x = 5\n with self.assertRaises(FrozenInstanceError):\n s.y = 5\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.cached, True)\n\n def test_overwriting_frozen(self):\n # frozen uses __setattr__ and __delattr__.\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __setattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __setattr__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __delattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __delattr__(self):\n pass\n\n @dataclass(frozen=False)\n class C:\n x: int\n def __setattr__(self, name, value):\n self.__dict__['x'] = value * 2\n self.assertEqual(C(10).x, 20)\n\n def test_frozen_hash(self):\n @dataclass(frozen=True)\n class C:\n x: Any\n\n # If x is immutable, we can compute the hash. No exception is\n # raised.\n hash(C(3))\n\n # If x is mutable, computing the hash is an error.\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(C({}))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFrozen","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_25.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestSlots(unittest.TestCase):\n def test_simple(self):\n @dataclass\n class C:\n __slots__ = ('x',)\n x: Any\n\n # There was a bug where a variable in a slot was assumed to\n # also have a default value (of type\n # types.MemberDescriptorType).\n with self.assertRaisesRegex(TypeError,\n r\"__init__\\(\\) missing 1 required positional argument: 'x'\"):\n C()\n\n # We can create an instance, and assign to x.\n c = C(10)\n self.assertEqual(c.x, 10)\n c.x = 5\n self.assertEqual(c.x, 5)\n\n # We can't assign to anything else.\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'y'\"):\n c.y = 5\n\n def test_derived_added_field(self):\n # See bpo-33100.\n @dataclass\n class Base:\n __slots__ = ('x',)\n x: Any\n\n @dataclass\n class Derived(Base):\n x: int\n y: int\n\n d = Derived(1, 2)\n self.assertEqual((d.x, d.y), (1, 2))\n\n # We can add a new field to the derived instance.\n d.z = 10\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestSlots","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_26.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDescriptors(unittest.TestCase):\n def test_set_name(self):\n # See bpo-33141.\n\n # Create a descriptor.\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n def __get__(self, instance, owner):\n if instance is not None:\n return 1\n return self\n\n # This is the case of just normal descriptor behavior, no\n # dataclass code is involved in initializing the descriptor.\n @dataclass\n class C:\n c: int=D()\n self.assertEqual(C.c.name, 'cx')\n\n # Now test with a default value and init=False, which is the\n # only time this is really meaningful. If not using\n # init=False, then the descriptor will be overwritten, anyway.\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n self.assertEqual(C().c, 1)\n\n def test_non_descriptor(self):\n # PEP 487 says __set_name__ should work on non-descriptors.\n # Create a descriptor.\n\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n\n def test_lookup_on_instance(self):\n # See bpo-33175.\n class D:\n pass\n\n d = D()\n # Create an attribute on the instance, not type.\n d.__set_name__ = Mock()\n\n # Make sure d.__set_name__ is not called.\n @dataclass\n class C:\n i: int=field(default=d, init=False)\n\n self.assertEqual(d.__set_name__.call_count, 0)\n\n def test_lookup_on_class(self):\n # See bpo-33175.\n class D:\n pass\n D.__set_name__ = Mock()\n\n # Make sure D.__set_name__ is called.\n @dataclass\n class C:\n i: int=field(default=D(), init=False)\n\n self.assertEqual(D.__set_name__.call_count, 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDescriptors","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_27.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestMakeDataclass(unittest.TestCase):\n def test_simple(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace={'add_one': lambda self: self.x + 1})\n c = C(10)\n self.assertEqual((c.x, c.y), (10, 5))\n self.assertEqual(c.add_one(), 11)\n\n\n def test_no_mutate_namespace(self):\n # Make sure a provided namespace isn't mutated.\n ns = {}\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace=ns)\n self.assertEqual(ns, {})\n\n def test_base(self):\n class Base1:\n pass\n class Base2:\n pass\n C = make_dataclass('C',\n [('x', int)],\n bases=(Base1, Base2))\n c = C(2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n def test_base_dataclass(self):\n @dataclass\n class Base1:\n x: int\n class Base2:\n pass\n C = make_dataclass('C',\n [('y', int)],\n bases=(Base1, Base2))\n with self.assertRaisesRegex(TypeError, 'required positional'):\n c = C(2)\n c = C(1, 2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n self.assertEqual((c.x, c.y), (1, 2))\n\n def test_init_var(self):\n def post_init(self, y):\n self.x *= y\n\n C = make_dataclass('C',\n [('x', int),\n ('y', InitVar[int]),\n ],\n namespace={'__post_init__': post_init},\n )\n c = C(2, 3)\n self.assertEqual(vars(c), {'x': 6})\n self.assertEqual(len(fields(c)), 1)\n\n def test_class_var(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ])\n c = C(1)\n self.assertEqual(vars(c), {'x': 1})\n self.assertEqual(len(fields(c)), 1)\n self.assertEqual(C.y, 10)\n self.assertEqual(C.z, 20)\n\n def test_other_params(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ],\n init=False)\n # Make sure we have a repr, but no init.\n self.assertNotIn('__init__', vars(C))\n self.assertIn('__repr__', vars(C))\n\n # Make sure random other params don't work.\n with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):\n C = make_dataclass('C',\n [],\n xxinit=False)\n\n def test_no_types(self):\n C = make_dataclass('Point', ['x', 'y', 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': 'typing.Any',\n 'z': 'typing.Any'})\n\n C = make_dataclass('Point', ['x', ('y', int), 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': int,\n 'z': 'typing.Any'})\n\n def test_invalid_type_specification(self):\n for bad_field in [(),\n (1, 2, 3, 4),\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'Invalid field: '):\n make_dataclass('C', ['a', bad_field])\n\n # And test for things with no len().\n for bad_field in [float,\n lambda x:x,\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'has no len\\(\\)'):\n make_dataclass('C', ['a', bad_field])\n\n def test_duplicate_field_names(self):\n for field in ['a', 'ab']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'Field name duplicated'):\n make_dataclass('C', [field, 'a', field])\n\n def test_keyword_field_names(self):\n for field in ['for', 'async', 'await', 'as']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field, 'a'])\n\n def test_non_identifier_field_names(self):\n for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must be valid identifers'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifers'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifers'):\n make_dataclass('C', [field, 'a'])\n\n def test_underscore_field_names(self):\n # Unlike namedtuple, it's okay if dataclass field names have\n # an underscore.\n make_dataclass('C', ['_', '_a', 'a_a', 'a_'])\n\n def test_funny_class_names_names(self):\n # No reason to prevent weird class names, since\n # types.new_class allows them.\n for classname in ['()', 'x,y', '*', '2@3', '']:\n with self.subTest(classname=classname):\n C = make_dataclass(classname, ['a', 'b'])\n self.assertEqual(C.__name__, classname)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestMakeDataclass","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.7","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_28.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestReplace(unittest.TestCase):\n def test(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n z: int = field(init=False, default=10)\n t: int = field(init=False, default=100)\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))\n self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))\n\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=3, z=20, t=50)\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, z=20)\n replace(c, x=3, z=20, t=50)\n\n # Make sure the result is still frozen.\n with self.assertRaisesRegex(FrozenInstanceError, \"cannot assign to field 'x'\"):\n c1.x = 3\n\n # Make sure we can't replace an attribute that doesn't exist,\n # if we're also replacing one that does exist. Test this\n # here, because setting attributes on frozen instances is\n # handled slightly differently from non-frozen ones.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'a'\"):\n c1 = replace(c, x=20, a=5)\n\n def test_invalid_field_name(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'z'\"):\n c1 = replace(c, z=3)\n\n def test_invalid_object(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(C, x=3)\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(0, x=3)\n\n def test_no_init(self):\n @dataclass\n class C:\n x: int\n y: int = field(init=False, default=10)\n\n c = C(1)\n c.y = 20\n\n # Make sure y gets the default value.\n c1 = replace(c, x=5)\n self.assertEqual((c1.x, c1.y), (5, 10))\n\n # Trying to replace y is an error.\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=2, y=30)\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, y=30)\n\n def test_classvar(self):\n @dataclass\n class C:\n x: int\n y: ClassVar[int] = 1000\n\n c = C(1)\n d = C(2)\n\n self.assertIs(c.y, d.y)\n self.assertEqual(c.y, 1000)\n\n # Trying to replace y is an error: can't replace ClassVars.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an \"\n \"unexpected keyword argument 'y'\"):\n replace(c, y=30)\n\n replace(c, x=5)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestReplace","origin_revision":"v3.7.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_18.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"async def c(): return f'{await 1+foo()}'","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_18.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_01.py","code":"from typing import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_02.py","code":"import typing\nD = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": typing.Literal[\"b\", b\"c\"]})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_05.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {\n # first comment\n \"a\": int, # inline comment\n # second comment\n \"b\": str,\n # third comment\n}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_07.py","code":"from typing_extensions import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_08.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_09.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int}, total=True)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nFoo = TypedDict(\"Foo\", {\"lsts\": List[List[int]]})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_11.py","code":"import typing\nif True:\n if False:\n pass\n D = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_12.py","code":"from typing import TypedDict\nFoo = TypedDict(\"Foo\", {\"union\": str | int | None})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_01.py","code":"from typing import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_02.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_03.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_04.py","code":"import typing\nclass D(typing.TypedDict):\n a: typing.Literal['b', b'c']\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_05.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_06.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n # first comment\n a: int # inline comment\n # second comment\n b: str\n # third comment\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_07.py","code":"from typing_extensions import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_08.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_09.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict, total=True):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nclass Foo(TypedDict):\n lsts: List[List[int]]","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_11.py","code":"import typing\nif True:\n if False:\n pass\n class D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_12.py","code":"from typing import TypedDict\nclass Foo(TypedDict):\n union: str | int | None","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_01.py","code":"from wat import TypedDict\nQ = TypedDict(\"Q\")\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[from imported from elsewhere]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_02.py","code":"import typing\nD = typing.TypedDict(\"D\")","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {}, a=int)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[both]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_05.py","code":"import typing\nD = typing.TypedDict(\"D\", 1)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[not a dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {1: str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not a string]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_07.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a-b\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not an identifier]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_08.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"class\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is a keyword]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_09.py","code":"import typing\nD = typing.TypedDict(\"D\", {**d, \"a\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[dictionary splat operator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_10.py","code":"import typing\nC = typing.TypedDict(\"C\", *types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_11.py","code":"import typing\nD = typing.TypedDict(\"D\", **types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starstarkwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_12.py","code":"import typing\nD = typing.TypedDict(\"D\", x=int, total=False)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[kw_typed_dict with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_01.py","code":"from contextvars import ContextVar\nfrom types import MappingProxyType\nimport re\nimport collections\nimport time\n\n# Okay\nContextVar(\"cv\")\nContextVar(\"cv\", default=())\nContextVar(\"cv\", default=(1, 2, 3))\nContextVar(\"cv\", default=\"foo\")\nContextVar(\"cv\", default=tuple())\nContextVar(\"cv\", default=frozenset())\nContextVar(\"cv\", default=MappingProxyType({}))\nContextVar(\"cv\", default=re.compile(\"foo\"))\nContextVar(\"cv\", default=float(1))\nContextVar(\"cv\", default=frozenset[str]())\nContextVar[frozenset[str]](\"cv\", default=frozenset[str]())\n\n# Bad\nContextVar(\"cv\", default=[])\nContextVar(\"cv\", default={})\nContextVar(\"cv\", default=list())\nContextVar(\"cv\", default=set())\nContextVar(\"cv\", default=dict())\nContextVar(\"cv\", default=[char for char in \"foo\"])\nContextVar(\"cv\", default={char for char in \"foo\"})\nContextVar(\"cv\", default={char: idx for idx, char in enumerate(\"foo\")})\nContextVar(\"cv\", default=collections.deque())\nContextVar(\"cv\", default=set[str]())\nContextVar[set[str]](\"cv\", default=set[str]())\n\ndef bar() -> list[int]:\n return [1, 2, 3]\n\nContextVar(\"cv\", default=bar())\nContextVar(\"cv\", default=time.time())\n\ndef baz(): ...\nContextVar(\"cv\", default=baz())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_02.py","code":"from contextvars import ContextVar\n\nfrom fastapi import Query\nContextVar(\"cv\", default=Query(None))\n\nfrom something_else import Depends\nContextVar(\"cv\", default=Depends())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039_extended.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_01.py","code":"import typing\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, Sequence\n\nKNOWINGLY_MUTABLE_DEFAULT = []\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = []\n immutable_annotation: typing.Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: typing.ClassVar[list[int]] = []\n\n\n@dataclass\nclass B:\n mutable_default: list[int] = []\n immutable_annotation: Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: ClassVar[list[int]] = []\n\n# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n@dataclass\nclass AWithQuotes:\n mutable_default: 'list[int]' = []\n immutable_annotation: 'typing.Sequence[int]' = []\n without_annotation = []\n correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: 'list[int]' = field(default_factory=list)\n class_variable: 'typing.ClassVar[list[int]]'= []\n\n\n# Mutable defaults wrapped in field() calls\n@dataclass\nclass C:\n mutable_default: list[int] = field(default=[]) # RUF008\n mutable_default2: dict[str, int] = field(default={}) # RUF008\n mutable_default3: set[int] = field(default=set()) # RUF008\n mutable_default4: dict[str, int] = field(default=dict()) # RUF008\n correct_factory: list[int] = field(default_factory=list) # okay\n immutable_default: tuple[int, ...] = field(default=()) # okay\n immutable_default2: str = field(default=\"hello\") # okay\n immutable_default3: int = field(default=1) # okay\n non_mutable_var: list[int] = field(default=KNOWINGLY_MUTABLE_DEFAULT) # okay\n class_variable: ClassVar[list[int]] = field(default=[]) # okay\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_02.py","code":"# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n\nfrom __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Example():\n \"\"\"Class that uses ClassVar.\"\"\"\n\n options: ClassVar[dict[str, str]] = {}\n\n\nif typing.TYPE_CHECKING:\n from typing import ClassVar\n\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_03.py","code":"import datetime\nimport re\nimport typing\nfrom dataclasses import dataclass, field\nfrom fractions import Fraction\nfrom pathlib import Path\nfrom typing import ClassVar, NamedTuple\n\n\ndef default_function() -> list[int]:\n return []\n\n\nclass ImmutableType(NamedTuple):\n something: int = 8\n\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\n fine_path: Path = Path()\n fine_date: datetime.date = datetime.date(2042, 1, 1)\n fine_timedelta: datetime.timedelta = datetime.timedelta(hours=7)\n fine_tuple: tuple[int] = tuple([1])\n fine_regex: re.Pattern = re.compile(r\".*\")\n fine_float: float = float(\"-inf\")\n fine_int: int = int(12)\n fine_complex: complex = complex(1, 2)\n fine_str: str = str(\"foo\")\n fine_bool: bool = bool(\"foo\")\n fine_fraction: Fraction = Fraction(1, 2)\n\n\nDEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES = ImmutableType(40)\nDEFAULT_A_FOR_ALL_DATACLASSES = A([1, 2, 3])\n\n\n@dataclass\nclass B:\n hidden_mutable_default: list[int] = default_function()\n another_dataclass: A = A()\n not_optimal: ImmutableType = ImmutableType(20)\n good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES\n okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES\n\n fine_dataclass_function: list[int] = field(default_factory=list)\n\n\nclass IntConversionDescriptor:\n def __init__(self, *, default):\n self._default = default\n\n def __set_name__(self, owner, name):\n self._name = \"_\" + name\n\n def __get__(self, obj, type):\n if obj is None:\n return self._default\n\n return getattr(obj, self._name, self._default)\n\n def __set__(self, obj, value):\n setattr(obj, self._name, int(value))\n\n\n@dataclass\nclass InventoryItem:\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\n\n\n# Regression tests for:\n# https://github.com/astral-sh/ruff/issues/6447\nfrom typing import NewType\n\nListOfStrings = NewType(\"ListOfStrs\", list[str])\nStringsToInts = NewType(\"IntsToStrings\", dict[str, int])\n\nSpecialString = NewType(name=\"SpecialString\", tp=str)\nNegativeInteger = NewType(\"NegInt\", tp=int)\n\nInvalid1 = NewType(*Foo)\nInvalid2 = NewType(\"Invalid2\", name=Foo)\nInvalid3 = NewType(\"Invalid3\", name=Foo, lorem=\"ipsum\")\n\n@dataclass\nclass DataclassWithNewTypeFields:\n # Errors\n a: ListOfStrings = ListOfStrings([])\n b: StringsToInts = StringsToInts()\n c: Invalid1 = Invalid1()\n d: Invalid2 = Invalid2()\n e: Invalid3 = Invalid3()\n\n # No errors\n e: SpecialString = SpecialString(\"Lorem ipsum\")\n f: NegativeInteger = NegativeInteger(-110)\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/15772\ndef f() -> int:\n return 0\n\n@dataclass\nclass ShouldMatchB008RuleOfImmutableTypeAnnotationIgnored:\n this_is_not_fine: list[int] = default_function()\n # ignored\n this_is_fine: int = f()\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/17424\n@dataclass(frozen=True)\nclass C:\n foo: int = 1\n\n\n@dataclass\nclass D:\n c: C = C()\n\n\n@dataclass\nclass E:\n c: C = C()\n\n# https://github.com/astral-sh/ruff/issues/20266\n@dataclass(frozen=True)\nclass C:\n @dataclass(frozen=True)\n class D:\n foo: int = 1\n\n d: D = D() # OK","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_04.py","code":"from dataclasses import dataclass \nfrom typing import TYPE_CHECKING\n\n\ndef default_function() ->list[int]:\n return []\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\nif TYPE_CHECKING:\n from typing import ClassVar\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_05.py","code":"from dataclasses import InitVar, KW_ONLY, MISSING, dataclass, field\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n # Errors\n no_annotation = r\"foo\"\n missing = MISSING\n field = field()\n\n # No errors\n __slots__ = (\"foo\", \"bar\")\n __radd__ = __add__\n _private_attr = 100\n\n with_annotation: str\n with_annotation_and_default: int = 42\n with_annotation_and_field_specifier: bytes = field()\n\n class_var_no_arguments: ClassVar = 42\n class_var_with_arguments: ClassVar[int] = 42\n\n init_var_no_arguments: InitVar = \"lorem\"\n init_var_with_arguments: InitVar[str] = \"ipsum\"\n\n kw_only: KW_ONLY\n tu, ple, [unp, ack, ing] = (0, 1, 2, [3, 4, 5])\n mul, [ti, ple] = (a, ssign), ment = {1: b\"3\", \"2\": 4}, [6j, 5]\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_06.py","code":"from dataclasses import dataclass\nfrom enum import Enum, Flag, IntEnum, IntFlag, StrEnum, ReprEnum\n\nimport attr\nimport attrs\n\n\n## Errors\n\n@dataclass\nclass E(Enum): ...\n\n\n@dataclass # Foobar\nclass E(Flag): ...\n\n\n@dataclass()\nclass E(IntEnum): ...\n\n\n@dataclass() # Foobar\nclass E(IntFlag): ...\n\n\n@dataclass(\n frozen=True\n)\nclass E(StrEnum): ...\n\n\n@dataclass( # Foobar\n frozen=True\n)\nclass E(ReprEnum): ...\n\n\n@dataclass(\n frozen=True\n) # Foobar\nclass E(Enum): ...\n\n\n## No errors\n\n@attrs.define\nclass E(Enum): ...\n\n\n@attrs.frozen\nclass E(Enum): ...\n\n\n@attrs.mutable\nclass E(Enum): ...\n\n\n@attr.s\nclass E(Enum): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_01.py","code":"import typing\nimport typing_extensions\nfrom typing import Literal\n\n# Shouldn't affect non-union field types.\nfield1: Literal[1] # OK\n\n# Should emit for duplicate field types.\nfield2: Literal[1] | Literal[2] # Error\n\n# Should emit for union types in arguments.\ndef func1(arg1: Literal[1] | Literal[2]): # Error\n print(arg1)\n\n\n# Should emit for unions in return types.\ndef func2() -> Literal[1] | Literal[2]: # Error\n return \"my Literal[1]ing\"\n\n\n# Should emit in longer unions, even if not directly adjacent.\nfield3: Literal[1] | Literal[2] | str # Error\nfield4: str | Literal[1] | Literal[2] # Error\nfield5: Literal[1] | str | Literal[2] # Error\nfield6: Literal[1] | bool | Literal[2] | str # Error\n\n# Should emit for non-type unions.\nfield7 = Literal[1] | Literal[2] # Error\n\n# Should emit for parenthesized unions.\nfield8: Literal[1] | (Literal[2] | str) # Error\n\n# Should handle user parentheses when fixing.\nfield9: Literal[1] | (Literal[2] | str) # Error\nfield10: (Literal[1] | str) | Literal[2] # Error\n\n# Should emit for union in generic parent type.\nfield11: dict[Literal[1] | Literal[2], str] # Error\n\n# Should emit for unions with more than two cases\nfield12: Literal[1] | Literal[2] | Literal[3] # Error\nfield13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error\n\n# Should emit for unions with more than two cases, even if not directly adjacent\nfield14: Literal[1] | Literal[2] | str | Literal[3] # Error\n\n# Should emit for unions with mixed literal internal types\nfield15: Literal[1] | Literal[\"foo\"] | Literal[True] # Error\n\n# Shouldn't emit for duplicate field types with same value; covered by Y016\nfield16: Literal[1] | Literal[1] # OK\n\n# Shouldn't emit if in new parent type\nfield17: Literal[1] | dict[Literal[2], str] # OK\n\n# Shouldn't emit if not in a union parent\nfield18: dict[Literal[1], Literal[2]] # OK\n\n# Should respect name of literal type used\nfield19: typing.Literal[1] | typing.Literal[2] # Error\n\n# Should emit in cases with newlines\nfield20: typing.Union[\n Literal[\n 1 # test\n ],\n Literal[2],\n] # Error, newline and comment will not be emitted in message\n\n# Should handle multiple unions with multiple members\nfield21: Literal[1, 2] | Literal[3, 4] # Error\n\n# Should emit in cases with `typing.Union` instead of `|`\nfield22: typing.Union[Literal[1], Literal[2]] # Error\n\n# Should emit in cases with `typing_extensions.Literal`\nfield23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error\n\n# Should emit in cases with nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error\n\n# Should emit in cases with mixed `typing.Union` and `|`\nfield25: typing.Union[Literal[1], Literal[2] | str] # Error\n\n# Should emit only once in cases with multiple nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error\n\n# Should use the first literal subscript attribute when fixing\nfield25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error\n\nfrom typing import IO, Literal\n\nInlineOption = Literal[\"a\"] | Literal[\"b\"] | IO[str]\n\n# Should use unsafe fix when comments are deleted\nfield26: (\n # First comment\n Literal[\"a\", \"b\"]\n # Second comment\n | Literal[\"c\", \"d\"]\n)\nfield27: (\n Literal[\"a\", \"b\"] # First comment\n | Literal[\"c\", \"d\"] # Second comment\n)\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI030.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_02.py","code":"import typing\nfrom typing import Literal, TypeAlias, Union\n\nA: str | Literal[\"foo\"]\nB: TypeAlias = typing.Union[Literal[b\"bar\", b\"foo\"], bytes, str]\nC: TypeAlias = typing.Union[Literal[5], int, typing.Union[Literal[\"foo\"], str]]\nD: TypeAlias = typing.Union[Literal[b\"str_bytes\", 42], bytes, int]\nE: TypeAlias = typing.Union[typing.Union[typing.Union[typing.Union[Literal[\"foo\"], str]]]]\nF: TypeAlias = typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\nG: typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\n\ndef func(x: complex | Literal[1J], y: Union[Literal[3.14], float]): ...\n\n# OK\nA: Literal[\"foo\"]\nB: TypeAlias = Literal[b\"bar\", b\"foo\"]\nC: TypeAlias = typing.Union[Literal[5], Literal[\"foo\"]]\nD: TypeAlias = Literal[b\"str_bytes\", 42]\n\ndef func(x: Literal[1J], y: Literal[3.14]): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI051.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_03.py","code":"from typing import Literal\nimport typing as t\nimport typing_extensions\n\nx: Literal[True, False, True, False] # PYI062 twice here\n\ny: Literal[1, print(\"hello\"), 3, Literal[4, 1]] # PYI062 on the last 1\n\nz: Literal[{1, 3, 5}, \"foobar\", {1,3,5}] # PYI062 on the set literal\n\nLiteral[1, Literal[1]] # once\nLiteral[1, 2, Literal[1, 2]] # twice\nLiteral[1, Literal[1], Literal[1]] # twice\nLiteral[1, Literal[2], Literal[2]] # once\nt.Literal[1, t.Literal[2, t.Literal[1]]] # once\ntyping_extensions.Literal[1, 1, 1] # twice\nLiteral[\n 1, # comment\n Literal[ # another comment\n 1\n ]\n] # once\n\n# Ensure issue is only raised once, even on nested literals\nMyType = Literal[\"foo\", Literal[True, False, True], \"bar\"] # PYI062\n\nn: Literal[\"No\", \"duplicates\", \"here\", 1, \"1\"]\n\n\n# nested literals, all equivalent to `Literal[1]`\nLiteral[Literal[1]] # no duplicate\nLiteral[Literal[Literal[1], Literal[1]]] # once\nLiteral[Literal[1], Literal[Literal[Literal[1]]]] # once\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI062.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_01.py","code":"# parse_options: {\"target-version\": \"3.8\"}\ndef foo(a, /): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pos_only_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_02.py","code":"lambda: a\nlambda: 1\nlambda x: 1\nlambda x, y: ...\nlambda a, b, c: 1\nlambda a, b=20, c=30: 1\nlambda x, y: x * y\nlambda y, z=1: z * y\nlambda *a: a\nlambda *a, z, x=0: ...\nlambda *, a, b, c: 1\nlambda *, a, b=20, c=30: 1\nlambda a, b, c, *, d, e: 0\nlambda **kwargs: f()\nlambda *args, **kwargs: f() + 1\nlambda *args, a, b=1, **kwargs: f() + 1\nlambda a, /: ...\nlambda a, /, b: ...\nlambda a=1, /,: ...\nlambda a, b, /, *, c: ...\nlambda kw=1, *, a: ...\nlambda a, b=20, /, c=30: 1\nlambda a, b, /, c, *, d, e: 0\nlambda a, b, /, c, *d, e, **f: 0","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/lambda.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_01.py","code":"# parse_options: {\"target-version\": \"3.14\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_function_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_03.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/walrus_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_04.py","code":"[a := 0 for x in range(0)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_rebound_comprehension_variable.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_05.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[(x:=1)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_06.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{(x := 1), 2, 3}\n{(last := x) for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_07.py","code":"class F(y := list): ...\ndef f():\n class G((yield 1)): ...\n class H((yield from 1)): ...\nasync def f():\n class G((await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_08.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_function_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_09.py","code":"# parse_options: {\"target-version\": \"3.13\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_10.py","code":"# parse_options: { \"target-version\": \"3.8\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/walrus_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_11.py","code":"# Simple\n{}\n{1: 2}\n{1: 2, a: 1, b: 'hello'}\n\n# Mixed indentations\n{\n}\n{\n 1:\n 2,\n 3\n :4\n}\n\n# Nested\n{{1: 2}: {3: {4: 5}}}\n\n# Lambda expressions\n{lambda x: x: 1}\n{'A': lambda p: None, 'B': C,}\n\n# Named expressions\n{(x := 1): y}\n{(x := 1): (y := 2)}\n\n# Double star unpacking\n{**d}\n{a: b, **d}\n{**a, **b}\n{\"a\": \"b\", **c, \"d\": \"e\"}\n{1: 2, **{'nested': 'dict'}}\n{x * 1: y ** 2, **call()}\n# Here, `not` isn't allowed but parentheses resets the precedence\n{**(not x)}\n\n# Random expressions\n{1: x if True else y}\n{x if True else y: y for x in range(10) for y in range(10)}\n{{1, 2}: 3, x: {1: 2,},}\n{(x): (y), (z): (a)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/dictionary.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_12.py","code":"(x for target in iter)\n(x async for target in iter)\n(x for target in iter if x in y if a and b if c)\n(x for target1 in iter1 if x and y for target2 in iter2 if a > b)\n(x for target1 in iter1 if x and y async for target2 in iter2 if a > b)\n\n# Named expression\n(x := y + 1 for y in z)\n\n# If expression\n(x if y else y for y in z)\n\n# Arguments\n\" \".join(\n sql\n for sql in (\n \"LIMIT %d\" % limit if limit else None,\n (\"OFFSET %d\" % offset) if offset else None,\n )\n)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/generator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_13.py","code":"# Simple lists\n[]\n[1]\n[1,]\n[1, 2, 3]\n[1, 2, 3,]\n\n# Mixed with indentations\n[\n]\n[\n 1\n]\n[\n 1,\n 2,\n]\n\n# Nested\n[[[1]]]\n[[1, 2], [3, 4]]\n\n# Named expression\n[x := 2]\n[x := 2,]\n[1, x := 2, 3]\n\n# Star expression\n[1, *x, 3]\n[1, *x | y, 3]\n\n# Random expressions\n[1 + 2, [1, 2, 3, 4], (a, b + c, d), {a, b, c}, {a: 1}, x := 2]\n[call1(call2(value.attr()) for element in iter)]\n[item in xs]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/list.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_14.py","code":"(name := 0)\n(name := (x * y))\n(name := 1 + 1)\n(name := (*x, y))\n(name := x if True else y)\n(name := lambda x: x)\n(name := (yield x))\n(name := (yield from x))","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/named.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_15.py","code":"(expr)\n(expr)()\n(expr)()()()\n\n(a and b or c)\n(lambda x: x)\n(x := 2)\n(yield x)\n(yield from x)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/parenthesized.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_16.py","code":"# With parentheses\n()\n(())\n((()), ())\n(a,)\n(a, b)\n(a, b,)\n((a, b))\n\n# Without parentheses\na,\na, b\na, b,\n\n# Starred expression\n*a,\na, *b\n*a | b, *await x, (), *()\n(*a,)\n(a, *b)\n(*a | b, *await x, (), *())\n\n# Named expression\n(x := 1,)\n(x, y := 2)\n(x, y := 2, z)\nx, (y := 2), z\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_17.py","code":"# Simple\n-1\n+1\n~1\nnot x\n\n# Multiple\n---1\n-+~1\nnot-+~1\nnot not x\n\n# Precedence check\n- await 1\n+ await 1 ** -2\n~(1, 2)\n-1 + 2\n\n# Precedence check for `not` operator because it is higher than other unary operators\nnot a and b or not c | d and not e\nnot (x := 1)\nnot a | (not b)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/unary_op.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_18.py","code":"yield\nyield x\nyield x + 1\nyield x and y\nyield call()\nyield [1, 2]\nyield {3, 4}\nyield {x: 5}\nyield x, y\nyield (x, y)\nyield x == y\nyield (x := 1)\nyield x, *y\nyield *x,\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_19.py","code":"yield from x\nyield from x + 1\nyield from x and y\nyield from call()\nyield from [1, 2]\nyield from {3, 4}\nyield from {x: 5}\nyield from (x, y)\nyield from x == y\nyield from (x := 1)\nyield from (x, *x | y)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield_from.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_20.py","code":"if 1: 10\nelif 2: 20\nelse: 30\n\nif True:\n 1\n ...\nif x < 1:\n ...\nelse:\n pass\n\nif a:\n pass\nelif b:\n ...\n\nif a and b:\n ...\nelif True:\n ...\nelif c:\n ...\nelif d:\n ...\nelse:\n f()\n\n# Valid test expression\nif a := b: ...\nelif a := b: ...\nif lambda x: x: ...\nelif lambda x: x: ...\nif await x: ...\nelif await x: ...\nif (yield x): ...\nelif (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/if.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_21.py","code":"return\nreturn x\nreturn *x, *y\nreturn (x := 1)\nreturn None\nreturn x and y\nreturn 1 < 2\nreturn 1, 2,\nreturn call()\nreturn attr.value()\nreturn await x\nreturn lambda x: y\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/return.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_22.py","code":"while x:\n ...\n\nwhile (x > 1) and y:\n pass\nelse:\n ...\n\nwhile x and y:\n ...\n print('Hello World!')\n\nelse:\n print('Olá, Mundo!')\n ...\n\nwhile a := b: ...\nwhile (a := b) and c: ...\nwhile lambda x: x: ...\nwhile await x: ...\n\nif True:\n while x:\n pass\n else:\n pass\nelse:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/while.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_07.py","code":"\"\"\"\nTests the handling of descriptors within a dataclass.\n\"\"\"\n\n# This portion of the dataclass spec is under-specified in the documentation,\n# but its behavior can be determined from the runtime implementation.\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, TypeVar, assert_type, overload\n\nT = TypeVar(\"T\")\n\n\nclass Desc1:\n @overload\n def __get__(self, __obj: None, __owner: Any) -> \"Desc1\":\n ...\n\n @overload\n def __get__(self, __obj: object, __owner: Any) -> int:\n ...\n\n def __get__(self, __obj: object | None, __owner: Any) -> \"int | Desc1\":\n raise NotImplementedError\n\n def __set__(self, __obj: object, __value: int) -> None:\n ...\n\n\n@dataclass\nclass DC1:\n y: Desc1 = Desc1()\n\n\ndc1 = DC1(3)\n\nassert_type(dc1.y, int)\nassert_type(DC1.y, Desc1)\n\n\nclass Desc2(Generic[T]):\n @overload\n def __get__(self, instance: None, owner: Any) -> list[T]:\n ...\n\n @overload\n def __get__(self, instance: object, owner: Any) -> T:\n ...\n\n def __get__(self, instance: object | None, owner: Any) -> list[T] | T:\n raise NotImplementedError\n\n\n@dataclass\nclass DC2:\n x: Desc2[int]\n y: Desc2[str]\n z: Desc2[str] = Desc2()\n\n\nassert_type(DC2.x, list[int])\nassert_type(DC2.y, list[str])\nassert_type(DC2.z, list[str])\n\ndc2 = DC2(Desc2(), Desc2(), Desc2())\nassert_type(dc2.x, int)\nassert_type(dc2.y, str)\nassert_type(dc2.z, str)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_descriptors.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_08.py","code":"\"\"\"\nTests validation of frozen dataclass instances.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#frozen-instances\n\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass DC1:\n a: float\n b: str\n\ndc1 = DC1(1, \"\")\n\ndc1.a = 1 # E: dataclass is frozen\ndc1.b = \"\" # E: dataclass is frozen\n\n\n# This should generate an error because a non-frozen dataclass\n# cannot inherit from a frozen dataclass.\n@dataclass # E[DC2]\nclass DC2(DC1): # E[DC2]\n pass\n\n@dataclass\nclass DC3:\n a: int\n\n# This should generate an error because a frozen dataclass\n# cannot inherit from a non-frozen dataclass.\n@dataclass(frozen=True) # E[DC4]\nclass DC4(DC3): # E[DC4]\n pass\n\n\n@dataclass(frozen=True)\nclass DC1Child(DC1):\n # This should be allowed because attributes within a frozen\n # dataclass are covariant rather than invariant.\n a: int\n","source":"typing_tests","origin":"conformance/tests/dataclasses_frozen.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_09.py","code":"\"\"\"\nTests the synthesis of the __hash__ method in a dataclass.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Callable, Hashable, assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n\n\nassert_type(DC1.__hash__, None)\n\n# These should generate errors because DC1 isn't hashable.\nDC1(0).__hash__() # E\nv1: Hashable = DC1(0) # E\n\n\n@dataclass(eq=True, frozen=True)\nclass DC2:\n a: int\n\n\ndc2_hash: Callable[..., int] = DC2.__hash__ # OK\nDC2(0).__hash__() # OK\nv2: Hashable = DC2(0) # OK\n\n\n@dataclass(eq=True)\nclass DC3:\n a: int\n\n\nassert_type(DC3.__hash__, None)\n\n# These should generate errors because DC3 isn't hashable.\nDC3(0).__hash__() # E\nv3: Hashable = DC3(0) # E\n\n\n@dataclass(frozen=True)\nclass DC4:\n a: int\n\n\ndc4_hash: Callable[..., int] = DC4.__hash__ # OK\nDC4(0).__hash__() # OK\nv4: Hashable = DC4(0) # OK\n\n\n@dataclass(eq=True, unsafe_hash=True)\nclass DC5:\n a: int\n\n\ndc5_hash: Callable[..., int] = DC5.__hash__ # OK\nDC5(0).__hash__() # OK\nv5: Hashable = DC5(0) # OK\n\n\n@dataclass(eq=True)\nclass DC6:\n a: int\n\n def __hash__(self) -> int:\n return 0\n\n\ndc6_hash: Callable[..., int] = DC6.__hash__ # OK\nDC6(0).__hash__() # OK\nv6: Hashable = DC6(0) # OK\n\n\n@dataclass(frozen=True)\nclass DC7:\n a: int\n\n def __eq__(self, other) -> bool:\n return self.a == other.a\n\n\ndc7_hash: Callable[..., int] = DC7.__hash__ # OK\nDC7(0).__hash__() # OK\nv7: Hashable = DC7(0) # OK\n","source":"typing_tests","origin":"conformance/tests/dataclasses_hash.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_10.py","code":"\"\"\"\nTests inheritance rules for dataclasses.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#inheritance\n\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar\n\n\n@dataclass\nclass DC1:\n a: int\n b: str = \"\"\n\n\n@dataclass\nclass DC2(DC1):\n b: str = \"\"\n a: int = 1\n\n\ndc2_1 = DC2(1, \"\")\n\ndc2_2 = DC2()\n\n\n@dataclass\nclass DC3:\n x: float = 15.0\n y: str = \"\"\n\n\n@dataclass\nclass DC4(DC3):\n z: tuple[int] = (10,)\n x: float = 15\n\n\ndc4_1 = DC4(0.0, \"\", (1,))\n\n\n@dataclass\nclass DC5:\n # While this generates an error at runtime for the stdlib dataclass,\n # other libraries that use dataclass_transform don't have similar\n # restrictions. It is therefore not required that a type checker\n # report an error here.\n x: list[int] = [] # E?\n\n\n@dataclass\nclass DC6:\n x: int\n y: ClassVar[int] = 1\n\n\n@dataclass\nclass DC7(DC6):\n # This should generate an error because a ClassVar cannot override\n # an instance variable of the same name.\n x: ClassVar[int] # E\n\n # This should generate an error because an instance variable cannot\n # override a class variable of the same name.\n y: int # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_11.py","code":"\"\"\"\nTests the keyword-only feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY, field\n\n\n@dataclass\nclass DC1:\n a: str\n _: KW_ONLY\n b: int = 0\n\n\nDC1(\"hi\")\nDC1(a=\"hi\")\nDC1(a=\"hi\", b=1)\nDC1(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC1(\"hi\", 1) # E\n\n\n@dataclass\nclass DC2:\n b: int = field(kw_only=True, default=3)\n a: str\n\n\nDC2(\"hi\")\nDC2(a=\"hi\")\nDC2(a=\"hi\", b=1)\nDC2(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC2(\"hi\", 1) # E\n\n\n@dataclass(kw_only=True)\nclass DC3:\n a: str = field(kw_only=False)\n b: int = 0\n\n\nDC3(\"hi\")\nDC3(a=\"hi\")\nDC3(a=\"hi\", b=1)\nDC3(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC3(\"hi\", 1) # E\n\n\n@dataclass\nclass DC4(DC3):\n c: float\n\n\nDC4(\"\", 0.2, b=3)\nDC4(a=\"\", b=3, c=0.2)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_kwonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_12.py","code":"\"\"\"\nTests the match_args feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY\nfrom typing import assert_type, Literal\n\n# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method\n\n@dataclass(match_args=True)\nclass DC1:\n x: int\n _: KW_ONLY\n y: str\n\nassert_type(DC1.__match_args__, tuple[Literal['x']])\n\n# The match_args default is True\n\n@dataclass\nclass DC2:\n x: int\n\nassert_type(DC2.__match_args__, tuple[Literal['x']])\n\n# __match_args__ is created even if __init__() is not generated\n\n@dataclass(match_args=True, init=False)\nclass DC3:\n x: int = 0\n\nassert_type(DC3.__match_args__, tuple[Literal['x']])\n\n# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.\n\n@dataclass(match_args=False)\nclass DC4:\n x: int\n\nDC4.__match_args__ # E\n\n@dataclass(match_args=True)\nclass DC5:\n __match_args__ = ()\n x: int\n\nassert_type(DC5.__match_args__, tuple[()])\n","source":"typing_tests","origin":"conformance/tests/dataclasses_match_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_13.py","code":"\"\"\"\nTests the synthesized comparison methods for dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass DC1:\n a: str\n b: int\n\n\n@dataclass(order=True)\nclass DC2:\n a: str\n b: int\n\n\ndc1_1 = DC1(\"\", 0)\ndc1_2 = DC1(\"\", 0)\n\nif dc1_1 < dc1_2:\n pass\n\nif dc1_1 <= dc1_2:\n pass\n\nif dc1_1 > dc1_2:\n pass\n\nif dc1_1 >= dc1_2:\n pass\n\nif dc1_1 == dc1_2:\n pass\n\nif dc1_1 != dc1_2:\n pass\n\nif dc1_1 == None:\n pass\n\nif dc1_1 != None:\n pass\n\ndc2_1 = DC2(\"hi\", 2)\n\n# This should generate an error because the types are\n# incompatible.\nif dc1_1 < dc2_1: # E:\n pass\n\nif dc1_1 != dc2_1:\n pass\n","source":"typing_tests","origin":"conformance/tests/dataclasses_order.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_14.py","code":"\"\"\"\nTests type checking of the __post_init__ method in a dataclass.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#post-init-processing\n\nfrom dataclasses import InitVar, dataclass, field, replace\nfrom typing import assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n b: int\n x: InitVar[int]\n c: int\n y: InitVar[str]\n\n def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y\n pass\n\n\ndc1 = DC1(1, 2, 3, 4, \"\")\n\nassert_type(dc1.a, int)\nassert_type(dc1.b, int)\nassert_type(dc1.c, int)\nprint(dc1.x) # E: cannot access InitVar\nprint(dc1.y) # E: cannot access InitVar\n\n@dataclass\nclass DC2:\n x: InitVar[int]\n y: InitVar[str]\n\n def __post_init__(self, x: int) -> None: # E: missing y\n pass\n\n\n@dataclass\nclass DC3:\n _name: InitVar[str] = field()\n name: str = field(init=False)\n\n def __post_init__(self, _name: str):\n ...\n\n\n@dataclass\nclass DC4(DC3):\n _age: InitVar[int] = field()\n age: int = field(init=False)\n\n def __post_init__(self, _name: str, _age: int):\n ...\n","source":"typing_tests","origin":"conformance/tests/dataclasses_postinit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_15.py","code":"\"\"\"\nTests the slots functionality of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass\n\n# This should generate an error because __slots__ is already defined.\n@dataclass(slots=True) # E[DC1]\nclass DC1: # E[DC1]\n x: int\n\n __slots__ = ()\n\n\n@dataclass(slots=True)\nclass DC2:\n x: int\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass(slots=False)\nclass DC3:\n x: int\n\n __slots__ = (\"x\",)\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass\nclass DC4:\n __slots__ = (\"y\", \"x\")\n x: int\n y: str\n\n\nDC4(1, \"bar\")\n\n\n@dataclass(slots=True)\nclass DC5:\n a: int\n\n\nDC5.__slots__\nDC5(1).__slots__\n\n\n@dataclass\nclass DC6:\n a: int\n\n\n# This should generate an error because __slots__ is not defined.\nDC6.__slots__ # E\n\n# This should generate an error because __slots__ is not defined.\nDC6(1).__slots__ # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_slots.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_16.py","code":"\"\"\"\nTests basic handling of the dataclass factory.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html\n# Also, see https://peps.python.org/pep-0557/\n\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar, assert_type\nimport sys\n\nT = TypeVar(\"T\")\n\n\n@dataclass(order=True)\nclass InventoryItem:\n x = 0\n name: str\n unit_price: float\n quantity_on_hand: int = 0\n\n def total_cost(self) -> float:\n return self.unit_price * self.quantity_on_hand\n\n\nv1 = InventoryItem(\"soap\", 2.3)\n\n\nclass InventoryItemInitProto(Protocol):\n def __call__(\n self, name: str, unit_price: float, quantity_on_hand: int = ...\n ) -> None: ...\n\n\n# Validate the type of the synthesized __init__ method.\nx1: InventoryItemInitProto = v1.__init__\n\n# Make sure the following additional methods were synthesized.\nprint(v1.__repr__)\nprint(v1.__eq__)\nprint(v1.__ne__)\nprint(v1.__lt__)\nprint(v1.__le__)\nprint(v1.__gt__)\nprint(v1.__ge__)\n\nassert_type(v1.name, str)\nassert_type(v1.unit_price, float)\nassert_type(v1.quantity_on_hand, int)\n\nv2 = InventoryItem(\"name\") # E: missing unit_price\nv3 = InventoryItem(\"name\", \"price\") # E: incorrect type for unit_price\nv4 = InventoryItem(\"name\", 3.1, 3, 4) # E: too many arguments\n\n\n# > TypeError will be raised if a field without a default value follows a\n# > field with a default value. This is true either when this occurs in a\n# > single class, or as a result of class inheritance.\n@dataclass # E[DC1]\nclass DC1:\n a: int = 0 # E[DC1]: field with default should follow a field with no default.\n b: int # E[DC1]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC2]\nclass DC2:\n a: int = field(default=1) # E[DC2]: field with default should follow a field with no default.\n b: int # E[DC2]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC3]\nclass DC3:\n a: InitVar[int] = 0 # E[DC3]: field with default should follow a field with no default.\n b: int # E[DC3]: field with no default cannot follow field with default.\n\n\n@dataclass\nclass DC4:\n a: int = field(init=False)\n b: int\n\n\nv5 = DC4(0)\nv6 = DC4(0, 1) # E: too many parameters\n\n\n@dataclass\nclass DC5:\n a: int = field(default_factory=str) # E: type mismatch\n\n\ndef f(s: str) -> int:\n return int(s)\n\n\n@dataclass\nclass DC6:\n a: ClassVar[int] = 0\n b: str\n c: Callable[[str], int] = f\n\n\ndc6 = DC6(\"\")\nassert_type(dc6.a, int)\nassert_type(DC6.a, int)\nassert_type(dc6.b, str)\nassert_type(dc6.c, Callable[[str], int])\n\n\n@dataclass\nclass DC7:\n x: int\n\n\n@dataclass(init=False)\nclass DC8(DC7):\n y: int\n\n def __init__(self, a: DC7, y: int):\n self.__dict__ = a.__dict__\n self.y = y\n\n\na = DC7(3)\nb = DC8(a, 5)\n\n# This should generate an error because there is an extra parameter\nDC7(3, 4) # E\n\n# This should generate an error because there is one too few parameters\nDC8(a) # E\n\n\n@dataclass\nclass DC9:\n a: str = field(init=False, default=\"s\")\n b: bool = field()\n\n\n@dataclass\nclass DC10(DC9):\n a: str = field()\n b: bool = field()\n\n\n@dataclass(init=False)\nclass DC11:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC11(3)\n\n\n@dataclass(init=True)\nclass DC12:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC12(3)\n\n\n@dataclass(init=False)\nclass DC13:\n x: int\n x_squared: int\n\n\n# This should generate an error because there is no matching\n# override __init__ method and no synthesized __init__.\nDC13(3) # E\n\n\n@dataclass\nclass DC14:\n prop_1: str = field(init=False)\n prop_2: str = field(default=\"hello\")\n prop_3: str = field(default_factory=lambda: \"hello\")\n\n\n@dataclass\nclass DC15(DC14):\n prop_2: str = \"\"\n\n\ndc15 = DC15(prop_2=\"test\")\n\nassert_type(dc15.prop_1, str)\nassert_type(dc15.prop_2, str)\nassert_type(dc15.prop_3, str)\n\n\nclass DataclassProto(Protocol):\n __dataclass_fields__: ClassVar[dict[str, Any]]\n\n\nv7: DataclassProto = dc15\n\n\n@dataclass\nclass DC16(Generic[T]):\n value: T\n\n\nassert_type(DC16(1), DC16[int])\n\n\nclass DC17(DC16[str]):\n pass\n\n\nassert_type(DC17(\"\"), DC17)\n\n\n@dataclass\nclass DC18:\n x: int = field()\n # This may generate a type checker error because an unannotated field\n # will result in a runtime exception.\n y = field() # E?\n\n\n# > Dataclass fields may be conditional, via checks of the same\n# > statically-known conditions that a type-checker understands elsewhere,\n# > such as Python version:\n\n@dataclass\nclass DC19:\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nDC19(1, 2)\nDC19(1, 2, 3) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_01.py","code":"\"\"\"\nTests the handling of ClassVar and Final in dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import assert_type, ClassVar, Final\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#dataclass-semantics\n\n# > A final class variable on a dataclass must be explicitly annotated as\n# e.g. x: ClassVar[Final[int]] = 3.\n\n\n@dataclass\nclass D:\n final_no_default: Final[int]\n final_with_default: Final[str] = \"foo\"\n final_classvar: ClassVar[Final[int]] = 4\n # we don't require support for Final[ClassVar[...]] because the dataclasses\n # runtime implementation won't recognize it as a ClassVar either\n\n\n# An explicitly marked ClassVar can be accessed on the class:\nassert_type(D.final_classvar, int)\n\n# ...but not assigned to, because it's Final:\nD.final_classvar = 10 # E: can't assign to final attribute\n\n# A non-ClassVar attribute (with or without default) is a dataclass field:\nd = D(final_no_default=1, final_with_default=\"bar\")\nassert_type(d.final_no_default, int)\nassert_type(d.final_with_default, str)\n\n# ... but can't be assigned to (on the class or on an instance):\nd.final_no_default = 10 # E: can't assign to final attribute\nd.final_with_default = \"baz\" # E: can't assign to final attribute\nD.final_no_default = 10 # E: can't assign to final attribute\nD.final_with_default = \"baz\" # E: can't assign to final attribute\n","source":"typing_tests","origin":"conformance/tests/dataclasses_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_02.py","code":"\"\"\"\nTests the typing.Final special form.\n\"\"\"\n\nfrom typing import ClassVar, Final, Literal, NamedTuple, TypedDict, assert_type\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#id1\n\nID1: Final[int] = 1\n\nID2: Final = 1\nassert_type(ID2, Literal[1])\n\n# > If the right hand side is omitted, there must be an explicit type argument to Final.\n\nBAD1: Final # E: missing assignment\n\nBAD2: Final[str, int] = \"\" # E: only one type argument allowed\n\n# > There can be at most one final declaration per module or class for a given\n# > attribute.\n\n# > As self.id: Final = 1 (also optionally with a type in square brackets).\n# > This is allowed only in __init__ methods, so that the final instance\n# > attribute is assigned only once when an instance is created.\n\n\nclass ClassA:\n ID1: Final = 1\n\n # > In class bodies and stub files you can omit the right hand side and just\n # > write ID: Final[float]. If the right hand side is omitted, there must be\n # > an explicit type argument to Final.\n ID2: Final # E: missing initialization\n\n # > A final attribute declared in a class body without an initializer must\n # > be initialized in the __init__ method (except in stub files):\n ID3: Final[int] # E: missing initialization\n\n ID4: Final[int] # OK because initialized in __init__\n\n ID5: Final[int] = 0\n\n ID6: Final[int]\n\n ID7: Final[int] = 0\n\n def __init__(self, cond: bool) -> None:\n self.id1: Final = 1\n self.id2: Final[int] = 1\n\n self.ID4 = 1\n\n self.ID5 = 0 # E: Already initialized\n\n if cond:\n self.ID6 = 1\n else:\n self.ID6 = 2\n\n def method1(self) -> None:\n self.id3: Final = 1 # E: not allowed outside of __init__ method.\n self.id4: Final[int] = 1 # E: not allowed outside of __init__ method.\n\n self.ID7 = 0 # E: cannot modify Final value\n\n self.ID7 += 1 # E: cannot modify Final value\n\n\nRATE: Final = 3000\nRATE = 300 # E: Cannot redefine Final value\n\n# > There can’t be separate class-level and instance-level constants\n# > with the same name.\n\n\nclass ClassB:\n DEFAULT_ID: Final = 0\n\n\nClassB.DEFAULT_ID = 0 # E: Cannot redefined value\n\n\n# > A type checker should prevent final attributes from being overridden in a subclass:\n\n\nclass ClassC:\n BORDER_WIDTH: Final = 2.5\n\n __private: Final = 0\n\n\nclass ClassCChild(ClassC):\n BORDER_WIDTH = 2.5 # E: Cannot override Final value\n\n __private = 0 # OK\n\n\n# > Type checkers should infer a final attribute that is initialized in a class\n# > body as being a class variable. Variables should not be annotated with both\n# > ClassVar and Final. (Except in a dataclass; see dataclasses_final.py.)\n\n\nclass ClassD:\n VALUE1: Final = 1\n\n VALUE2: ClassVar[Final] = 1 # E: Final cannot be used with ClassVar\n VALUE3: Final[ClassVar] = 1 # E: Final cannot be used with ClassVar\n\n\nClassD.VALUE1 # OK\n\n\n# > Final may only be used as the outermost type in assignments or variable\n# > annotations. Using it in any other position is an error. In particular,\n# > Final can’t be used in annotations for function arguments.\n\nx: list[Final[int]] = [] # E\n\n\ndef func1(x: Final[list[int]]) -> None: # E\n ...\n\n\n# > ``Final`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithFinal(TypedDict):\n a: int\n b: Final[int] # E: Final not allowed in a TypedDict\n\n\nclass NTWithFinal(NamedTuple):\n a: int\n b: Final[int] # E: Final not allowed in a NamedTuple\n\n\n# > Type checkers should treat uses of a final name that was initialized with\n# > a literal as if it was replaced by the literal. For example, the following\n# > should be allowed:\n\nX: Final = \"x\"\nY: Final = \"y\"\nN = NamedTuple(\"N\", [(X, int), (Y, int)])\n\nN(x=3, y=4) # OK\nN(a=1) # E\nN(x=\"\", y=\"\") # E\n\n\ndef func2() -> None:\n global ID1\n\n ID1 = 2 # E: cannot modify Final value\n\n x: Final = 3\n\n x += 1 # E: cannot modify Final value\n\n a = (x := 4) # E: cannot modify Final value\n\n for x in [1, 2, 3]: # E: cannot modify Final value\n pass\n\n with open(\"FileName\") as x: # E: cannot modify Final value\n pass\n\n (a, x) = (1, 2) # E: cannot modify Final value\n\n\n# > If a module declares a ``Final`` variable and another module imports that\n# > variable in an import statement by name or wildcard, the imported symbol\n# > inherits the ``Final`` type qualifier. Any attempt to assign a different value\n# > to this symbol should be flagged as an error by a type checker.\n\n\nfrom _qualifiers_final_annotation_1 import TEN\n\nTEN = 9 # E: Cannot redefine Final value\n\nfrom _qualifiers_final_annotation_2 import *\n\nPI = 3.14159 # E: Cannot redefine Final value\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_03.py","code":"\"\"\"\nTests the @final decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#final\n\nfrom typing import final, overload\nfrom _qualifiers_final_decorator import Base3, Base4\n\n# > A type checker should prohibit any class decorated with @final from being\n# > subclassed and any method decorated with @final from being overridden in a\n# > subclass. The method decorator version may be used with all of instance\n# > methods, class methods, static methods, and properties.\n\n\n@final\nclass Base1:\n ...\n\n\nclass Derived1(Base1): # E: Cannot inherit from final class \"Base\"\n ...\n\n\nclass Base2:\n @final\n def method1(self) -> None:\n pass\n\n @final\n @classmethod\n def method2(cls) -> None:\n pass\n\n @final\n @staticmethod\n def method3() -> None:\n pass\n\n # > For overloaded methods, @final should be placed on the implementation.\n\n @overload\n def method4(self, x: int) -> int:\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @final\n def method4(self, x: int | str) -> int | str:\n return 0\n\n\nclass Derived2(Base2):\n def method1(self) -> None: # E\n pass\n\n @classmethod # E[method2]\n def method2(cls) -> None: # E[method2]\n pass\n\n @staticmethod # E[method3]\n def method3() -> None: # E[method3]\n pass\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n def method4(self, x: int | str) -> int | str: # E[method4]\n return 0\n\n\nclass Derived3(Base3):\n @overload # E[Derived3]\n def method(self, x: int) -> int: # E[Derived3]\n ...\n\n @overload # E[Derived3-2]\n @final # E[Derived3-2]: should be applied only to implementation\n def method(self, x: str) -> str: # E[Derived3-2]\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived3]\n return 0\n\n\nclass Derived4(Base4):\n @overload # E[Derived4]\n def method(self, x: int) -> int: # E[Derived4]\n ...\n\n @overload\n def method(self, x: str) -> str:\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived4]\n return 0\n\n\nclass Base5_1:\n ...\n\n\nclass Base5_2:\n @final\n def method(self, v: int) -> None:\n ...\n\n\n# Test multiple inheritance case.\nclass Derived5(Base5_1, Base5_2):\n def method(self) -> None: # E\n ...\n\n\n# > It is an error to use @final on a non-method function.\n\n\n@final # E[func]: not allowed on non-method function.\ndef func1() -> int: # E[func]\n return 0\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_decorator.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_04.py","code":"\"\"\"\nTests the use of Final values when used with TypedDicts.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#use-of-final-values-and-literal-types\n\nfrom typing import Final, Literal, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\n# > Type checkers should allow final names (PEP 591) with string values to be\n# > used instead of string literals in operations on TypedDict objects.\nYEAR: Final = \"year\"\n\nm: Movie = {\"name\": \"Alien\", \"year\": 1979}\nyears_since_epoch = m[YEAR] - 1970\n\n\n# > An expression with a suitable literal type (PEP 586) can be used instead of\n# > a literal value.\ndef get_value(movie: Movie, key: Literal[\"year\", \"name\"]) -> int | str:\n return movie[key]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_04.py","code":"\"\"\"\nTests interactions between Literal types and other typing features.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#interactions-with-other-types-and-features\nfrom enum import Enum\nfrom typing import IO, Any, Final, Generic, Literal, TypeVar, LiteralString, assert_type, overload\n\n\ndef func1(v: tuple[int, str, list[bool]], a: Literal[0], b: Literal[5], c: Literal[-5]):\n assert_type(v[a], int)\n assert_type(v[2], list[bool])\n\n v[b] # E: index out of range\n v[c] # E: index out of range\n v[4] # E: index out of range\n v[-4] # E: index out of range\n\n\n_PathType = str | bytes | int\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"r\", \"w\", \"a\", \"x\", \"r+\", \"w+\", \"a+\", \"x+\"],\n) -> IO[str]:\n ...\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"rb\", \"wb\", \"ab\", \"xb\", \"r+b\", \"w+b\", \"a+b\", \"x+b\"],\n) -> IO[bytes]:\n ...\n\n\n@overload\ndef open(path: _PathType, mode: str) -> IO[Any]:\n ...\n\n\ndef open(path: _PathType, mode: Any) -> Any:\n raise NotImplementedError\n\n\nassert_type(open(\"path\", \"r\"), IO[str])\nassert_type(open(\"path\", \"wb\"), IO[bytes])\nassert_type(open(\"path\", \"other\"), IO[Any])\n\n\nA = TypeVar(\"A\", bound=int)\nB = TypeVar(\"B\", bound=int)\nC = TypeVar(\"C\", bound=int)\n\n\nclass Matrix(Generic[A, B]):\n def __add__(self, other: \"Matrix[A, B]\") -> \"Matrix[A, B]\":\n raise NotImplementedError\n\n def __matmul__(self, other: \"Matrix[B, C]\") -> \"Matrix[A, C]\":\n raise NotImplementedError\n\n def transpose(self) -> \"Matrix[B, A]\":\n raise NotImplementedError\n\n\ndef func2(a: Matrix[Literal[2], Literal[3]], b: Matrix[Literal[3], Literal[7]]):\n c = a @ b\n assert_type(c, Matrix[Literal[2], Literal[7]])\n\n\nT = TypeVar(\"T\", Literal[\"a\"], Literal[\"b\"], Literal[\"c\"])\nS = TypeVar(\"S\", bound=Literal[\"foo\"])\n\n\nclass Status(Enum):\n SUCCESS = 0\n INVALID_DATA = 1\n FATAL_ERROR = 2\n\n\ndef parse_status1(s: str | Status) -> None:\n if s is Status.SUCCESS:\n assert_type(s, Literal[Status.SUCCESS])\n elif s is Status.INVALID_DATA:\n assert_type(s, Literal[Status.INVALID_DATA])\n elif s is Status.FATAL_ERROR:\n assert_type(s, Literal[Status.FATAL_ERROR])\n else:\n assert_type(s, str)\n\n\n# > Type checkers may optionally perform additional analysis for both\n# > enum and non-enum Literal types beyond what is described in the section above.\n#\n# > For example, it may be useful to perform narrowing based on things\n# > like containment or equality checks:\n\ndef expects_bad_status(status: Literal[\"MALFORMED\", \"ABORTED\"]):\n ...\n\n\ndef expects_pending_status(status: Literal[\"PENDING\"]):\n ...\n\n\ndef parse_status2(status: LiteralString) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n\n# Narrowing `str` to `Literal` strings is unsound given the possiblity of\n# user-defined `str` subclasses that could have custom equality semantics,\n# but is explicitly listed by the spec as optional analysis that type checkers\n# may perform.\ndef parse_status3(status: str) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n\nfinal_val1: Final = 3\nassert_type(final_val1, Literal[3])\n\nfinal_val2: Final = True\nassert_type(final_val2, Literal[True])\n","source":"typing_tests","origin":"conformance/tests/literals_interactions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_05.py","code":"\"\"\"\nTests legal and illegal parameterizations of Literal.\n\"\"\"\n\n# > Literal must be parameterized with at least one type.\n\nfrom typing import Any, Literal, TypeVar\nfrom enum import Enum\n\n\nclass Color(Enum):\n RED = 0\n GREEN = 1\n BLUE = 2\n\n\ngood1: Literal[26]\ngood2: Literal[0x1A]\ngood3: Literal[-4]\ngood4: Literal[+5]\ngood5: Literal[\"hello world\"]\ngood6: Literal[b\"hello world\"]\ngood7: Literal[\"hello world\"]\ngood8: Literal[True]\ngood9: Literal[Color.RED]\ngood10: Literal[None]\n\nReadOnlyMode = Literal[\"r\", \"r+\"]\nWriteAndTruncateMode = Literal[\"w\", \"w+\", \"wt\", \"w+t\"]\nWriteNoTruncateMode = Literal[\"r+\", \"r+t\"]\nAppendMode = Literal[\"a\", \"a+\", \"at\", \"a+t\"]\n\nAllModes = Literal[ReadOnlyMode, WriteAndTruncateMode, WriteNoTruncateMode, AppendMode]\n\ngood11: Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n\nvariable = 3\nT = TypeVar(\"T\")\n\n# > Arbitrary expressions [are illegal]\nbad1: Literal[3 + 4] # E\nbad2: Literal[\"foo\".replace(\"o\", \"b\")] # E\nbad3: Literal[4 + 3j] # E\nbad4: Literal[~5] # E\nbad5: Literal[not False] # E\nbad6: Literal[(1, \"foo\", \"bar\")] # E\nbad7: Literal[{\"a\": \"b\", \"c\": \"d\"}] # E\nbad8: Literal[int] # E\nbad9: Literal[variable] # E\nbad10: Literal[T] # E\nbad11: Literal[3.14] # E\nbad12: Literal[Any] # E\nbad13: Literal[...] # E\n\n\ndef my_function(x: Literal[1 + 2]) -> int: # E\n return x * 3\n\n\nx: Literal # E\ny: Literal[my_function] = my_function # E\n\n\ndef func2(a: Literal[Color.RED]):\n x1: Literal[\"Color.RED\"] = a # E\n\n x2: \"Literal[Color.RED]\" = a # OK\n","source":"typing_tests","origin":"conformance/tests/literals_parameterizations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_06.py","code":"\"\"\"\nTests the semantics of the Literal special form.\n\"\"\"\n\nfrom typing import Literal\nfrom typing import Literal as L\n\n\nv1: Literal[3] = 3\nv2: Literal[3] = 4 # E\n\nv3: L[-3] = -3\n\n\n# > Literal[20] and Literal[0x14] are equivalent\ndef func1(a: Literal[20], b: Literal[0x14], c: Literal[0b10100]):\n x1: Literal[0x14] = a\n x2: Literal[0x14] = b\n x3: Literal[0x14] = c\n\n\n# > Literal[0] and Literal[False] are not equivalent\ndef func2(a: Literal[0], b: Literal[False]):\n x1: Literal[False] = a # E\n x2: Literal[0] = b # E\n\n\n# > Given some value v that is a member of type T, the type Literal[v] shall\n# > be treated as a subtype of T. For example, Literal[3] is a subtype of int.\ndef func3(a: L[3, 4, 5]):\n b = a.__add__(3)\n c = a + 3\n a += 3 # E\n\n\n# > When a Literal is parameterized with more than one value, it’s treated\n# > as exactly equivalent to the union of those types.\ndef func4(a: L[None, 3] | L[3, \"foo\", b\"bar\", True]):\n x1: Literal[3, b\"bar\", True, \"foo\", None] = a\n a = x1\n","source":"typing_tests","origin":"conformance/tests/literals_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_01.py","code":"\"\"\"\nTests the handling of class objects as implementations of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#type-and-class-objects-vs-protocols\n\n# > Variables and parameters annotated with Type[Proto] accept only concrete\n# (non-protocol) subtypes of Proto.\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Protocol\n\n\nclass Proto(Protocol):\n @abstractmethod\n def meth(self) -> int:\n ...\n\n\nclass Concrete:\n def meth(self) -> int:\n return 42\n\n\ndef fun(cls: type[Proto]) -> int:\n return cls().meth() # OK\n\n\nfun(Proto) # E\nfun(Concrete) # OK\n\n\nvar: type[Proto]\nvar = Proto # E\nvar = Concrete # OK\nvar().meth() # OK\n\n\n# > A class object is considered an implementation of a protocol if accessing\n# > all members on it results in types compatible with the protocol members.\n\n\nclass ProtoA1(Protocol):\n def method1(self, x: int) -> int:\n ...\n\n\nclass ProtoA2(Protocol):\n def method1(_self, self: Any, x: int) -> int:\n ...\n\n\nclass ConcreteA:\n def method1(self, x: int) -> int:\n return 0\n\n\npa1: ProtoA1 = ConcreteA # E: signatures don't match\npa2: ProtoA2 = ConcreteA # OK\n\n\nclass ProtoB1(Protocol):\n @property\n def prop1(self) -> int:\n ...\n\n\nclass ConcreteB:\n @property\n def prop1(self) -> int:\n return 0\n\n\npb1: ProtoB1 = ConcreteB # E\n\n\nclass ProtoC1(Protocol):\n attr1: ClassVar[int]\n\n\nclass ProtoC2(Protocol):\n attr1: int\n\n\nclass ConcreteC1:\n attr1: ClassVar[int] = 1\n\n\nclass ConcreteC2:\n attr1: int = 1\n\n\nclass CMeta(type):\n attr1: int\n\n def __init__(self, *args, **kwargs) -> None:\n self.attr1: int = 1\n\n\nclass ConcreteC3(metaclass=CMeta):\n pass\n\n\npc1: ProtoC1 = ConcreteC1 # E\npc2: ProtoC2 = ConcreteC1 # OK\npc3: ProtoC1 = ConcreteC2 # E\npc4: ProtoC2 = ConcreteC2 # E\npc5: ProtoC1 = ConcreteC3 # E?: Explicit ClassVar matching is unspecified\npc6: ProtoC2 = ConcreteC3 # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_class_objects.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_02.py","code":"\"\"\"\nTests the basic definition rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#defining-a-protocol\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Iterable, NamedTuple, Protocol, Sequence\nfrom dataclasses import dataclass\n\n\nclass SupportsClose(Protocol):\n def close(self) -> None:\n ...\n\n\nclass Resource:\n def close(self) -> None:\n pass\n\n\ndef close_all(things: Iterable[SupportsClose]) -> None:\n for t in things:\n t.close()\n\n\nf = open(\"foo.txt\")\nr = Resource()\nclose_all([f, r]) # OK\nclose_all([1]) # E: 'int' has no 'close' method\n\n\nclass Example(Protocol):\n def first(self) -> int: # This is a protocol member\n return 42\n\n @abstractmethod\n def second(self) -> int: # Method without a default implementation\n raise NotImplementedError\n\n # > Static methods, class methods, and properties are equally allowed in protocols.\n\n @staticmethod\n def third() -> int:\n ...\n\n @classmethod\n def fourth(cls) -> int:\n ...\n\n @property\n def fifth(self) -> int:\n ...\n\n\n# > To define a protocol variable, one can use PEP 526 variable annotations\n# > in the class body. Additional attributes only defined in the body of a\n# > method by assignment via self are not allowed.\n\n\nclass Template(Protocol):\n name: str # This is a protocol member\n value: int = 0 # This one too (with default)\n\n def method(self) -> None:\n self.name = \"name\" # OK\n self.temp: list[int] = [] # E: use of self variables not allowed\n\n\nclass Concrete:\n def __init__(self, name: str, value: int) -> None:\n self.name = name\n self.value = value\n\n def method(self) -> None:\n return\n\n\nvar: Template = Concrete(\"value\", 42) # OK\n\n\n# > To distinguish between protocol class variables and protocol instance\n# > variables, the special ClassVar annotation should be used as specified\n# > by PEP 526. By default, protocol variables as defined above are considered\n# > readable and writable. To define a read-only protocol variable, one can\n# > use an (abstract) property.\n\n\nclass Template2(Protocol):\n val1: ClassVar[Sequence[int]]\n\n\nclass Concrete2_Good1:\n val1: ClassVar[Sequence[int]] = [2]\n\n\nclass Concrete2_Bad1:\n ...\n\n\nclass Concrete2_Bad2:\n val1: Sequence[float] = [2]\n\n\nclass Concrete2_Bad3:\n val1: list[int] = [2]\n\n\nclass Concrete2_Bad4:\n val1: Sequence[int] = [2]\n\n\nv2_good1: Template2 = Concrete2_Good1() # OK\nv2_bad1: Template2 = Concrete2_Bad1() # E\nv2_bad2: Template2 = Concrete2_Bad2() # E\nv2_bad3: Template2 = Concrete2_Bad3() # E\nv2_bad4: Template2 = Concrete2_Bad4() # E?: Explicit ClassVar matching is unspecified\n\n\nclass Template3(Protocol):\n val1: Sequence[int]\n\n\nclass Concrete3_Good1:\n val1: Sequence[int] = [0]\n\n\nclass Concrete3_Good2:\n def __init__(self) -> None:\n self.val1: Sequence[int] = [0]\n\n\nclass Concrete3_Bad1:\n ...\n\n\nclass Concrete3_Bad2:\n val1: ClassVar[Sequence[int]] = [0]\n\n\nclass Concrete3_Bad3:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete3_Bad4:\n val1: Sequence[float] = [0]\n\n\nclass Concrete3_Bad5:\n val1: list[int] = [0]\n\n\nv3_good1: Template3 = Concrete3_Good1() # OK\nv3_bad1: Template3 = Concrete3_Bad1() # E\nv3_bad2: Template3 = Concrete3_Bad2() # E\nv3_bad3: Template3 = Concrete3_Bad3() # E\nv3_bad4: Template3 = Concrete3_Bad4() # E\nv3_bad5: Template3 = Concrete3_Bad5() # E\n\n\nclass Template4(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n\nclass Concrete4_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete4_Good2:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete4_Good3:\n val1: Sequence[float] = [0]\n\n\nclass Concrete4_Good4:\n val1: Sequence[int] = [0]\n\n\nclass Concrete4_Good5:\n val1: list[float] = [0]\n\n\nclass Concrete4_Good6(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete4_Good7:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete4_Bad1:\n def val1(self) -> Sequence[int]: # Not a property\n return [0]\n\n\nclass Concrete4_Bad2:\n ...\n\n\nv4_good1: Template4 = Concrete4_Good1() # OK\nv4_good2: Template4 = Concrete4_Good2() # OK\nv4_good3: Template4 = Concrete4_Good3() # OK\nv4_good4: Template4 = Concrete4_Good4() # OK\nv4_good5: Template4 = Concrete4_Good5() # OK\nv4_good6: Template4 = Concrete4_Good6() # OK\nv4_good7: Template4 = Concrete4_Good7() # OK\nv4_bad1: Template4 = Concrete4_Bad1() # E\nv4_bad2: Template4 = Concrete4_Bad2() # E\n\n\nclass Template5(Protocol):\n def method1(self, a: int, b: int) -> float:\n ...\n\n\nclass Concrete5_Good1:\n def method1(self, a: float, b: float) -> int:\n return 0\n\n\nclass Concrete5_Good2:\n def method1(self, *args: float, **kwargs: float) -> Any:\n return 0.0\n\n\nclass Concrete5_Good3:\n def method1(self, a, b) -> Any:\n return 0.0\n\n\nclass Concrete5_Good4:\n @classmethod\n def method1(cls, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Good5:\n @staticmethod\n def method1(a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad1:\n def method1(self, a, c) -> int:\n return 0\n\n\nclass Concrete5_Bad2:\n def method1(self, a: int, c: int) -> int:\n return 0\n\n\nclass Concrete5_Bad3:\n def method1(self, *, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad4:\n def method1(self, a: int, b: int, /) -> float:\n return 0\n\n\nclass Concrete5_Bad5:\n @staticmethod\n def method1(self, a: int, b: int) -> float:\n return 0\n\n\nv5_good1: Template5 = Concrete5_Good1() # OK\nv5_good2: Template5 = Concrete5_Good2() # OK\nv5_good3: Template5 = Concrete5_Good3() # OK\nv5_good4: Template5 = Concrete5_Good4() # OK\nv5_good5: Template5 = Concrete5_Good5() # OK\nv5_bad1: Template5 = Concrete5_Bad1() # E\nv5_bad2: Template5 = Concrete5_Bad2() # E\nv5_bad3: Template5 = Concrete5_Bad3() # E\nv5_bad4: Template5 = Concrete5_Bad4() # E\nv5_bad5: Template5 = Concrete5_Bad5() # E\n\n\nclass Template6(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n ...\n\n\nclass Concrete6_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n pass\n\n\nclass Concrete6_Good2:\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete6_Good3:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete6_Bad1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete6_Bad2(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=True)\nclass Concrete6_Bad3:\n val1: Sequence[float] = (0,)\n\n\nv6_good1: Template6 = Concrete6_Good1() # OK\nv6_good2: Template6 = Concrete6_Good2() # OK\nv6_good3: Template6 = Concrete6_Good3() # OK\nv6_bad1: Template6 = Concrete6_Bad1() # E\nv6_bad2: Template6 = Concrete6_Bad2() # E: named tuple is immutable\nv6_bad3: Template6 = Concrete6_Bad3() # E: dataclass is frozen\n\n\n# The specification leaves two possible interpretations of a ClassVar protocol\n# member. One interpretation requires the implementing attribute to be explicitly\n# declared with ClassVar. The other interpretation imposes only structural\n# requirements: the attribute must be readable and writable on the class object\n# and readable on instances of the class. Both interpretations therefore require\n# the following assignments to be rejected.\n\n\nclass Template7(Protocol):\n val1: ClassVar[int]\n\n\nclass Concrete7_Bad1:\n def __init__(self) -> None:\n self.val1: int = 42\n\n\nclass Concrete7Meta(type):\n val1: int = 42\n\n\nclass Concrete7_Bad2(metaclass=Concrete7Meta):\n pass\n\n\nv7_bad1: Template7 = Concrete7_Bad1() # E: val1 is not readable on the class object\nv7_bad2: Template7 = Concrete7_Bad2() # E: val1 is not readable on instances\n","source":"typing_tests","origin":"conformance/tests/protocols_definition.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_03.py","code":"\"\"\"\nTests the handling of explicit protocol classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#explicitly-declaring-implementation\n\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar, Protocol\n\n\nclass PColor(Protocol):\n @abstractmethod\n def draw(self) -> str:\n ...\n\n def complex_method(self) -> int:\n return 1\n\n\nclass NiceColor(PColor):\n def draw(self) -> str:\n return \"deep blue\"\n\n\nclass BadColor(PColor):\n def draw(self) -> str:\n return super().draw() # E: no default implementation\n\n\nclass ImplicitColor: # Note no 'PColor' base here\n def draw(self) -> str:\n return \"probably gray\"\n\n def complex_method(self) -> int:\n return 0\n\n\nv1: PColor = NiceColor() # OK\nv2: PColor = ImplicitColor() # OK\n\n\nclass RGB(Protocol):\n rgb: tuple[int, int, int]\n other: int\n\n @abstractmethod\n def intensity(self) -> int:\n return 1\n\n def transparency(self) -> int:\n ...\n\n\nclass Point(RGB):\n def __init__(self, red: int, green: int, blue: str) -> None:\n self.rgb = red, green, blue # E: 'blue' must be 'int'\n self.other = 0\n\n\np = Point(0, 0, \"\") # E: Cannot instantiate abstract class\n\n\nclass Proto1(Protocol):\n cm1: ClassVar[int]\n cm2: ClassVar[int] = 0\n\n im1: int\n im2: int = 2\n im3: int\n\n def __init__(self):\n self.im3 = 3\n\n\nclass Proto2(Protocol):\n cm10: int\n\n\nclass Proto3(Proto2, Protocol):\n cm11: int\n\n\nclass Concrete1(Proto1):\n def __init__(self):\n self.im1 = 1\n self.im3 = 3\n\n\nc1 = Concrete1() # E: cannot instantiate abstract class\n\n\nclass Concrete2(Proto1):\n cm1 = 3\n im1 = 0\n\n\nc2 = Concrete2()\n\n\nclass Concrete3(Proto1, Proto3):\n cm1 = 3\n\n def __init__(self):\n self.im1 = 0\n self.cm10 = 10\n self.cm11 = 11\n\n\nc3 = Concrete3()\n\n\nclass Concrete4(Proto1, Proto3):\n cm1 = 3\n cm10 = 3\n\n def __init__(self):\n self.im1 = 3\n self.im10 = 10\n self.cm11 = 3\n\n\nc4 = Concrete4()\n\n\nclass Proto5(Protocol):\n def method1(self) -> int:\n ...\n\n\nclass Concrete5(Proto5):\n pass\n\n\nc5 = Concrete5() # E: cannot instantiate abstract class\n\n\nclass Proto6(Protocol):\n x: int\n\n\nclass Mixin:\n x = 3\n\n\nclass Concrete6(Mixin, Proto6):\n pass\n\n\nclass Proto7(Protocol):\n @abstractmethod\n def method1(self):\n ...\n\n\nclass Mixin7(Proto7, ABC):\n def method1(self) -> None:\n pass\n\n\nclass Concrete7A(Proto7):\n pass\n\n\nc7a = Concrete7A() # E: cannot instantiate abstract class\n\n\nclass Concrete7B(Mixin7, Proto7):\n pass\n\n\nc7b = Concrete7B()\n","source":"typing_tests","origin":"conformance/tests/protocols_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_04.py","code":"\"\"\"\nTests the handling of generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\n\nfrom typing import Callable, Generic, Iterator, Protocol, Self, TypeVar, assert_type\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Iterable(Protocol[T_co]):\n def __iter__(self) -> Iterator[T_co]:\n ...\n\n\n# > Protocol[T, S, ...] is allowed as a shorthand for Protocol, Generic[T, S, ...].\n# In particular, the implicit order of type parameters is dictated by\n# the order in which they appear in the `Protocol` subscript.\n\n\nclass Proto1(Iterable[T_co], Protocol[S, T_co]):\n def method1(self, x: S) -> S:\n ...\n\n\nclass Concrete1:\n def __iter__(self) -> Iterator[int]:\n return (x for x in [1, 2, 3])\n\n def method1(self, x: str) -> str:\n return \"\"\n\n\np1: Proto1[str, int] = Concrete1() # OK\np2: Proto1[int, str] = Concrete1() # E: incompatible type\n\n\n# > It is an error to combine the shorthand with Generic[T, S, ...]\nclass Proto2(Protocol[T_co], Generic[T_co]): # E\n ...\n\n\n# > User-defined generic protocols support explicitly declared variance.\nclass Box(Protocol[T_co]):\n def content(self) -> T_co:\n ...\n\n\ndef func1(box_int: Box[int], box_float: Box[float]):\n v1: Box[float] = box_int # OK\n v2: Box[int] = box_float # E\n\n\nclass Sender(Protocol[T_contra]):\n def send(self, data: T_contra) -> int:\n return 0\n\n\ndef func2(sender_int: Sender[int], sender_float: Sender[float]):\n v1: Sender[int] = sender_float # OK\n v2: Sender[float] = sender_int # E\n\n\nclass AttrProto(Protocol[T]):\n attr: T\n\n\ndef func3(attr_int: AttrProto[int], attr_float: AttrProto[float]):\n v1: AttrProto[float] = attr_int # E\n v2: AttrProto[int] = attr_float # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n# > The self-types in protocols follow the rules for other methods.\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n# > In addition, the first argument in an instance method can be annotated\n# > with a type variable. In this case the return type may use the same\n# > type variable, thus making that method a generic function.\n\n\nT_bounded = TypeVar(\"T_bounded\", bound=\"HasParent\")\n\n\nclass HasParent(Protocol):\n def get_parent(self: T_bounded) -> T_bounded:\n ...\n\n\nGenericHasParent = TypeVar(\"GenericHasParent\", bound=HasParent)\n\n\ndef generic_get_parent(n: GenericHasParent) -> GenericHasParent:\n return n.get_parent()\n\n\nclass ConcreteHasParent:\n def get_parent(self) -> Self:\n return self\n\n\nparent = generic_get_parent(ConcreteHasParent()) # OK\nassert_type(parent, ConcreteHasParent)\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > `Self` is valid within Protocols, similar to its use in classes:\n\n\nclass HasParentProperty(Protocol):\n @property\n def parent(self) -> Self:\n ...\n\n\nclass ConcreteParentProperty:\n @property\n def parent(self) -> Self:\n return self\n\n\nclass InvalidParentProperty:\n @property\n def parent(self) -> HasParentProperty:\n return ConcreteParentProperty()\n\n\nhp1: HasParentProperty = ConcreteParentProperty() # OK\nhp2: HasParentProperty = InvalidParentProperty() # E\n\n\n\nclass HasMethod(Protocol):\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n ...\n\n\nclass ConcreteHasMethod:\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n return \"\"\n\n\nclass InvalidHasMethod:\n def m(self, item: int, callback: Callable[[int], str]) -> str:\n return \"\"\n\n\nhm1: HasMethod = ConcreteHasMethod() # OK\nhm2: HasMethod = InvalidHasMethod() # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > Checking a class for assignability to a protocol: If a protocol uses `Self`\n# > in methods or attribute annotations, then a class `Foo` is assignable\n# > to the protocol if its corresponding methods and attribute annotations use\n# > either `Self` or `Foo` or any of `Foo`'s subclasses.\n\n\nclass HasGreaterThan(Protocol):\n def __gt__(self, other: Self) -> bool:\n ...\n\n\nclass ConcreteGreaterThan1:\n def __gt__(self, other: Self) -> bool:\n return False\n\n\nclass ConcreteGreaterThan2:\n def __gt__(self, other: \"ConcreteGreaterThan2\") -> bool:\n return False\n\n\nclass InvalidGreaterThan:\n def __gt__(self, other: int) -> bool:\n return False\n\n\nhg1: HasGreaterThan = ConcreteGreaterThan1() # OK\nhg2: HasGreaterThan = ConcreteGreaterThan2() # OK\nhg3: HasGreaterThan = InvalidGreaterThan() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_generic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_05.py","code":"\"\"\"\nTests merging and extending of protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#merging-and-extending-protocols\n\nfrom abc import abstractmethod\nfrom typing import Protocol\nfrom collections.abc import Sized\n\n\nclass SizedAndClosable1(Sized, Protocol):\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable2(Protocol):\n def __len__(self) -> int:\n ...\n\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable3(SizedAndClosable1): # Note: not a protocol\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete1:\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete2:\n def close(self) -> None:\n pass\n\n\ns1: SizedAndClosable1 = SCConcrete1() # OK\ns2: SizedAndClosable2 = SCConcrete1() # OK\ns3: SizedAndClosable1 = SizedAndClosable3() # OK\ns4: SizedAndClosable2 = SizedAndClosable3() # OK\ns5: Sized = SCConcrete1() # OK\n\ns6: SizedAndClosable1 = SCConcrete2() # E: doesn't implement `__len__`\ns7: SizedAndClosable2 = SCConcrete2() # E: doesn't implement `__len__`\ns8: SizedAndClosable3 = SCConcrete2() # E: SizedAndClosable3 is not a protocol\n\n\ndef func1(s1: SizedAndClosable1, s2: SizedAndClosable2):\n # > The two definitions of SizedAndClosable are equivalent.\n v1: SizedAndClosable2 = s1\n v2: SizedAndClosable1 = s2\n\n\n# > If Protocol is included in the base class list, all the other base classes\n# > must be protocols.\n\n\nclass BadProto(SizedAndClosable3, Protocol): # E: SizedAndClosable3 is not a protocol\n ...\n\n\n# > Without this base, the class is “downgraded” to a regular ABC that\n# > cannot be used with structural subtyping.\nclass SizedAndClosable4(SizedAndClosable1):\n def __len__(self) -> int:\n return 0\n\n @abstractmethod\n def close(self) -> None:\n raise NotImplementedError\n\n\nx = SizedAndClosable4() # E: cannot instantiate abstract class\ny: SizedAndClosable4 = SCConcrete1() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_merging.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_06.py","code":"\"\"\"\nTests the handling of modules as the implementation of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#modules-as-implementations-of-protocols\n\n# > A module object is accepted where a protocol is expected if the public\n# > interface of the given module is compatible with the expected protocol.\n\nimport _protocols_modules1\nimport _protocols_modules2\nfrom typing import Protocol\n\n\nclass Options1(Protocol):\n timeout: int\n one_flag: bool\n other_flag: bool\n\n\nclass Options2(Protocol):\n timeout: str\n\n\nop1: Options1 = _protocols_modules1 # OK\nop2: Options2 = _protocols_modules1 # E\n\n\nclass Reporter1(Protocol):\n def on_error(self, x: int) -> None:\n ...\n\n def on_success(self) -> None:\n ...\n\n\nclass Reporter2(Protocol):\n def on_error(self, x: int) -> int:\n ...\n\n\nclass Reporter3(Protocol):\n def not_implemented(self, x: int) -> int:\n ...\n\n\nrp1: Reporter1 = _protocols_modules2 # OK\nrp2: Reporter2 = _protocols_modules2 # E\nrp3: Reporter3 = _protocols_modules2 # E\n","source":"typing_tests","origin":"conformance/tests/protocols_modules.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_07.py","code":"\"\"\"\nTests the handling of recursive protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#recursive-protocols\n\n\nfrom typing import Generic, Iterable, Never, Protocol, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Traversable(Protocol):\n def leaves(self) -> Iterable[\"Traversable\"]:\n ...\n\n\nclass SimpleTree:\n def leaves(self) -> list[\"SimpleTree\"]:\n return []\n\n\nroot: Traversable = SimpleTree() # OK\n\n\nclass Tree(Generic[T]):\n def leaves(self) -> list[\"Tree[T]\"]:\n return []\n\n\ndef walk(graph: Traversable) -> None:\n pass\n\n\ntree: Tree[float] = Tree()\nwalk(tree) # OK\n\n\nclass ProtoA(Protocol[T_co, T_contra]):\n def method1(self) -> \"ProtoA[T_co, T_contra]\":\n ...\n\n @classmethod\n def method2(cls, value: T_contra) -> None:\n ...\n\n\nclass ProtoB(Protocol[T_co, T_contra]):\n def method3(self) -> ProtoA[T_co, T_contra]:\n ...\n\n\nclass ImplA:\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls, value: int) -> None:\n pass\n\n\nclass ImplB:\n def method3(self) -> ImplA:\n return ImplA()\n\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls: type[ProtoB[object, T]], value: list[T]) -> None:\n pass\n\n\ndef func1(x: ProtoA[Never, T]) -> T:\n raise NotImplementedError\n\n\nv1 = func1(ImplB())\nassert_type(v1, list[int])\n","source":"typing_tests","origin":"conformance/tests/protocols_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_08.py","code":"\"\"\"\nTests the handling of the @runtime_checkable decorator for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#runtime-checkable-decorator-and-narrowing-types-by-isinstance\n\n# > A protocol can be used as a second argument in isinstance() and\n# > issubclass() only if it is explicitly opt-in by @runtime_checkable decorator.\n\nfrom typing import Any, Protocol, runtime_checkable\n\n\nclass Proto1(Protocol):\n name: str\n\n\n@runtime_checkable\nclass Proto2(Protocol):\n name: str\n\n\ndef func1(a: Any):\n if isinstance(a, Proto1): # E: not runtime_checkable\n return\n\n if isinstance(a, Proto2): # OK\n return\n\n\n# > isinstance() can be used with both data and non-data protocols, while\n# > issubclass() can be used only with non-data protocols.\n\n\n@runtime_checkable\nclass DataProtocol(Protocol):\n name: str\n\n def method1(self) -> int:\n ...\n\n\n@runtime_checkable\nclass NonDataProtocol(Protocol):\n def method1(self) -> int:\n ...\n\n\ndef func2(a: Any):\n if isinstance(a, DataProtocol): # OK\n return\n\n if isinstance(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, DataProtocol): # E\n return\n\n if issubclass(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, (NonDataProtocol, DataProtocol)): # E\n return\n\n\n# > Type checkers should reject an isinstance() or issubclass() call if there\n# > is an unsafe overlap between the type of the first argument and the protocol.\n\n\n@runtime_checkable\nclass Proto3(Protocol):\n def method1(self, a: int) -> int:\n ...\n\n\nclass Concrete3A:\n def method1(self, a: str) -> None:\n pass\n\n\nclass Concrete3B:\n method1: int = 1\n\n\ndef func3():\n if isinstance(Concrete3A(), Proto2): # OK\n pass\n\n if isinstance(Concrete3A(), Proto3): # E: unsafe overlap\n pass\n\n if isinstance(Concrete3B(), (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n\n if issubclass(Concrete3A, (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n","source":"typing_tests","origin":"conformance/tests/protocols_runtime_checkable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_09.py","code":"\"\"\"\nTests the handling of annotated \"self\" parameters in a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n\nfrom typing import Generic, Protocol, Self, TypeVar\n\n\nC = TypeVar(\"C\", bound=\"Copyable\")\n\n\nclass Copyable(Protocol):\n def copy(self: C) -> C:\n return self\n\n\nclass One:\n def copy(self) -> \"One\":\n return One()\n\n\nT = TypeVar(\"T\", bound=\"Other\")\n\n\nclass Other:\n def copy(self: T) -> T:\n return self\n\n\nc: Copyable\nc = One() # OK\nc = Other() # OK\n\n\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT2_co = TypeVar(\"T2_co\", covariant=True)\n\n\nclass P1Parent(Protocol[T2_co]):\n def f0(self, /) -> Self:\n ...\n\n\nclass P1Child(P1Parent[T2_co], Protocol[T2_co]):\n ...\n\n\nclass C1(Generic[T1_co]):\n def f0(self, /) -> Self:\n return self\n\n\na1: P1Parent[str] = C1[str]()\nb1: P1Child[str] = C1[str]()\n\n\nclass P2Parent(Protocol[T1_co]):\n def f0(self, right: Self, /) -> \"P2Parent[T1_co]\":\n return right\n\n\nclass P2Child(P2Parent[T1_co], Protocol[T1_co]):\n ...\n\n\nclass C2(Generic[T2_co]):\n def f0(self, other: Self) -> \"C2[T2_co]\":\n return other\n\n\na2: P2Parent[str] = C2[str]() # OK\nb2: P2Child[str] = C2[str]() # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_self.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_10.py","code":"\"\"\"\nTests subtyping rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#subtyping-relationships-with-other-types\n\n# > Protocols cannot be instantiated.\n\nfrom typing import Hashable, Iterable, Protocol, Sequence, TypeVar\n\n\nclass Proto1(Protocol):\n pass\n\n\np1 = Proto1() # E: protocol cannot be instantiated\n\n\n# > A protocol is never a subtype of a concrete type.\n\n# > A concrete type X is a subtype of protocol P if and only if X implements\n# > all protocol members of P with compatible types. In other words, subtyping\n# > with respect to a protocol is always structural.\n\n\nclass Proto2(Protocol):\n def method1(self) -> None:\n ...\n\n\nclass Concrete2:\n def method1(self) -> None:\n pass\n\n\ndef func1(p2: Proto2, c2: Concrete2):\n v1: Proto2 = c2 # OK\n v2: Concrete2 = p2 # E\n\n\n# > A protocol P1 is a subtype of another protocol P2 if P1 defines all\n# > protocol members of P2 with compatible types.\n\n\nclass Proto3(Protocol):\n def method1(self) -> None:\n ...\n\n def method2(self) -> None:\n ...\n\n\ndef func2(p2: Proto2, p3: Proto3):\n v1: Proto2 = p3 # OK\n v2: Proto3 = p2 # E\n\n\n# > Generic protocols follow the rules for generic abstract classes, except\n# > for using structural compatibility instead of compatibility defined by\n# > inheritance relationships.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n\nclass Proto4(Protocol[S, T]):\n def method1(self, a: S, b: T) -> tuple[S, T]:\n ...\n\n\nclass Proto5(Protocol[T]):\n def method1(self, a: T, b: T) -> tuple[T, T]:\n ...\n\n\ndef func3(p4_int: Proto4[int, int], p5_int: Proto5[int]):\n v1: Proto4[int, int] = p5_int # OK\n v2: Proto5[int] = p4_int # OK\n v3: Proto4[int, float] = p5_int # E\n v4: Proto5[float] = p4_int # E\n\n\nS_co = TypeVar(\"S_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Proto6(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\nclass Proto7(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\ndef func4(p6: Proto6[float, float]):\n v1: Proto7[object, int] = p6 # OK\n v2: Proto7[float, float] = p6 # OK\n v3: Proto7[complex, int] = p6 # OK\n\n v4: Proto7[int, float] = p6 # E\n v5: Proto7[float, object] = p6 # E\n\n\n# > Unions of protocol classes behaves the same way as for non-protocol classes.\n\n\nclass SupportsExit(Protocol):\n def exit(self) -> int:\n ...\n\n\nclass SupportsQuit(Protocol):\n def quit(self) -> int | None:\n ...\n\n\ndef finish(task: SupportsExit | SupportsQuit) -> int:\n return 0\n\n\nclass DefaultJob:\n def quit(self) -> int:\n return 0\n\n\nfinish(DefaultJob()) # OK\n\n\n# > One can use multiple inheritance to define an intersection of protocols.\n\n\nclass HashableFloats(Iterable[float], Hashable, Protocol):\n pass\n\n\ndef cached_func(args: HashableFloats) -> float:\n return 0.0\n\n\ncached_func((1, 2, 3)) # OK, tuple is both hashable and iterable\n","source":"typing_tests","origin":"conformance/tests/protocols_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_11.py","code":"\"\"\"\nTests type variable variance inference for generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\nfrom typing import Protocol, TypeVar\nfrom typing_extensions import ParamSpec\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", bound=int)\nT3 = TypeVar(\"T3\", bytes, str)\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT1_contra = TypeVar(\"T1_contra\", contravariant=True)\nP = ParamSpec(\"P\", contravariant=True)\nR = TypeVar(\"R\", covariant=True)\n\n# > Type checkers will warn if the inferred variance is different from the\n# > declared variance.\n\n\nclass AnotherBox(Protocol[T1]): # E: T should be covariant\n def content(self) -> T1:\n ...\n\n\nclass Protocol1(Protocol[T1, T2, T3]): # OK\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1 | T2:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n def m4(self) -> T3:\n ...\n\n\nclass Protocol2(Protocol[T1, T2, T3]): # E: T3 should be contravariant\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n\nclass Protocol3(Protocol[T1_co]):\n def m1(self) -> None:\n pass\n\n\nclass Protocol4(Protocol[T1]): # E: T1 should be contravariant\n def m1(self, p0: T1) -> None:\n ...\n\n\nclass Protocol5(Protocol[T1_co]): # E[covariant_in_input+]\n def m1(self, p0: T1_co) -> None: # E[covariant_in_input+]\n ...\n\n\nclass Protocol6(Protocol[T1]): # E: T1 should be covariant\n def m1(self) -> T1:\n ...\n\n\nclass Protocol7(Protocol[T1_contra]): # E[contravariant_in_output+]\n def m1(self) -> T1_contra: # E[contravariant_in_output+]\n ...\n\n\nclass Protocol8(Protocol[T1]): # OK\n def m1(self) -> T1:\n ...\n\n def m2(self, p1: T1) -> None:\n pass\n\n\nclass Callback(Protocol[P, R]): # OK\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\nclass Protocol9(Protocol[T1_co]): # OK\n @property\n def prop1(self) -> T1_co:\n ...\n\n\nclass Protocol10(Protocol[T1_co]): # OK\n def m1(self) -> type[T1_co]:\n ...\n\n\nclass Protocol11(Protocol[T1]): # OK\n x: T1 | None\n\n\nclass Protocol12(Protocol[T1]): # E: T1 should be covariant\n # __init__ method is exempt from variance calculations.\n def __init__(self, x: T1) -> None:\n ...\n\n\nclass Protocol13(Protocol[T1_contra]): # OK\n def m1(self: \"Protocol13[T1_contra]\", x: T1_contra) -> None:\n ...\n\n @classmethod\n def m2(cls: \"type[Protocol13[T1_contra]]\") -> None:\n ...\n\n\nclass Protocol14(Protocol[T1]): # OK\n def m1(self) -> list[T1]:\n ...\n","source":"typing_tests","origin":"conformance/tests/protocols_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_13.py","code":"\"\"\"\nTests the \"alternative\" (non-class) syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#alternative-syntax\n\nfrom typing import TypedDict\n\n\nMovie = TypedDict(\"Movie\", {\"name\": str, \"year\": int, \"illegal key name\": bool})\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982, \"illegal key name\": True}\n\nMovieOptional = TypedDict(\"MovieOptional\", {\"name\": str, \"year\": int}, total=False)\n\nmovie_opt1: MovieOptional = {}\nmovie_opt2: MovieOptional = {\"year\": 1982}\n\n# > A type checker is only expected to accept a dictionary display expression as\n# > the second argument to TypedDict. In particular, a variable that refers to a\n# > dictionary object does not need to be supported, to simplify implementation.\nmy_dict = {\"name\": str}\nBadTypedDict1 = TypedDict(\"BadTypedDict1\", my_dict) # E\n\n\n# This should generate an error because it uses a non-str key.\nBadTypedDict2 = TypedDict(\"BadTypedDict2\", {1: str}) # E\n\n\n# This should generate an error because it uses a non-matching name.\nBadTypedDict3 = TypedDict(\"WrongName\", {\"name\": str}) # E\n\n\n# This should generate an error because of the additional parameter.\nBadTypedDict4 = TypedDict(\"BadTypedDict4\", {\"name\": str}, total=False, other=False) # E\n\n\n# > The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13.\n# > It may also be unsupported by static type checkers.\n\nMovie2 = TypedDict(\"Movie2\", name=str, year=int) # E?\n\nmovie2: Movie2\nmovie2 = {\"name\": \"Blade Runner\", \"year\": 1982} # E?: May generate errors if keyword-argument syntax is unsupported\nmovie2 = {\"name\": \"Blade Runner\", \"year\": \"\"} # E?: Incorrect type for year\n","source":"typing_tests","origin":"conformance/tests/typeddicts_alt_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_14.py","code":"\"\"\"\nTests the class syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import Generic, TypeVar, TypedDict\nimport sys\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n # > String literal forward references are valid in the value types.\n director: \"Person\"\n\n\nclass Person(TypedDict):\n name: str\n age: int\n\n\n# > Methods are not allowed, since the runtime type of a TypedDict object\n# > will always be just dict (it is never a subclass of dict).\nclass BadTypedDict1(TypedDict):\n name: str\n\n # Methods are not allowed, so this should generate an error.\n def method1(self): # E\n pass\n\n # Methods are not allowed, so this should generate an error.\n @classmethod # E[method2]\n def method2(cls): # E[method2]\n pass\n\n # Methods are not allowed, so this should generate an error.\n @staticmethod # E[method3]\n def method3(): # E[method3]\n pass\n\n\nclass CustomMeta(type):\n pass\n\n\n# > Specifying a custom metaclass is not allowed.\nclass BadTypedDict2(TypedDict, metaclass=CustomMeta): # E\n name: str\n\n\n# This should generate an error because \"other\" is not an allowed keyword argument.\nclass BadTypedDict3(TypedDict, other=True): # E\n name: str\n\n# > `if` conditions that the type checker is able to\n# > statically evaluate are also permitted (e.g. `if sys.version_info > (3, 14)`),\n# > in order to specify items that exist only under the given conditions.\nclass ConditionalField(TypedDict):\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nConditionalField(x=1, y=2)\nConditionalField(x=1, y=2, z=3) # E\n\n\n# > TypedDicts may be made generic by adding Generic[T] among the bases.\nT = TypeVar(\"T\")\n\n\nclass GenericTypedDict(TypedDict, Generic[T]):\n name: str\n value: T\n\n\n# > An empty TypedDict can be created by only including pass in the\n# > body (if there is a docstring, pass can be omitted):\nclass EmptyDict1(TypedDict):\n pass\n\n\nclass EmptyDict2(TypedDict):\n \"\"\"Docstring\"\"\"\n\n\nclass MovieTotal(TypedDict, total=True):\n name: str\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n","source":"typing_tests","origin":"conformance/tests/typeddicts_class_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_15.py","code":"\"\"\"\nTests inheritance rules for TypedDict classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclass BookBasedMovie(Movie):\n based_on: str\n\nclass BookBasedMovieAlso(TypedDict):\n name: str\n year: int\n based_on: str\n\nb1: BookBasedMovie = {\"name\": \"Little Women\", \"year\": 2019, \"based_on\": \"Little Women\"}\n\nb2: BookBasedMovieAlso = b1\n\n\nclass X(TypedDict):\n x: int\n\nclass Y(TypedDict):\n y: str\n\nclass XYZ(X, Y):\n z: bool\n\nx1 = XYZ(x=1, y=\"\", z=True)\n\n# > A TypedDict cannot inherit from both a TypedDict type and a\n# > non-TypedDict base class other than Generic.\n\nclass NonTypedDict:\n pass\n\nclass BadTypedDict(TypedDict, NonTypedDict): # E\n pass\n\n\n# > Changing a field type of a parent TypedDict class in a subclass is\n# > not allowed.\n\nclass X1(TypedDict):\n x: str\n\nclass Y1(X1): # E[Y1]\n x: int # E[Y1]: cannot overwrite TypedDict field \"x\"\n\n\n# > Multiple inheritance does not allow conflict types for the same name field:\nclass X2(TypedDict):\n x: int\n\nclass Y2(TypedDict):\n x: str\n\nclass XYZ2(X2, Y2): # E: cannot overwrite TypedDict field \"x\" while merging\n xyz: bool\n","source":"typing_tests","origin":"conformance/tests/typeddicts_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_16.py","code":"\"\"\"\nTests operations provided by a TypedDict object.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#supported-and-unsupported-operations\n\n\nfrom typing import TypedDict, assert_type\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie\n\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982}\nmovie[\"name\"] = \"Other\"\nmovie[\"year\"] = 1981\n\nmovie[\"name\"] = 1982 # E: wrong type\nmovie[\"year\"] = \"\" # E: wrong type\nmovie[\"other\"] = \"\" # E: unknown key added\n\nprint(movie[\"other\"]) # E: unknown key referenced\n\nmovie = {\"name\": \"Blade Runner\"} # E: year is missing\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982.1} # E: year is wrong type\n\n# > The use of a key that is not known to exist should be reported as an error.\nmovie = {\"name\": \"\", \"year\": 1900, \"other\": 2} # E: extra key\n\n\ndef func1(variable_key: str):\n # > A key that is not a literal should generally be rejected.\n movie: Movie = {variable_key: \"\", \"year\": 1900} # E: variable key\n\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"name\")\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"other\") # E?\n\n\nmovie.clear() # E: clear not allowed\n\ndel movie[\"name\"] # E: del not allowed for required key\n\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n year: int\n\n\nmovie_optional: MovieOptional = {}\n\nassert_type(movie_optional.get(\"name\"), str | None)\n\nmovie_optional.clear() # E: clear not allowed\n\ndel movie_optional[\"name\"]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_operations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_17.py","code":"\"\"\"\nTests the type consistency rules for TypedDict objects.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#type-consistency\n\nfrom typing import Any, Literal, Mapping, TypedDict\n\n\nclass A1(TypedDict):\n x: int | None\n\n\nclass B1(TypedDict):\n x: int\n\n\nb1: B1 = {\"x\": 0}\n\n# > Value types behave invariantly.\na1: A1 = b1 # E: 'B1' not compatible with 'A1'\n\n# > any TypedDict type is consistent with Mapping[str, object]\nv1: Mapping[str, object] = b1\n\n# > A TypedDict type with a required key is not consistent with a TypedDict\n# > type where the same key is a non-required key.\n\nclass A2(TypedDict, total=False):\n x: int\n\n\nclass B2(TypedDict):\n x: int\n\n\nb2: B2 = {\"x\": 0}\na2: A2 = b2 # E: 'B2' not compatible with 'A2'\n\n\n# > A TypedDict type A is consistent with TypedDict B if A is structurally\n# > compatible with B. This is true if and only if both of these conditions\n# > are satisfied:\n# > 1. For each key in B, A has the corresponding key and the corresponding\n# > value type in A is consistent with the value type in B. For each key in B,\n# > the value type in B is also consistent with the corresponding value type\n# > in A.\n# > 2. For each required key in B, the corresponding key is required in A. For\n# > each non-required key in B, the corresponding key is not required in A.\n\n\nclass A3(TypedDict):\n x: int\n\n\nclass B3(TypedDict):\n x: int\n y: int\n\n\nb3: B3 = {\"x\": 0, \"y\": 0}\na3: A3 = b3\n\na3 = {\"x\": 0}\nb3 = a3 # E\n\n\n# This should generate an error because it's a literal assignment.\na3_1: A3 = {\"x\": 0, \"y\": 0} # E\n\n# This should not generate an error.\na3_2 = b3\n\n# > A TypedDict isn’t consistent with any Dict[...] type.\n\nd1: dict[str, int] = b3 # E\nd2: dict[str, object] = b3 # E\nd3: dict[Any, Any] = b3 # E\n\n# > A TypedDict with all int values is not consistent with Mapping[str, int].\n\nm1: Mapping[str, int] = b3 # E\nm2: Mapping[str, object] = b3 # OK\nm3: Mapping[str, Any] = b3 # OK\n\n\n# Test \"get\" method.\nUserType1 = TypedDict(\"UserType1\", {\"name\": str, \"age\": int}, total=False)\nuser1: UserType1 = {\"name\": \"Bob\", \"age\": 40}\n\nname1: str = user1.get(\"name\", \"n/a\")\nage1: int = user1.get(\"age\", 42)\n\nUserType2 = TypedDict(\"UserType2\", {\"name\": str, \"age\": int})\nuser2: UserType2 = {\"name\": \"Bob\", \"age\": 40}\n\nname2: str | None = user2.get(\"name\")\n\n# The spec does not say whether type checkers should adjust the return type of `.get()`\n# to exclude `None` if it is known that the key exists. Either option is acceptable.\nname3: str = user2.get(\"name\") # E?\n\nage2: int = user2.get(\"age\", 42)\n\nage3: int | str = user2.get(\"age\", \"42\")\n\nage4: int = user2.get(\"age\", \"42\") # E?\n\n# Test nested TypedDicts.\nclass Inner1(TypedDict):\n inner_key: str\n\n\nclass Inner2(TypedDict):\n inner_key: Inner1\n\n\nclass Outer1(TypedDict):\n outer_key: Inner2\n\n\no1: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": \"hi\"}}}\n\n# This should generate an error because the inner-most value\n# should be a string.\no2: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": 1}}} # E\n\n\nclass Inner3(TypedDict):\n x: int\n\n\nclass Inner4(TypedDict):\n x: int\n\n\nclass Outer2(TypedDict):\n y: str\n z: Literal[\"\"] | Inner3\n\n\nclass Outer3(TypedDict):\n y: str\n z: Literal[\"\"] | Inner4\n\n\ndef func1(td: Outer3):\n ...\n\n\no3: Outer2 = {\"y\": \"\", \"z\": {\"x\": 0}}\no4: Outer3 = o3\n","source":"typing_tests","origin":"conformance/tests/typeddicts_type_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_18.py","code":"\"\"\"\nTests for basic usage of TypedDict.\n\"\"\"\n\nfrom typing import TypeVar, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982}\n\n\ndef record_movie(movie: Movie) -> None:\n ...\n\n\nrecord_movie({\"name\": \"Blade Runner\", \"year\": 1982})\n\n\nmovie[\"director\"] = \"Ridley Scott\" # E: invalid key 'director'\nmovie[\"year\"] = \"1982\" # E: invalid value type (\"int\" expected)\n\n# The code below should be rejected, since 'title' is not a valid key,\n# and the 'name' key is missing:\nmovie2: Movie = {\"title\": \"Blade Runner\", \"year\": 1982} # E\n\nm = Movie(name='Blade Runner', year=1982)\n\n\n# > TypedDict type objects cannot be used in isinstance() tests such as\n# > isinstance(d, Movie).\nif isinstance(movie, Movie): # E\n pass\n\n\n# TypedDict should not be allowed as a bound for a TypeVar.\nT = TypeVar(\"T\", bound=TypedDict) # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport types\nimport unittest\nfrom test.support import import_module\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport types\nimport unittest\nfrom test.support import import_module\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n an = g.__anext__()\n try:\n while True:\n try:\n an.__next__()\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n break\n else:\n res.append('EMPTY StopIteration')\n break\n except StopAsyncIteration:\n raise\n except Exception as ex:\n res.append(str(type(ex)))\n break\n except StopAsyncIteration:\n res.append('STOP')\n break\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_exception_11(self):\n def sync_gen():\n yield 10\n yield 20\n\n def sync_gen_wrapper():\n yield 1\n sg = sync_gen()\n sg.send(None)\n try:\n sg.throw(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n async def async_gen():\n yield 10\n yield 20\n\n async def async_gen_wrapper():\n yield 1\n asg = async_gen()\n await asg.asend(None)\n try:\n await asg.athrow(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n\n self.assertTrue(inspect.isawaitable(g.aclose()))\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport types\nimport unittest\nfrom test.support import import_module\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n asyncio.set_event_loop_policy(None)\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n await asyncio.sleep(0.01)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n\n await asyncio.sleep(0.1)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout)\n yield 1\n finally:\n await asyncio.sleep(0)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1))\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t1)\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t2)\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(finalized, 2)\n\n def test_async_gen_expression_01(self):\n async def arange(n):\n for i in range(n):\n await asyncio.sleep(0.01)\n yield i\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 async for i in arange(n))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(10)])\n\n def test_async_gen_expression_02(self):\n async def wrap(n):\n await asyncio.sleep(0.01)\n return n\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 for i in range(n) if await wrap(i))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(1, 10)])\n\n def test_asyncgen_nonstarted_hooks_are_cancellable(self):\n # See https://bugs.python.org/issue38013\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n\n asyncio.run(main())\n\n self.assertEqual([], messages)\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"breakpoint","pep":"553","introduced_in":"3.7","form":"modern","file":"breakpoint/modern_01.py","code":"import ast\nimport asyncio\nimport builtins\nimport collections\nimport decimal\nimport fractions\nimport io\nimport locale\nimport os\nimport pickle\nimport platform\nimport random\nimport re\nimport sys\nimport traceback\nimport types\nimport unittest\nimport warnings\nfrom contextlib import ExitStack\nfrom functools import partial\nfrom inspect import CO_COROUTINE\nfrom itertools import product\nfrom textwrap import dedent\nfrom types import AsyncGeneratorType, FunctionType\nfrom operator import neg\nfrom test.support import (\n EnvironmentVarGuard, TESTFN, check_warnings, swap_attr, unlink,\n maybe_get_event_loop_policy)\nfrom test.support.script_helper import assert_python_ok\nfrom unittest.mock import MagicMock, patch\n\n\nclass TestBreakpoint(unittest.TestCase):\n def setUp(self):\n # These tests require a clean slate environment. For example, if the\n # test suite is run with $PYTHONBREAKPOINT set to something else, it\n # will mess up these tests. Similarly for sys.breakpointhook.\n # Cleaning the slate here means you can't use breakpoint() to debug\n # these tests, but I think that's okay. Just use pdb.set_trace() if\n # you must.\n self.resources = ExitStack()\n self.addCleanup(self.resources.close)\n self.env = self.resources.enter_context(EnvironmentVarGuard())\n del self.env['PYTHONBREAKPOINT']\n self.resources.enter_context(\n swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))\n\n def test_breakpoint(self):\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once()\n\n def test_breakpoint_with_breakpointhook_set(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_breakpointhook_reset(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n # Reset the hook and it will not be called again.\n sys.breakpointhook = sys.__breakpointhook__\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_args_and_keywords(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint(1, 2, 3, four=4, five=5)\n my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)\n\n def test_breakpoint_with_passthru_error(self):\n def my_breakpointhook():\n pass\n sys.breakpointhook = my_breakpointhook\n self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_builtin(self):\n self.env['PYTHONBREAKPOINT'] = 'int'\n with patch('builtins.int') as mock:\n breakpoint('7')\n mock.assert_called_once_with('7')\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_other(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_noop_0(self):\n self.env['PYTHONBREAKPOINT'] = '0'\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_not_called()\n\n def test_envar_good_path_empty_string(self):\n # PYTHONBREAKPOINT='' is the same as it not being set.\n self.env['PYTHONBREAKPOINT'] = ''\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_unimportable(self):\n for envar in (\n '.', '..', '.foo', 'foo.', '.int', 'int.',\n '.foo.bar', '..foo.bar', '/./',\n 'nosuchbuiltin',\n 'nosuchmodule.nosuchcallable',\n ):\n with self.subTest(envar=envar):\n self.env['PYTHONBREAKPOINT'] = envar\n mock = self.resources.enter_context(patch('pdb.set_trace'))\n w = self.resources.enter_context(check_warnings(quiet=True))\n breakpoint()\n self.assertEqual(\n str(w.message),\n f'Ignoring unimportable $PYTHONBREAKPOINT: \"{envar}\"')\n self.assertEqual(w.category, RuntimeWarning)\n mock.assert_not_called()\n\n def test_envar_ignored_when_hook_is_set(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n sys.breakpointhook = int\n breakpoint()\n mock.assert_not_called()\n","source":"cpython_tests","origin":"Lib/test/test_builtin.py::TestBreakpoint","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, ZeroDivisionError)\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, TypeError)\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_03.py","code":"import concurrent.futures\nimport contextvars\nimport functools\nimport gc\nimport random\nimport time\nimport unittest\nimport weakref\n\n\nclass ContextTest(unittest.TestCase):\n def test_context_var_new_1(self):\n with self.assertRaisesRegex(TypeError, 'takes exactly 1'):\n contextvars.ContextVar()\n\n with self.assertRaisesRegex(TypeError, 'must be a str'):\n contextvars.ContextVar(1)\n\n c = contextvars.ContextVar('aaa')\n self.assertEqual(c.name, 'aaa')\n\n with self.assertRaises(AttributeError):\n c.name = 'bbb'\n\n self.assertNotEqual(hash(c), hash('aaa'))\n\n def test_context_var_new_2(self):\n self.assertIsNone(contextvars.ContextVar[int])\n\n @isolated_context\n def test_context_var_repr_1(self):\n c = contextvars.ContextVar('a')\n self.assertIn('a', repr(c))\n\n c = contextvars.ContextVar('a', default=123)\n self.assertIn('123', repr(c))\n\n lst = []\n c = contextvars.ContextVar('a', default=lst)\n lst.append(c)\n self.assertIn('...', repr(c))\n self.assertIn('...', repr(lst))\n\n t = c.set(1)\n self.assertIn(repr(c), repr(t))\n self.assertNotIn(' used ', repr(t))\n c.reset(t)\n self.assertIn(' used ', repr(t))\n\n def test_context_subclassing_1(self):\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContextVar(contextvars.ContextVar):\n # Potentially we might want ContextVars to be subclassable.\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContext(contextvars.Context):\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyToken(contextvars.Token):\n pass\n\n def test_context_new_1(self):\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1, a=1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(a=1)\n contextvars.Context(**{})\n\n def test_context_typerrors_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx[1]\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n 1 in ctx\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx.get(1)\n\n def test_context_get_context_1(self):\n ctx = contextvars.copy_context()\n self.assertIsInstance(ctx, contextvars.Context)\n\n def test_context_run_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required'):\n ctx.run()\n\n def test_context_run_2(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n kwargs['spam'] = 'foo'\n args += ('bar',)\n return args, kwargs\n\n for f in (func, functools.partial(func)):\n # partial doesn't support FASTCALL\n\n self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))\n self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, a=2),\n (('bar',), {'a': 2, 'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, 11, a=2),\n ((11, 'bar'), {'a': 2, 'spam': 'foo'}))\n\n a = {}\n self.assertEqual(\n ctx.run(f, 11, **a),\n ((11, 'bar'), {'spam': 'foo'}))\n self.assertEqual(a, {})\n\n def test_context_run_3(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2, a=123)\n\n @isolated_context\n def test_context_run_4(self):\n ctx1 = contextvars.Context()\n ctx2 = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func2():\n self.assertIsNone(var.get(None))\n\n def func1():\n self.assertIsNone(var.get(None))\n var.set('spam')\n ctx2.run(func2)\n self.assertEqual(var.get(None), 'spam')\n\n cur = contextvars.copy_context()\n self.assertEqual(len(cur), 1)\n self.assertEqual(cur[var], 'spam')\n return cur\n\n returned_ctx = ctx1.run(func1)\n self.assertEqual(ctx1, returned_ctx)\n self.assertEqual(returned_ctx[var], 'spam')\n self.assertIn(var, returned_ctx)\n\n def test_context_run_5(self):\n ctx = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func():\n self.assertIsNone(var.get(None))\n var.set('spam')\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n\n self.assertIsNone(var.get(None))\n\n def test_context_run_6(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('a', default=0)\n\n def fun():\n self.assertEqual(c.get(), 0)\n self.assertIsNone(ctx.get(c))\n\n c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(ctx.get(c), 42)\n\n ctx.run(fun)\n\n def test_context_run_7(self):\n ctx = contextvars.Context()\n\n def fun():\n with self.assertRaisesRegex(RuntimeError, 'is already entered'):\n ctx.run(fun)\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_1(self):\n c = contextvars.ContextVar('c')\n with self.assertRaises(LookupError):\n c.get()\n\n self.assertIsNone(c.get(None))\n\n t0 = c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n self.assertIs(t0.old_value, t0.MISSING)\n self.assertIs(t0.old_value, contextvars.Token.MISSING)\n self.assertIs(t0.var, c)\n\n t = c.set('spam')\n self.assertEqual(c.get(), 'spam')\n self.assertEqual(c.get(None), 'spam')\n self.assertEqual(t.old_value, 42)\n c.reset(t)\n\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n\n c.set('spam2')\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t)\n self.assertEqual(c.get(), 'spam2')\n\n ctx1 = contextvars.copy_context()\n self.assertIn(c, ctx1)\n\n c.reset(t0)\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t0)\n self.assertIsNone(c.get(None))\n\n self.assertIn(c, ctx1)\n self.assertEqual(ctx1[c], 'spam2')\n self.assertEqual(ctx1.get(c, 'aa'), 'spam2')\n self.assertEqual(len(ctx1), 1)\n self.assertEqual(list(ctx1.items()), [(c, 'spam2')])\n self.assertEqual(list(ctx1.values()), ['spam2'])\n self.assertEqual(list(ctx1.keys()), [c])\n self.assertEqual(list(ctx1), [c])\n\n ctx2 = contextvars.copy_context()\n self.assertNotIn(c, ctx2)\n with self.assertRaises(KeyError):\n ctx2[c]\n self.assertEqual(ctx2.get(c, 'aa'), 'aa')\n self.assertEqual(len(ctx2), 0)\n self.assertEqual(list(ctx2), [])\n\n @isolated_context\n def test_context_getset_2(self):\n v1 = contextvars.ContextVar('v1')\n v2 = contextvars.ContextVar('v2')\n\n t1 = v1.set(42)\n with self.assertRaisesRegex(ValueError, 'by a different'):\n v2.reset(t1)\n\n @isolated_context\n def test_context_getset_3(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n def fun():\n self.assertEqual(c.get(), 42)\n with self.assertRaises(KeyError):\n ctx[c]\n self.assertIsNone(ctx.get(c))\n self.assertEqual(ctx.get(c, 'spam'), 'spam')\n self.assertNotIn(c, ctx)\n self.assertEqual(list(ctx.keys()), [])\n\n t = c.set(1)\n self.assertEqual(list(ctx.keys()), [c])\n self.assertEqual(ctx[c], 1)\n\n c.reset(t)\n self.assertEqual(list(ctx.keys()), [])\n with self.assertRaises(KeyError):\n ctx[c]\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_4(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n tok = ctx.run(c.set, 1)\n\n with self.assertRaisesRegex(ValueError, 'different Context'):\n c.reset(tok)\n\n @isolated_context\n def test_context_getset_5(self):\n c = contextvars.ContextVar('c', default=42)\n c.set([])\n\n def fun():\n c.set([])\n c.get().append(42)\n self.assertEqual(c.get(), [42])\n\n contextvars.copy_context().run(fun)\n self.assertEqual(c.get(), [])\n\n def test_context_copy_1(self):\n ctx1 = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def ctx1_fun():\n c.set(10)\n\n ctx2 = ctx1.copy()\n self.assertEqual(ctx2[c], 10)\n\n c.set(20)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 10)\n\n ctx2.run(ctx2_fun)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 30)\n\n def ctx2_fun():\n self.assertEqual(c.get(), 10)\n c.set(30)\n self.assertEqual(c.get(), 30)\n\n ctx1.run(ctx1_fun)\n\n @isolated_context\n def test_context_threads_1(self):\n cvar = contextvars.ContextVar('cvar')\n\n def sub(num):\n for i in range(10):\n cvar.set(num + i)\n time.sleep(random.uniform(0.001, 0.05))\n self.assertEqual(cvar.get(), num + i)\n return num\n\n tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)\n try:\n results = list(tp.map(sub, range(10)))\n finally:\n tp.shutdown()\n self.assertEqual(results, list(range(10)))\n","source":"cpython_tests","origin":"Lib/test/test_context.py::ContextTest","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_17.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFieldNoAnnotation(unittest.TestCase):\n def test_field_without_annotation(self):\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n @dataclass\n class C:\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base(self):\n @dataclass\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base_not_dataclass(self):\n # Same test, but with the base class not a dataclass.\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFieldNoAnnotation","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_18.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDocString(unittest.TestCase):\n def assertDocStrEqual(self, a, b):\n # Because 3.6 and 3.7 differ in how inspect.signature work\n # (see bpo #32108), for the time being just compare them with\n # whitespace stripped.\n self.assertEqual(a.replace(' ', ''), b.replace(' ', ''))\n\n def test_existing_docstring_not_overridden(self):\n @dataclass\n class C:\n \"\"\"Lorem ipsum\"\"\"\n x: int\n\n self.assertEqual(C.__doc__, \"Lorem ipsum\")\n\n def test_docstring_no_fields(self):\n @dataclass\n class C:\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C()\")\n\n def test_docstring_one_field(self):\n @dataclass\n class C:\n x: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int)\")\n\n def test_docstring_two_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int)\")\n\n def test_docstring_three_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n z: str\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int, z:str)\")\n\n def test_docstring_one_field_with_default(self):\n @dataclass\n class C:\n x: int = 3\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int=3)\")\n\n def test_docstring_one_field_with_default_none(self):\n @dataclass\n class C:\n x: Union[int, type(None)] = None\n\n self.assertDocStrEqual(C.__doc__, \"C(x:Union[int, NoneType]=None)\")\n\n def test_docstring_list_field(self):\n @dataclass\n class C:\n x: List[int]\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int])\")\n\n def test_docstring_list_field_with_default_factory(self):\n @dataclass\n class C:\n x: List[int] = field(default_factory=list)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int]=)\")\n\n def test_docstring_deque_field(self):\n @dataclass\n class C:\n x: deque\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque)\")\n\n def test_docstring_deque_field_with_default_factory(self):\n @dataclass\n class C:\n x: deque = field(default_factory=deque)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque=)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDocString","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_19.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestInit(unittest.TestCase):\n def test_base_has_init(self):\n class B:\n def __init__(self):\n self.z = 100\n pass\n\n # Make sure that declaring this class doesn't raise an error.\n # The issue is that we can't override __init__ in our class,\n # but it should be okay to add __init__ to us if our base has\n # an __init__.\n @dataclass\n class C(B):\n x: int = 0\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertNotIn('z', vars(c))\n\n # Make sure that if we don't add an init, the base __init__\n # gets called.\n @dataclass(init=False)\n class C(B):\n x: int = 10\n c = C()\n self.assertEqual(c.x, 10)\n self.assertEqual(c.z, 100)\n\n def test_no_init(self):\n dataclass(init=False)\n class C:\n i: int = 0\n self.assertEqual(C().i, 0)\n\n dataclass(init=False)\n class C:\n i: int = 2\n def __init__(self):\n self.i = 3\n self.assertEqual(C().i, 3)\n\n def test_overwriting_init(self):\n # If the class has __init__, use it no matter the value of\n # init=.\n\n @dataclass\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(3).x, 6)\n\n @dataclass(init=True)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(4).x, 8)\n\n @dataclass(init=False)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(5).x, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestInit","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_20.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestRepr(unittest.TestCase):\n def test_repr(self):\n @dataclass\n class B:\n x: int\n\n @dataclass\n class C(B):\n y: int = 10\n\n o = C(4)\n self.assertEqual(repr(o), 'TestRepr.test_repr..C(x=4, y=10)')\n\n @dataclass\n class D(C):\n x: int = 20\n self.assertEqual(repr(D()), 'TestRepr.test_repr..D(x=20, y=10)')\n\n @dataclass\n class C:\n @dataclass\n class D:\n i: int\n @dataclass\n class E:\n pass\n self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr..C.D(i=0)')\n self.assertEqual(repr(C.E()), 'TestRepr.test_repr..C.E()')\n\n def test_no_repr(self):\n # Test a class with no __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n self.assertIn(f'{__name__}.TestRepr.test_no_repr..C object at',\n repr(C(3)))\n\n # Test a class with a __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'C-class'\n self.assertEqual(repr(C(3)), 'C-class')\n\n def test_overwriting_repr(self):\n # If the class has __repr__, use it no matter the value of\n # repr=.\n\n @dataclass\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=True)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestRepr","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_21.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestEq(unittest.TestCase):\n def test_no_eq(self):\n # Test a class with no __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n self.assertNotEqual(C(0), C(0))\n c = C(3)\n self.assertEqual(c, c)\n\n # Test a class with an __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 10\n self.assertEqual(C(3), 10)\n\n def test_overwriting_eq(self):\n # If the class has __eq__, use it no matter the value of\n # eq=.\n\n @dataclass\n class C:\n x: int\n def __eq__(self, other):\n return other == 3\n self.assertEqual(C(1), 3)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=True)\n class C:\n x: int\n def __eq__(self, other):\n return other == 4\n self.assertEqual(C(1), 4)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 5\n self.assertEqual(C(1), 5)\n self.assertNotEqual(C(1), 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestEq","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_22.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestOrdering(unittest.TestCase):\n def test_functools_total_ordering(self):\n # Test that functools.total_ordering works with this class.\n @total_ordering\n @dataclass\n class C:\n x: int\n def __lt__(self, other):\n # Perform the test \"backward\", just to make\n # sure this is being called.\n return self.x >= other\n\n self.assertLess(C(0), -1)\n self.assertLessEqual(C(0), -1)\n self.assertGreater(C(0), 1)\n self.assertGreaterEqual(C(0), 1)\n\n def test_no_order(self):\n # Test that no ordering functions are added by default.\n @dataclass(order=False)\n class C:\n x: int\n # Make sure no order methods are added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__lt__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n # Test that __lt__ is still called\n @dataclass(order=False)\n class C:\n x: int\n def __lt__(self, other):\n return False\n # Make sure other methods aren't added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n def test_overwriting_order(self):\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __lt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __lt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __le__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __le__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __gt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __gt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __ge__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __ge__(self):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestOrdering","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_23.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestHash(unittest.TestCase):\n def test_unsafe_hash(self):\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n y: str\n self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))\n\n def test_hash_rules(self):\n def non_bool(value):\n # Map to something else that's True, but not a bool.\n if value is None:\n return None\n if value:\n return (3,)\n return 0\n\n def test(case, unsafe_hash, eq, frozen, with_hash, result):\n with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,\n frozen=frozen):\n if result != 'exception':\n if with_hash:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n else:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n pass\n\n # See if the result matches what's expected.\n if result == 'fn':\n # __hash__ contains the function we generated.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNotNone(C.__dict__['__hash__'])\n\n elif result == '':\n # __hash__ is not present in our class.\n if not with_hash:\n self.assertNotIn('__hash__', C.__dict__)\n\n elif result == 'none':\n # __hash__ is set to None.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNone(C.__dict__['__hash__'])\n\n elif result == 'exception':\n # Creating the class should cause an exception.\n # This only happens with with_hash==True.\n assert(with_hash)\n with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n\n else:\n assert False, f'unknown result {result!r}'\n\n # There are 8 cases of:\n # unsafe_hash=True/False\n # eq=True/False\n # frozen=True/False\n # And for each of these, a different result if\n # __hash__ is defined or not.\n for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([\n (False, False, False, '', ''),\n (False, False, True, '', ''),\n (False, True, False, 'none', ''),\n (False, True, True, 'fn', ''),\n (True, False, False, 'fn', 'exception'),\n (True, False, True, 'fn', 'exception'),\n (True, True, False, 'fn', 'exception'),\n (True, True, True, 'fn', 'exception'),\n ], 1):\n test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)\n test(case, unsafe_hash, eq, frozen, True, res_defined_hash)\n\n # Test non-bool truth values, too. This is just to\n # make sure the data-driven table in the decorator\n # handles non-bool values.\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)\n\n\n def test_eq_only(self):\n # If a class defines __eq__, __hash__ is automatically added\n # and set to None. This is normal Python behavior, not\n # related to dataclasses. Make sure we don't interfere with\n # that (see bpo=32546).\n\n @dataclass\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1))\n self.assertNotEqual(C(1), C(4))\n\n # And make sure things work in this case if we specify\n # unsafe_hash=True.\n @dataclass(unsafe_hash=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1.0))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n # And check that the classes __eq__ is being used, despite\n # specifying eq=True.\n @dataclass(unsafe_hash=True, eq=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == 3 and self.i == other.i\n self.assertEqual(C(3), C(3))\n self.assertNotEqual(C(1), C(1))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n def test_0_field_hash(self):\n @dataclass(frozen=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n @dataclass(unsafe_hash=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n def test_1_field_hash(self):\n @dataclass(frozen=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n def test_hash_no_args(self):\n # Test dataclasses with no hash= argument. This exists to\n # make sure that if the @dataclass parameter name is changed\n # or the non-default hashing behavior changes, the default\n # hashability keeps working the same way.\n\n class Base:\n def __hash__(self):\n return 301\n\n # If frozen or eq is None, then use the default value (do not\n # specify any value in the decorator).\n for frozen, eq, base, expected in [\n (None, None, object, 'unhashable'),\n (None, None, Base, 'unhashable'),\n (None, False, object, 'object'),\n (None, False, Base, 'base'),\n (None, True, object, 'unhashable'),\n (None, True, Base, 'unhashable'),\n (False, None, object, 'unhashable'),\n (False, None, Base, 'unhashable'),\n (False, False, object, 'object'),\n (False, False, Base, 'base'),\n (False, True, object, 'unhashable'),\n (False, True, Base, 'unhashable'),\n (True, None, object, 'tuple'),\n (True, None, Base, 'tuple'),\n (True, False, object, 'object'),\n (True, False, Base, 'base'),\n (True, True, object, 'tuple'),\n (True, True, Base, 'tuple'),\n ]:\n\n with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):\n # First, create the class.\n if frozen is None and eq is None:\n @dataclass\n class C(base):\n i: int\n elif frozen is None:\n @dataclass(eq=eq)\n class C(base):\n i: int\n elif eq is None:\n @dataclass(frozen=frozen)\n class C(base):\n i: int\n else:\n @dataclass(frozen=frozen, eq=eq)\n class C(base):\n i: int\n\n # Now, make sure it hashes as expected.\n if expected == 'unhashable':\n c = C(10)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(c)\n\n elif expected == 'base':\n self.assertEqual(hash(C(10)), 301)\n\n elif expected == 'object':\n # I'm not sure what test to use here. object's\n # hash isn't based on id(), so calling hash()\n # won't tell us much. So, just check the\n # function used is object's.\n self.assertIs(C.__hash__, object.__hash__)\n\n elif expected == 'tuple':\n self.assertEqual(hash(C(42)), hash((42,)))\n\n else:\n assert False, f'unknown value for expected={expected!r}'\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestHash","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_24.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFrozen(unittest.TestCase):\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n c = C(10)\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertEqual(c.i, 10)\n\n def test_inherit(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n @dataclass(frozen=True)\n class D(C):\n j: int\n\n d = D(0, 10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n with self.assertRaises(FrozenInstanceError):\n d.j = 6\n self.assertEqual(d.i, 0)\n self.assertEqual(d.j, 10)\n\n # Test both ways: with an intermediate normal (non-dataclass)\n # class and without an intermediate class.\n def test_inherit_nonfrozen_from_frozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass(frozen=True)\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(I):\n pass\n\n def test_inherit_frozen_from_nonfrozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one'):\n @dataclass(frozen=True)\n class D(I):\n pass\n\n def test_inherit_from_normal_class(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n class C:\n pass\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n @dataclass(frozen=True)\n class D(I):\n i: int\n\n d = D(10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n\n def test_non_frozen_normal_derived(self):\n # See bpo-32953.\n\n @dataclass(frozen=True)\n class D:\n x: int\n y: int = 10\n\n class S(D):\n pass\n\n s = S(3)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n s.cached = True\n\n # But can't change the frozen attributes.\n with self.assertRaises(FrozenInstanceError):\n s.x = 5\n with self.assertRaises(FrozenInstanceError):\n s.y = 5\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.cached, True)\n\n def test_overwriting_frozen(self):\n # frozen uses __setattr__ and __delattr__.\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __setattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __setattr__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __delattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __delattr__(self):\n pass\n\n @dataclass(frozen=False)\n class C:\n x: int\n def __setattr__(self, name, value):\n self.__dict__['x'] = value * 2\n self.assertEqual(C(10).x, 20)\n\n def test_frozen_hash(self):\n @dataclass(frozen=True)\n class C:\n x: Any\n\n # If x is immutable, we can compute the hash. No exception is\n # raised.\n hash(C(3))\n\n # If x is mutable, computing the hash is an error.\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(C({}))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFrozen","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_25.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestSlots(unittest.TestCase):\n def test_simple(self):\n @dataclass\n class C:\n __slots__ = ('x',)\n x: Any\n\n # There was a bug where a variable in a slot was assumed to\n # also have a default value (of type\n # types.MemberDescriptorType).\n with self.assertRaisesRegex(TypeError,\n r\"__init__\\(\\) missing 1 required positional argument: 'x'\"):\n C()\n\n # We can create an instance, and assign to x.\n c = C(10)\n self.assertEqual(c.x, 10)\n c.x = 5\n self.assertEqual(c.x, 5)\n\n # We can't assign to anything else.\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'y'\"):\n c.y = 5\n\n def test_derived_added_field(self):\n # See bpo-33100.\n @dataclass\n class Base:\n __slots__ = ('x',)\n x: Any\n\n @dataclass\n class Derived(Base):\n x: int\n y: int\n\n d = Derived(1, 2)\n self.assertEqual((d.x, d.y), (1, 2))\n\n # We can add a new field to the derived instance.\n d.z = 10\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestSlots","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_26.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDescriptors(unittest.TestCase):\n def test_set_name(self):\n # See bpo-33141.\n\n # Create a descriptor.\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n def __get__(self, instance, owner):\n if instance is not None:\n return 1\n return self\n\n # This is the case of just normal descriptor behavior, no\n # dataclass code is involved in initializing the descriptor.\n @dataclass\n class C:\n c: int=D()\n self.assertEqual(C.c.name, 'cx')\n\n # Now test with a default value and init=False, which is the\n # only time this is really meaningful. If not using\n # init=False, then the descriptor will be overwritten, anyway.\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n self.assertEqual(C().c, 1)\n\n def test_non_descriptor(self):\n # PEP 487 says __set_name__ should work on non-descriptors.\n # Create a descriptor.\n\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n\n def test_lookup_on_instance(self):\n # See bpo-33175.\n class D:\n pass\n\n d = D()\n # Create an attribute on the instance, not type.\n d.__set_name__ = Mock()\n\n # Make sure d.__set_name__ is not called.\n @dataclass\n class C:\n i: int=field(default=d, init=False)\n\n self.assertEqual(d.__set_name__.call_count, 0)\n\n def test_lookup_on_class(self):\n # See bpo-33175.\n class D:\n pass\n D.__set_name__ = Mock()\n\n # Make sure D.__set_name__ is called.\n @dataclass\n class C:\n i: int=field(default=D(), init=False)\n\n self.assertEqual(D.__set_name__.call_count, 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDescriptors","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_27.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestMakeDataclass(unittest.TestCase):\n def test_simple(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace={'add_one': lambda self: self.x + 1})\n c = C(10)\n self.assertEqual((c.x, c.y), (10, 5))\n self.assertEqual(c.add_one(), 11)\n\n\n def test_no_mutate_namespace(self):\n # Make sure a provided namespace isn't mutated.\n ns = {}\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace=ns)\n self.assertEqual(ns, {})\n\n def test_base(self):\n class Base1:\n pass\n class Base2:\n pass\n C = make_dataclass('C',\n [('x', int)],\n bases=(Base1, Base2))\n c = C(2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n def test_base_dataclass(self):\n @dataclass\n class Base1:\n x: int\n class Base2:\n pass\n C = make_dataclass('C',\n [('y', int)],\n bases=(Base1, Base2))\n with self.assertRaisesRegex(TypeError, 'required positional'):\n c = C(2)\n c = C(1, 2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n self.assertEqual((c.x, c.y), (1, 2))\n\n def test_init_var(self):\n def post_init(self, y):\n self.x *= y\n\n C = make_dataclass('C',\n [('x', int),\n ('y', InitVar[int]),\n ],\n namespace={'__post_init__': post_init},\n )\n c = C(2, 3)\n self.assertEqual(vars(c), {'x': 6})\n self.assertEqual(len(fields(c)), 1)\n\n def test_class_var(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ])\n c = C(1)\n self.assertEqual(vars(c), {'x': 1})\n self.assertEqual(len(fields(c)), 1)\n self.assertEqual(C.y, 10)\n self.assertEqual(C.z, 20)\n\n def test_other_params(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ],\n init=False)\n # Make sure we have a repr, but no init.\n self.assertNotIn('__init__', vars(C))\n self.assertIn('__repr__', vars(C))\n\n # Make sure random other params don't work.\n with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):\n C = make_dataclass('C',\n [],\n xxinit=False)\n\n def test_no_types(self):\n C = make_dataclass('Point', ['x', 'y', 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': 'typing.Any',\n 'z': 'typing.Any'})\n\n C = make_dataclass('Point', ['x', ('y', int), 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': int,\n 'z': 'typing.Any'})\n\n def test_invalid_type_specification(self):\n for bad_field in [(),\n (1, 2, 3, 4),\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'Invalid field: '):\n make_dataclass('C', ['a', bad_field])\n\n # And test for things with no len().\n for bad_field in [float,\n lambda x:x,\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'has no len\\(\\)'):\n make_dataclass('C', ['a', bad_field])\n\n def test_duplicate_field_names(self):\n for field in ['a', 'ab']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'Field name duplicated'):\n make_dataclass('C', [field, 'a', field])\n\n def test_keyword_field_names(self):\n for field in ['for', 'async', 'await', 'as']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field, 'a'])\n\n def test_non_identifier_field_names(self):\n for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field, 'a'])\n\n def test_underscore_field_names(self):\n # Unlike namedtuple, it's okay if dataclass field names have\n # an underscore.\n make_dataclass('C', ['_', '_a', 'a_a', 'a_'])\n\n def test_funny_class_names_names(self):\n # No reason to prevent weird class names, since\n # types.new_class allows them.\n for classname in ['()', 'x,y', '*', '2@3', '']:\n with self.subTest(classname=classname):\n C = make_dataclass(classname, ['a', 'b'])\n self.assertEqual(C.__name__, classname)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestMakeDataclass","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.8","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_28.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestReplace(unittest.TestCase):\n def test(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n self.assertRaises(TypeError, replace)\n self.assertRaises(TypeError, replace, c, c)\n with self.assertWarns(DeprecationWarning):\n c1 = replace(obj=c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n z: int = field(init=False, default=10)\n t: int = field(init=False, default=100)\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))\n self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))\n\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=3, z=20, t=50)\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, z=20)\n replace(c, x=3, z=20, t=50)\n\n # Make sure the result is still frozen.\n with self.assertRaisesRegex(FrozenInstanceError, \"cannot assign to field 'x'\"):\n c1.x = 3\n\n # Make sure we can't replace an attribute that doesn't exist,\n # if we're also replacing one that does exist. Test this\n # here, because setting attributes on frozen instances is\n # handled slightly differently from non-frozen ones.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'a'\"):\n c1 = replace(c, x=20, a=5)\n\n def test_invalid_field_name(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'z'\"):\n c1 = replace(c, z=3)\n\n def test_invalid_object(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(C, x=3)\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(0, x=3)\n\n def test_no_init(self):\n @dataclass\n class C:\n x: int\n y: int = field(init=False, default=10)\n\n c = C(1)\n c.y = 20\n\n # Make sure y gets the default value.\n c1 = replace(c, x=5)\n self.assertEqual((c1.x, c1.y), (5, 10))\n\n # Trying to replace y is an error.\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=2, y=30)\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, y=30)\n\n def test_classvar(self):\n @dataclass\n class C:\n x: int\n y: ClassVar[int] = 1000\n\n c = C(1)\n d = C(2)\n\n self.assertIs(c.y, d.y)\n self.assertEqual(c.y, 1000)\n\n # Trying to replace y is an error: can't replace ClassVars.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an \"\n \"unexpected keyword argument 'y'\"):\n replace(c, y=30)\n\n replace(c, x=5)\n\n def test_initvar_is_specified(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int]\n\n def __post_init__(self, y):\n self.x *= y\n\n c = C(1, 10)\n self.assertEqual(c.x, 10)\n with self.assertRaisesRegex(ValueError, r\"InitVar 'y' must be \"\n \"specified with replace()\"):\n replace(c, x=3)\n c = replace(c, x=3, y=5)\n self.assertEqual(c.x, 15)\n\n def test_recursive_repr(self):\n @dataclass\n class C:\n f: \"C\"\n\n c = C(None)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr..C(f=...)\")\n\n def test_recursive_repr_two_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: \"C\"\n\n c = C(None, None)\n c.f = c\n c.g = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_two_attrs\"\n \"..C(f=..., g=...)\")\n\n def test_recursive_repr_indirection(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n c.f = d\n d.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection\"\n \"..C(f=TestReplace.test_recursive_repr_indirection\"\n \"..D(f=...))\")\n\n def test_recursive_repr_indirection_two(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"E\"\n\n @dataclass\n class E:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n e = E(None)\n c.f = d\n d.f = e\n e.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection_two\"\n \"..C(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..D(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..E(f=...)))\")\n\n def test_recursive_repr_misc_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: int\n\n c = C(None, 1)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_misc_attrs\"\n \"..C(f=..., g=1)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestReplace","origin_revision":"v3.8.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_01.py","code":"from typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_02.py","code":"import typing\nx: typing.List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_03.py","code":"from typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: List[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> List[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_01.py","code":"from typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_02.py","code":"import typing\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_03.py","code":"from typing import List\nSomeAlias = list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: list[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> list[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_01.py","code":"x = lambda foo: None","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[lambdas do not have type annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_02.py","code":"from __future__ import annotations\nfrom typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_03.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not a PEP 585 type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_18.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"async def c(): return f'{await 1+foo()}'","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_18.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_01.py","code":"if s.startswith(\"foo\"):\n s = s[len(\"foo\"):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_02.py","code":"if s.startswith(S):\n s = s[len(S):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_03.py","code":"if s.endswith(\"foo\"):\n s = s[:-1 * len(\"foo\")]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_04.py","code":"if s.endswith(S):\n s = s[:-1 * len(S)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_05.py","code":"if s.startswith(x):\n s = s[len(x):] # TODO: removeprefix\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_06.py","code":"if True:\n if s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_07.py","code":"if True:\n something_else()\n if s.startswith(x):\n s = s[len(x):]\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_08.py","code":"if (\n x.startswith(y)\n):\n x = x[len(y):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_01.py","code":"s = s.removeprefix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_02.py","code":"s = s.removeprefix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_03.py","code":"s = s.removesuffix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_04.py","code":"s = s.removesuffix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_05.py","code":"s = s.removeprefix(x)\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_06.py","code":"if True:\n s = s.removeprefix(x)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_07.py","code":"if True:\n something_else()\n s = s.removeprefix(x)\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_08.py","code":"x = x.removeprefix(y)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_01.py","code":"if x.startswith(S):\n x = x[len(S):]\nelif x.endswith(T):\n x = x[:-1 * len(T)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop_before_39","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_02.py","code":"if s.startswith(\"a\"):\n s = s.lstrip(\"a\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[unrelated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_03.py","code":"if s.startswith(x):\n s = s[2:]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[cannot prove x is 2]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_04.py","code":"if s.startswith(x):\n s = s[len(x):]\nelse:\n print(\"no!)\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has else]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_05.py","code":"if something:\n print(\"something!\")\nelif s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has elif]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_01.py","code":"from typing import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_02.py","code":"import typing\nD = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": typing.Literal[\"b\", b\"c\"]})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_05.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {\n # first comment\n \"a\": int, # inline comment\n # second comment\n \"b\": str,\n # third comment\n}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_07.py","code":"from typing_extensions import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_08.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_09.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int}, total=True)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nFoo = TypedDict(\"Foo\", {\"lsts\": List[List[int]]})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_11.py","code":"import typing\nif True:\n if False:\n pass\n D = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_12.py","code":"from typing import TypedDict\nFoo = TypedDict(\"Foo\", {\"union\": str | int | None})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_01.py","code":"from typing import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_02.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_03.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_04.py","code":"import typing\nclass D(typing.TypedDict):\n a: typing.Literal['b', b'c']\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_05.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_06.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n # first comment\n a: int # inline comment\n # second comment\n b: str\n # third comment\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_07.py","code":"from typing_extensions import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_08.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_09.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict, total=True):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nclass Foo(TypedDict):\n lsts: List[List[int]]","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_11.py","code":"import typing\nif True:\n if False:\n pass\n class D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_12.py","code":"from typing import TypedDict\nclass Foo(TypedDict):\n union: str | int | None","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_01.py","code":"from wat import TypedDict\nQ = TypedDict(\"Q\")\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[from imported from elsewhere]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_02.py","code":"import typing\nD = typing.TypedDict(\"D\")","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {}, a=int)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[both]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_05.py","code":"import typing\nD = typing.TypedDict(\"D\", 1)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[not a dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {1: str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not a string]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_07.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a-b\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not an identifier]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_08.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"class\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is a keyword]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_09.py","code":"import typing\nD = typing.TypedDict(\"D\", {**d, \"a\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[dictionary splat operator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_10.py","code":"import typing\nC = typing.TypedDict(\"C\", *types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_11.py","code":"import typing\nD = typing.TypedDict(\"D\", **types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starstarkwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_12.py","code":"import typing\nD = typing.TypedDict(\"D\", x=int, total=False)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[kw_typed_dict with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_01.py","code":"from contextvars import ContextVar\nfrom types import MappingProxyType\nimport re\nimport collections\nimport time\n\n# Okay\nContextVar(\"cv\")\nContextVar(\"cv\", default=())\nContextVar(\"cv\", default=(1, 2, 3))\nContextVar(\"cv\", default=\"foo\")\nContextVar(\"cv\", default=tuple())\nContextVar(\"cv\", default=frozenset())\nContextVar(\"cv\", default=MappingProxyType({}))\nContextVar(\"cv\", default=re.compile(\"foo\"))\nContextVar(\"cv\", default=float(1))\nContextVar(\"cv\", default=frozenset[str]())\nContextVar[frozenset[str]](\"cv\", default=frozenset[str]())\n\n# Bad\nContextVar(\"cv\", default=[])\nContextVar(\"cv\", default={})\nContextVar(\"cv\", default=list())\nContextVar(\"cv\", default=set())\nContextVar(\"cv\", default=dict())\nContextVar(\"cv\", default=[char for char in \"foo\"])\nContextVar(\"cv\", default={char for char in \"foo\"})\nContextVar(\"cv\", default={char: idx for idx, char in enumerate(\"foo\")})\nContextVar(\"cv\", default=collections.deque())\nContextVar(\"cv\", default=set[str]())\nContextVar[set[str]](\"cv\", default=set[str]())\n\ndef bar() -> list[int]:\n return [1, 2, 3]\n\nContextVar(\"cv\", default=bar())\nContextVar(\"cv\", default=time.time())\n\ndef baz(): ...\nContextVar(\"cv\", default=baz())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_02.py","code":"from contextvars import ContextVar\n\nfrom fastapi import Query\nContextVar(\"cv\", default=Query(None))\n\nfrom something_else import Depends\nContextVar(\"cv\", default=Depends())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039_extended.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_01.py","code":"import typing\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, Sequence\n\nKNOWINGLY_MUTABLE_DEFAULT = []\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = []\n immutable_annotation: typing.Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: typing.ClassVar[list[int]] = []\n\n\n@dataclass\nclass B:\n mutable_default: list[int] = []\n immutable_annotation: Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: ClassVar[list[int]] = []\n\n# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n@dataclass\nclass AWithQuotes:\n mutable_default: 'list[int]' = []\n immutable_annotation: 'typing.Sequence[int]' = []\n without_annotation = []\n correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: 'list[int]' = field(default_factory=list)\n class_variable: 'typing.ClassVar[list[int]]'= []\n\n\n# Mutable defaults wrapped in field() calls\n@dataclass\nclass C:\n mutable_default: list[int] = field(default=[]) # RUF008\n mutable_default2: dict[str, int] = field(default={}) # RUF008\n mutable_default3: set[int] = field(default=set()) # RUF008\n mutable_default4: dict[str, int] = field(default=dict()) # RUF008\n correct_factory: list[int] = field(default_factory=list) # okay\n immutable_default: tuple[int, ...] = field(default=()) # okay\n immutable_default2: str = field(default=\"hello\") # okay\n immutable_default3: int = field(default=1) # okay\n non_mutable_var: list[int] = field(default=KNOWINGLY_MUTABLE_DEFAULT) # okay\n class_variable: ClassVar[list[int]] = field(default=[]) # okay\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_02.py","code":"# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n\nfrom __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Example():\n \"\"\"Class that uses ClassVar.\"\"\"\n\n options: ClassVar[dict[str, str]] = {}\n\n\nif typing.TYPE_CHECKING:\n from typing import ClassVar\n\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_03.py","code":"import datetime\nimport re\nimport typing\nfrom dataclasses import dataclass, field\nfrom fractions import Fraction\nfrom pathlib import Path\nfrom typing import ClassVar, NamedTuple\n\n\ndef default_function() -> list[int]:\n return []\n\n\nclass ImmutableType(NamedTuple):\n something: int = 8\n\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\n fine_path: Path = Path()\n fine_date: datetime.date = datetime.date(2042, 1, 1)\n fine_timedelta: datetime.timedelta = datetime.timedelta(hours=7)\n fine_tuple: tuple[int] = tuple([1])\n fine_regex: re.Pattern = re.compile(r\".*\")\n fine_float: float = float(\"-inf\")\n fine_int: int = int(12)\n fine_complex: complex = complex(1, 2)\n fine_str: str = str(\"foo\")\n fine_bool: bool = bool(\"foo\")\n fine_fraction: Fraction = Fraction(1, 2)\n\n\nDEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES = ImmutableType(40)\nDEFAULT_A_FOR_ALL_DATACLASSES = A([1, 2, 3])\n\n\n@dataclass\nclass B:\n hidden_mutable_default: list[int] = default_function()\n another_dataclass: A = A()\n not_optimal: ImmutableType = ImmutableType(20)\n good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES\n okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES\n\n fine_dataclass_function: list[int] = field(default_factory=list)\n\n\nclass IntConversionDescriptor:\n def __init__(self, *, default):\n self._default = default\n\n def __set_name__(self, owner, name):\n self._name = \"_\" + name\n\n def __get__(self, obj, type):\n if obj is None:\n return self._default\n\n return getattr(obj, self._name, self._default)\n\n def __set__(self, obj, value):\n setattr(obj, self._name, int(value))\n\n\n@dataclass\nclass InventoryItem:\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\n\n\n# Regression tests for:\n# https://github.com/astral-sh/ruff/issues/6447\nfrom typing import NewType\n\nListOfStrings = NewType(\"ListOfStrs\", list[str])\nStringsToInts = NewType(\"IntsToStrings\", dict[str, int])\n\nSpecialString = NewType(name=\"SpecialString\", tp=str)\nNegativeInteger = NewType(\"NegInt\", tp=int)\n\nInvalid1 = NewType(*Foo)\nInvalid2 = NewType(\"Invalid2\", name=Foo)\nInvalid3 = NewType(\"Invalid3\", name=Foo, lorem=\"ipsum\")\n\n@dataclass\nclass DataclassWithNewTypeFields:\n # Errors\n a: ListOfStrings = ListOfStrings([])\n b: StringsToInts = StringsToInts()\n c: Invalid1 = Invalid1()\n d: Invalid2 = Invalid2()\n e: Invalid3 = Invalid3()\n\n # No errors\n e: SpecialString = SpecialString(\"Lorem ipsum\")\n f: NegativeInteger = NegativeInteger(-110)\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/15772\ndef f() -> int:\n return 0\n\n@dataclass\nclass ShouldMatchB008RuleOfImmutableTypeAnnotationIgnored:\n this_is_not_fine: list[int] = default_function()\n # ignored\n this_is_fine: int = f()\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/17424\n@dataclass(frozen=True)\nclass C:\n foo: int = 1\n\n\n@dataclass\nclass D:\n c: C = C()\n\n\n@dataclass\nclass E:\n c: C = C()\n\n# https://github.com/astral-sh/ruff/issues/20266\n@dataclass(frozen=True)\nclass C:\n @dataclass(frozen=True)\n class D:\n foo: int = 1\n\n d: D = D() # OK","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_04.py","code":"from dataclasses import dataclass \nfrom typing import TYPE_CHECKING\n\n\ndef default_function() ->list[int]:\n return []\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\nif TYPE_CHECKING:\n from typing import ClassVar\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_05.py","code":"from dataclasses import InitVar, KW_ONLY, MISSING, dataclass, field\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n # Errors\n no_annotation = r\"foo\"\n missing = MISSING\n field = field()\n\n # No errors\n __slots__ = (\"foo\", \"bar\")\n __radd__ = __add__\n _private_attr = 100\n\n with_annotation: str\n with_annotation_and_default: int = 42\n with_annotation_and_field_specifier: bytes = field()\n\n class_var_no_arguments: ClassVar = 42\n class_var_with_arguments: ClassVar[int] = 42\n\n init_var_no_arguments: InitVar = \"lorem\"\n init_var_with_arguments: InitVar[str] = \"ipsum\"\n\n kw_only: KW_ONLY\n tu, ple, [unp, ack, ing] = (0, 1, 2, [3, 4, 5])\n mul, [ti, ple] = (a, ssign), ment = {1: b\"3\", \"2\": 4}, [6j, 5]\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_06.py","code":"from dataclasses import dataclass\nfrom enum import Enum, Flag, IntEnum, IntFlag, StrEnum, ReprEnum\n\nimport attr\nimport attrs\n\n\n## Errors\n\n@dataclass\nclass E(Enum): ...\n\n\n@dataclass # Foobar\nclass E(Flag): ...\n\n\n@dataclass()\nclass E(IntEnum): ...\n\n\n@dataclass() # Foobar\nclass E(IntFlag): ...\n\n\n@dataclass(\n frozen=True\n)\nclass E(StrEnum): ...\n\n\n@dataclass( # Foobar\n frozen=True\n)\nclass E(ReprEnum): ...\n\n\n@dataclass(\n frozen=True\n) # Foobar\nclass E(Enum): ...\n\n\n## No errors\n\n@attrs.define\nclass E(Enum): ...\n\n\n@attrs.frozen\nclass E(Enum): ...\n\n\n@attrs.mutable\nclass E(Enum): ...\n\n\n@attr.s\nclass E(Enum): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_01.py","code":"import typing\nimport typing_extensions\nfrom typing import Literal\n\n# Shouldn't affect non-union field types.\nfield1: Literal[1] # OK\n\n# Should emit for duplicate field types.\nfield2: Literal[1] | Literal[2] # Error\n\n# Should emit for union types in arguments.\ndef func1(arg1: Literal[1] | Literal[2]): # Error\n print(arg1)\n\n\n# Should emit for unions in return types.\ndef func2() -> Literal[1] | Literal[2]: # Error\n return \"my Literal[1]ing\"\n\n\n# Should emit in longer unions, even if not directly adjacent.\nfield3: Literal[1] | Literal[2] | str # Error\nfield4: str | Literal[1] | Literal[2] # Error\nfield5: Literal[1] | str | Literal[2] # Error\nfield6: Literal[1] | bool | Literal[2] | str # Error\n\n# Should emit for non-type unions.\nfield7 = Literal[1] | Literal[2] # Error\n\n# Should emit for parenthesized unions.\nfield8: Literal[1] | (Literal[2] | str) # Error\n\n# Should handle user parentheses when fixing.\nfield9: Literal[1] | (Literal[2] | str) # Error\nfield10: (Literal[1] | str) | Literal[2] # Error\n\n# Should emit for union in generic parent type.\nfield11: dict[Literal[1] | Literal[2], str] # Error\n\n# Should emit for unions with more than two cases\nfield12: Literal[1] | Literal[2] | Literal[3] # Error\nfield13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error\n\n# Should emit for unions with more than two cases, even if not directly adjacent\nfield14: Literal[1] | Literal[2] | str | Literal[3] # Error\n\n# Should emit for unions with mixed literal internal types\nfield15: Literal[1] | Literal[\"foo\"] | Literal[True] # Error\n\n# Shouldn't emit for duplicate field types with same value; covered by Y016\nfield16: Literal[1] | Literal[1] # OK\n\n# Shouldn't emit if in new parent type\nfield17: Literal[1] | dict[Literal[2], str] # OK\n\n# Shouldn't emit if not in a union parent\nfield18: dict[Literal[1], Literal[2]] # OK\n\n# Should respect name of literal type used\nfield19: typing.Literal[1] | typing.Literal[2] # Error\n\n# Should emit in cases with newlines\nfield20: typing.Union[\n Literal[\n 1 # test\n ],\n Literal[2],\n] # Error, newline and comment will not be emitted in message\n\n# Should handle multiple unions with multiple members\nfield21: Literal[1, 2] | Literal[3, 4] # Error\n\n# Should emit in cases with `typing.Union` instead of `|`\nfield22: typing.Union[Literal[1], Literal[2]] # Error\n\n# Should emit in cases with `typing_extensions.Literal`\nfield23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error\n\n# Should emit in cases with nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error\n\n# Should emit in cases with mixed `typing.Union` and `|`\nfield25: typing.Union[Literal[1], Literal[2] | str] # Error\n\n# Should emit only once in cases with multiple nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error\n\n# Should use the first literal subscript attribute when fixing\nfield25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error\n\nfrom typing import IO, Literal\n\nInlineOption = Literal[\"a\"] | Literal[\"b\"] | IO[str]\n\n# Should use unsafe fix when comments are deleted\nfield26: (\n # First comment\n Literal[\"a\", \"b\"]\n # Second comment\n | Literal[\"c\", \"d\"]\n)\nfield27: (\n Literal[\"a\", \"b\"] # First comment\n | Literal[\"c\", \"d\"] # Second comment\n)\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI030.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_02.py","code":"import typing\nfrom typing import Literal, TypeAlias, Union\n\nA: str | Literal[\"foo\"]\nB: TypeAlias = typing.Union[Literal[b\"bar\", b\"foo\"], bytes, str]\nC: TypeAlias = typing.Union[Literal[5], int, typing.Union[Literal[\"foo\"], str]]\nD: TypeAlias = typing.Union[Literal[b\"str_bytes\", 42], bytes, int]\nE: TypeAlias = typing.Union[typing.Union[typing.Union[typing.Union[Literal[\"foo\"], str]]]]\nF: TypeAlias = typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\nG: typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\n\ndef func(x: complex | Literal[1J], y: Union[Literal[3.14], float]): ...\n\n# OK\nA: Literal[\"foo\"]\nB: TypeAlias = Literal[b\"bar\", b\"foo\"]\nC: TypeAlias = typing.Union[Literal[5], Literal[\"foo\"]]\nD: TypeAlias = Literal[b\"str_bytes\", 42]\n\ndef func(x: Literal[1J], y: Literal[3.14]): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI051.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_03.py","code":"from typing import Literal\nimport typing as t\nimport typing_extensions\n\nx: Literal[True, False, True, False] # PYI062 twice here\n\ny: Literal[1, print(\"hello\"), 3, Literal[4, 1]] # PYI062 on the last 1\n\nz: Literal[{1, 3, 5}, \"foobar\", {1,3,5}] # PYI062 on the set literal\n\nLiteral[1, Literal[1]] # once\nLiteral[1, 2, Literal[1, 2]] # twice\nLiteral[1, Literal[1], Literal[1]] # twice\nLiteral[1, Literal[2], Literal[2]] # once\nt.Literal[1, t.Literal[2, t.Literal[1]]] # once\ntyping_extensions.Literal[1, 1, 1] # twice\nLiteral[\n 1, # comment\n Literal[ # another comment\n 1\n ]\n] # once\n\n# Ensure issue is only raised once, even on nested literals\nMyType = Literal[\"foo\", Literal[True, False, True], \"bar\"] # PYI062\n\nn: Literal[\"No\", \"duplicates\", \"here\", 1, \"1\"]\n\n\n# nested literals, all equivalent to `Literal[1]`\nLiteral[Literal[1]] # no duplicate\nLiteral[Literal[Literal[1], Literal[1]]] # once\nLiteral[Literal[1], Literal[Literal[Literal[1]]]] # once\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI062.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_01.py","code":"# parse_options: {\"target-version\": \"3.8\"}\ndef foo(a, /): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pos_only_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_02.py","code":"lambda: a\nlambda: 1\nlambda x: 1\nlambda x, y: ...\nlambda a, b, c: 1\nlambda a, b=20, c=30: 1\nlambda x, y: x * y\nlambda y, z=1: z * y\nlambda *a: a\nlambda *a, z, x=0: ...\nlambda *, a, b, c: 1\nlambda *, a, b=20, c=30: 1\nlambda a, b, c, *, d, e: 0\nlambda **kwargs: f()\nlambda *args, **kwargs: f() + 1\nlambda *args, a, b=1, **kwargs: f() + 1\nlambda a, /: ...\nlambda a, /, b: ...\nlambda a=1, /,: ...\nlambda a, b, /, *, c: ...\nlambda kw=1, *, a: ...\nlambda a, b=20, /, c=30: 1\nlambda a, b, /, c, *, d, e: 0\nlambda a, b, /, c, *d, e, **f: 0","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/lambda.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_01.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/decorator_named_expression_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_03.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_function_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_04.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_comp_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_05.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{x := 1, 2, 3}\n{1, x := 2, 3}\n{1, 2, x := 3}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_literal_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_06.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/walrus_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_07.py","code":"# parse_options: { \"target-version\": \"3.9\" }\n@buttons[0].clicked.connect\ndef spam(): ...\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/decorator_expression_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_08.py","code":"[a := 0 for x in range(0)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_rebound_comprehension_variable.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_09.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[(x:=1)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_10.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{(x := 1), 2, 3}\n{(last := x) for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_11.py","code":"# parse_options: {\"target-version\": \"3.9\"}\n{x := 1, 2, 3}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_12.py","code":"class F(y := list): ...\ndef f():\n class G((yield 1)): ...\n class H((yield from 1)): ...\nasync def f():\n class G((await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_13.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_function_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_14.py","code":"# parse_options: {\"target-version\": \"3.13\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_15.py","code":"# parse_options: { \"target-version\": \"3.8\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/walrus_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_16.py","code":"# This only tests the call arguments and not the expression before the opening parenthesis.\n\n# Simple\ncall()\ncall(x, y)\ncall(x, y,) # Trailing comma\ncall(x=1, y=2)\ncall(*x)\ncall(**x)\n\n# Order\ncall(x, y=1)\ncall(x, *y)\ncall(x, **y)\ncall(x=1, *y)\ncall(x=1, **y)\ncall(*x, **y)\ncall(*x, y, z)\ncall(**x, y=1, z=2)\ncall(*x1, *x2, **y1, **y2)\ncall(x=1, **y, z=1)\n\n# Keyword expression\ncall(x=1 if True else 2)\ncall(x=await y)\ncall(x=lambda y: y)\ncall(x=(y := 1))\n\n# Yield expression\ncall((yield x))\ncall((yield from x))\n\n# Named expression\ncall(x := 1)\ncall(x := 1 for i in iter)\n\n# Starred expressions\ncall(*x and y)\ncall(*x | y)\ncall(*await x)\ncall(*lambda x: x)\ncall(*x if True else y)\n\n# Double starred\ncall(**x)\ncall(**x and y)\ncall(**await x)\ncall(**x if True else y)\ncall(**(yield x))\ncall(**lambda x: x)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/arguments.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_17.py","code":"# Simple\n{}\n{1: 2}\n{1: 2, a: 1, b: 'hello'}\n\n# Mixed indentations\n{\n}\n{\n 1:\n 2,\n 3\n :4\n}\n\n# Nested\n{{1: 2}: {3: {4: 5}}}\n\n# Lambda expressions\n{lambda x: x: 1}\n{'A': lambda p: None, 'B': C,}\n\n# Named expressions\n{(x := 1): y}\n{(x := 1): (y := 2)}\n\n# Double star unpacking\n{**d}\n{a: b, **d}\n{**a, **b}\n{\"a\": \"b\", **c, \"d\": \"e\"}\n{1: 2, **{'nested': 'dict'}}\n{x * 1: y ** 2, **call()}\n# Here, `not` isn't allowed but parentheses resets the precedence\n{**(not x)}\n\n# Random expressions\n{1: x if True else y}\n{x if True else y: y for x in range(10) for y in range(10)}\n{{1, 2}: 3, x: {1: 2,},}\n{(x): (y), (z): (a)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/dictionary.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_18.py","code":"(x for target in iter)\n(x async for target in iter)\n(x for target in iter if x in y if a and b if c)\n(x for target1 in iter1 if x and y for target2 in iter2 if a > b)\n(x for target1 in iter1 if x and y async for target2 in iter2 if a > b)\n\n# Named expression\n(x := y + 1 for y in z)\n\n# If expression\n(x if y else y for y in z)\n\n# Arguments\n\" \".join(\n sql\n for sql in (\n \"LIMIT %d\" % limit if limit else None,\n (\"OFFSET %d\" % offset) if offset else None,\n )\n)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/generator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_19.py","code":"# Simple lists\n[]\n[1]\n[1,]\n[1, 2, 3]\n[1, 2, 3,]\n\n# Mixed with indentations\n[\n]\n[\n 1\n]\n[\n 1,\n 2,\n]\n\n# Nested\n[[[1]]]\n[[1, 2], [3, 4]]\n\n# Named expression\n[x := 2]\n[x := 2,]\n[1, x := 2, 3]\n\n# Star expression\n[1, *x, 3]\n[1, *x | y, 3]\n\n# Random expressions\n[1 + 2, [1, 2, 3, 4], (a, b + c, d), {a, b, c}, {a: 1}, x := 2]\n[call1(call2(value.attr()) for element in iter)]\n[item in xs]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/list.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_20.py","code":"(name := 0)\n(name := (x * y))\n(name := 1 + 1)\n(name := (*x, y))\n(name := x if True else y)\n(name := lambda x: x)\n(name := (yield x))\n(name := (yield from x))","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/named.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_21.py","code":"(expr)\n(expr)()\n(expr)()()()\n\n(a and b or c)\n(lambda x: x)\n(x := 2)\n(yield x)\n(yield from x)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/parenthesized.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_22.py","code":"# Simple sets\n{}\n{1}\n{1,}\n{1, 2, 3}\n{1, 2, 3,}\n\n# Mixed with indentations\n{\n}\n{\n 1\n}\n{\n 1,\n 2,\n}\n\n# Nested\n{{1}}\n{{1, 2}, {3, 4}}\n\n# Named expression\n{x := 2}\n{1, x := 2, 3}\n{1, (x := 2),}\n\n# Star expression\n{1, *x, 3}\n{1, *x | y, 3}\n\n# Random expressions\n{1 + 2, (a, b), {1, 2, 3}, {a: b, **d}}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/set.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_23.py","code":"# With parentheses\n()\n(())\n((()), ())\n(a,)\n(a, b)\n(a, b,)\n((a, b))\n\n# Without parentheses\na,\na, b\na, b,\n\n# Starred expression\n*a,\na, *b\n*a | b, *await x, (), *()\n(*a,)\n(a, *b)\n(*a | b, *await x, (), *())\n\n# Named expression\n(x := 1,)\n(x, y := 2)\n(x, y := 2, z)\nx, (y := 2), z\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_24.py","code":"# Simple\n-1\n+1\n~1\nnot x\n\n# Multiple\n---1\n-+~1\nnot-+~1\nnot not x\n\n# Precedence check\n- await 1\n+ await 1 ** -2\n~(1, 2)\n-1 + 2\n\n# Precedence check for `not` operator because it is higher than other unary operators\nnot a and b or not c | d and not e\nnot (x := 1)\nnot a | (not b)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/unary_op.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_25.py","code":"yield\nyield x\nyield x + 1\nyield x and y\nyield call()\nyield [1, 2]\nyield {3, 4}\nyield {x: 5}\nyield x, y\nyield (x, y)\nyield x == y\nyield (x := 1)\nyield x, *y\nyield *x,\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_26.py","code":"yield from x\nyield from x + 1\nyield from x and y\nyield from call()\nyield from [1, 2]\nyield from {3, 4}\nyield from {x: 5}\nyield from (x, y)\nyield from x == y\nyield from (x := 1)\nyield from (x, *x | y)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield_from.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_27.py","code":"@function_decorator\ndef test():\n pass\n\n\n@class_decorator\nclass Test:\n pass\n\n\n@decorator\ndef f(): ...\n\n\n@a.b.c\ndef f(): ...\n\n\n@a\n@a.b.c\ndef f(): ...\n\n\n@a\n@1 | 2\n@a.b.c\nclass T: ...\n\n\n@x := 1\n@x if True else y\n@lambda x: x\n@x and y\n@(yield x)\n@(*x, *y)\ndef f(): ...\n\n\n# This is not multiple decorators on the same line but rather a binary (`@`) expression\n@x @y\ndef foo(): ...\n\n\n@x\n\n\n@y\n\n\ndef foo(): ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/other/decorator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_28.py","code":"# These test cases specifically tests out parsing a list of with items that start with a\n# left parenthesis. This makes parsing ambiguous as to whether the left parenthesis is to\n# parenthesize the with items or part of a parenthesized expression. It's not to test the\n# with statement itself.\n\n# The following sections basically separates between which node does the\n# start parenthesis belongs to.\n\n# Parenthesized with items\n# ------------------------\n#\n# - The opening parenthesis belongs to the with statement.\n# - The range of the first with item shouldn't include the parenthesis.\nwith (item): ...\nwith (item,): ... # with a trailing comma\nwith (((item))): ...\nwith (item1, item2): ...\nwith (item1, item2,): ... # with a trailing comma\nwith ((item1), (item2), item3 as f, (item4)): ...\nwith ((item1, item2), item3): ...\nwith ((x, y) as f): ...\nwith (item1 as f1, item2 as f2): ...\nwith (item1 as f1, item2 as f2,): ... # with a trailing comma\nwith (item == 10,): ...\nwith ((item := 10)): ...\nwith ((item := 10,)): ...\nwith ((*item,)): ...\nwith ((item1 := 10), item2): ...\nwith (item1 as f, (item2 := 10)): ...\nwith (foo()): ...\nwith (foo(),): ...\nwith (foo() as f): ...\nwith (f\"{item := 42}\"): ...\nwith (f\"{(item := 42)}\"): ...\nwith ((x for x in range(10)), item): ...\nwith (item, (x for x in range(10))): ...\nwith (item, (x for x in range(10)), item): ...\nwith (data[1:2]): ...\nwith (data[1:2] as f): ...\nwith ((x for x in iter) as y): ...\n\n# Parenthesized expression\n# ------------------------\n#\n# - The opening parenthesis belongs to the context expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (item) as f: ...\nwith (item := 10): ...\nwith (item := 10) as f: ...\nwith ( item := 1 ): ...\nwith (item1 := 42), item2: ...\nwith (root + filename).read(): ... # Postfix expression\nwith (root + filename).read() as f: ... # Postfix expression\nwith (foo)(): ... # Postfix expression\nwith (foo)() as f: ... # Postfix expression\nwith (foo()) as f: ...\nwith (data[1:2]) as f: ...\nwith (1, 2, 3)[0]: ... # Postfix expression\nwith (1, 2, 3)[0] as f: ... # Postfix expression\nwith (item1), (item2): ...\nwith (open('a.py')), (open('b.py')): ...\nwith (yield x): ...\nwith ((yield x)): ...\nwith (yield from x): ...\nwith ((yield from x)): ...\nwith (yield x) as f: ...\nwith (yield x,) as f: ...\n\n\n# Tuple expression\n# ----------------\n#\n# - This is a sub-case of the parenthesized expression and requires transforming the list of\n# with items from the speculative parsing to a single with item containing a tuple expression.\n# - The opening parenthesis belongs to the tuple expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (): ...\nwith () as f: ...\nwith (item := 42,): ...\nwith (1, item := 2): ...\nwith (item1 := 10, item2): ...\nwith (item1, item2 := 2, item3) as f: ...\nwith (item,) as f: ...\nwith (*item,): ...\nwith (*item,) as f: ...\nwith (item1, item2) as f: ...\nwith (item1, item2,) as f: ...\nwith (item1, item2), item3: ...\nwith ((item1, item2), item3) as f: ...\nwith (item1,), item2, (item3, item4) as f: ...\nwith (item1, item2) as f1, item3 as f2: ...\nwith (item1, *item2): ...\nwith (item1, *item2) as f: ...\nwith (item1 := 10, *item2): ...\nwith ((item1 := 10), *item2): ...\n\n\n# Parenthesized generator expression\n# ----------------------------------\n#\n# - The opening parenthesis belongs to the generator expression\n# - The range of the with item should include the parenthesis\nwith (x for x in range(10)): ...\nwith (x async for x in range(10)): ...\nwith (x for x in range(10)), item: ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/ambiguous_lpar_with_items.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_29.py","code":"if 1: 10\nelif 2: 20\nelse: 30\n\nif True:\n 1\n ...\nif x < 1:\n ...\nelse:\n pass\n\nif a:\n pass\nelif b:\n ...\n\nif a and b:\n ...\nelif True:\n ...\nelif c:\n ...\nelif d:\n ...\nelse:\n f()\n\n# Valid test expression\nif a := b: ...\nelif a := b: ...\nif lambda x: x: ...\nelif lambda x: x: ...\nif await x: ...\nelif await x: ...\nif (yield x): ...\nelif (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/if.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_30.py","code":"return\nreturn x\nreturn *x, *y\nreturn (x := 1)\nreturn None\nreturn x and y\nreturn 1 < 2\nreturn 1, 2,\nreturn call()\nreturn attr.value()\nreturn await x\nreturn lambda x: y\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/return.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_31.py","code":"while x:\n ...\n\nwhile (x > 1) and y:\n pass\nelse:\n ...\n\nwhile x and y:\n ...\n print('Hello World!')\n\nelse:\n print('Olá, Mundo!')\n ...\n\nwhile a := b: ...\nwhile (a := b) and c: ...\nwhile lambda x: x: ...\nwhile await x: ...\n\nif True:\n while x:\n pass\n else:\n pass\nelse:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/while.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.9","idiom_id":"annotated","pep":"593","introduced_in":"3.9","form":"modern","file":"annotated/modern_01.py","code":"\"\"\"\nTests the typing.Annotated special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#annotated\n\n# > The first argument to Annotated must be a valid type\n\nfrom dataclasses import InitVar, dataclass\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Literal,\n NotRequired,\n Required,\n TypeAlias,\n TypeVar,\n TypedDict,\n Union,\n)\n\nT = TypeVar(\"T\")\n\n\nGood1: Annotated[Union[int, str], \"\"]\nGood2: Annotated[int | None, \"\"]\nGood3: Annotated[list[int], \"\"]\nGood4: Annotated[Any, \"\"]\nGood5: Annotated[tuple[int, ...] | list[int], \"\"]\nGood6: Annotated[Callable[..., int], \"\"]\nGood7: Annotated[\"int | str\", \"\"]\nGood8: Annotated[list[\"int | str\"], \"\"]\n\n\nBad1: Annotated[[int, str], \"\"] # E: invalid type expression\nBad2: Annotated[((int, str),), \"\"] # E: invalid type expression\nBad3: Annotated[[int for i in range(1)], \"\"] # E: invalid type expression\nBad4: Annotated[{\"a\": \"b\"}, \"\"] # E: invalid type expression\nBad5: Annotated[(lambda: int)(), \"\"] # E: invalid type expression\nBad6: Annotated[[int][0], \"\"] # E: invalid type expression\nBad7: Annotated[int if 1 < 3 else str, \"\"] # E: invalid type expression\nBad8: Annotated[var1, \"\"] # E: invalid type expression\nBad9: Annotated[True, \"\"] # E: invalid type expression\nBad10: Annotated[1, \"\"] # E: invalid type expression\nBad11: Annotated[list or set, \"\"] # E: invalid type expression\nBad12: Annotated[f\"{'int'}\", \"\"] # E: invalid type expression\n\n\n# > Multiple type annotations are supported (Annotated supports variadic arguments):\n\nMulti1: Annotated[int | str, 3, \"\"]\nMulti2: Annotated[int | str, 3, \"\", lambda x: x, max(1, 2)]\n\n# > Annotated must be called with at least two arguments ( Annotated[int] is not valid)\n\nBad13: Annotated[int] # E: requires at least two arguments\n\n\n# > Annotated types can be nested\n\nNested1: list[Annotated[dict[str, Annotated[str, \"\"]], \"\"]]\nNested2: Annotated[list[Annotated[dict[str, Annotated[Literal[1, 2, 3], \"\"]], \"\"]], \"\"]\n\n\n# > Annotated is not type compatible with type or type[T]\nSmallInt: TypeAlias = Annotated[int, \"\"]\n\nnot_type1: type[Any] = Annotated[int, \"\"] # E\nnot_type2: type[Any] = SmallInt # E\n\n\ndef func4(x: type[T]) -> T:\n return x()\n\n\nfunc4(Annotated[str, \"\"]) # E\nfunc4(SmallInt) # E\n\n\n# > An attempt to call Annotated (whether parameterized or not) should be\n# > treated as a type error by type checkers.\n\nAnnotated() # E\nAnnotated[int, \"\"]() # E\nSmallInt(1) # E\n\n\nclass ClassA:\n a: ClassVar[Annotated[int, \"\"]] = 1\n b: Annotated[ClassVar[int], \"\"] = 1\n c: Final[Annotated[int, \"\"]] = 1\n d: Annotated[Final[int], \"\"] = 1\n\n\n@dataclass\nclass ClassB:\n a: InitVar[Annotated[int, \"\"]]\n b: Annotated[InitVar[int], \"\"]\n\n\nclass ClassC(TypedDict):\n a: Annotated[Required[int], \"\"]\n b: Required[Annotated[int, \"\"]]\n c: Annotated[NotRequired[int], \"\"]\n d: NotRequired[Annotated[int, \"\"]]\n\n\nTA1: TypeAlias = Annotated[int | str, \"\"]\nTA2 = Annotated[Literal[1, 2], \"\"]\nTA3 = Annotated[T, \"\"]\n","source":"typing_tests","origin":"conformance/tests/qualifiers_annotated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_07.py","code":"\"\"\"\nTests the handling of builtins.type[T].\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#type\n\n\nfrom typing import Any, Callable, Generic, Type, TypeAlias, TypeVar, assert_type\n\n\nclass User:\n ...\n\n\nclass BasicUser(User):\n ...\n\n\nclass ProUser(User):\n ...\n\n\nclass TeamUser(User):\n ...\n\n\ndef func1(user_class: type) -> User:\n return user_class()\n\n\ndef func2(user_class: type[User]) -> User:\n return user_class()\n\n\nU = TypeVar(\"U\", bound=User)\n\n\ndef func3(user_class: type[U]) -> U:\n return user_class()\n\n\nassert_type(func1(TeamUser), User)\nassert_type(func2(TeamUser), User)\nassert_type(func3(TeamUser), TeamUser)\n\n\n# > Note that it is legal to use a union of classes as the parameter for type[].\n\n\ndef func4(user_class: type[BasicUser | ProUser]) -> User:\n return user_class()\n\n\nassert_type(func4(BasicUser), User)\nassert_type(func4(ProUser), User)\nfunc4(TeamUser) # E\n\n\n# > Any other special constructs like Callable are not allowed as an argument to type.\n\nT = TypeVar(\"T\")\n\n\ndef func5(x: type[T]) -> None:\n pass\n\n\nfunc5(User) # OK\nfunc5(tuple) # OK\nfunc5(Callable) # E\n\n\n# > When type is parameterized it requires exactly one parameter. Plain type\n# > without brackets, the root of Python’s metaclass hierarchy, is equivalent to type[Any].\n\nbad_type1: type[int, str] # E\n\n\nclass MyMetaA(type):\n ...\n\n\ndef func6(a: type, b: type[Any]):\n assert_type(a, type[Any])\n a = b # OK\n b = a # OK\n a = type # OK\n b = type # OK\n\n\n# > Regarding the behavior of type[Any] (or type), accessing attributes of a\n# > variable with this type only provides attributes and methods defined by\n# > type (for example, __repr__() and __mro__). Such a variable can be called\n# > with arbitrary arguments, and the return type is Any.\n\n\ndef func7(a: type, b: type[Any], c: Type, d: Type[Any]):\n assert_type(a.__mro__, tuple[type, ...])\n assert_type(a.unknown, Any)\n assert_type(a.unknown(), Any)\n\n assert_type(b.__mro__, tuple[type, ...])\n assert_type(b.unknown, Any)\n assert_type(b.unknown(), Any)\n\n assert_type(c.__mro__, tuple[type, ...])\n assert_type(c.unknown, Any)\n assert_type(c.unknown(), Any)\n\n assert_type(d.__mro__, tuple[type, ...])\n assert_type(d.unknown, Any)\n assert_type(d.unknown(), Any)\n\n\ndef func8(a: type[object], b: Type[object]):\n assert_type(a.__name__, str)\n a.unknown # E\n\n assert_type(b.__name__, str)\n b.unknown # E\n\n\n# > type is covariant in its parameter, because type[Derived] is a subtype of type[Base]:\n\n\ndef func9(pro_user_class: type[ProUser]):\n assert_type(func3(pro_user_class), ProUser)\n\n\nTA1: TypeAlias = Type\nTA2: TypeAlias = Type[Any]\nTA3: TypeAlias = type\nTA4: TypeAlias = type[Any]\n\n\ndef func10(a: TA1, b: TA2, c: TA3, d: TA4):\n assert_type(a, type[Any])\n assert_type(b, type[Any])\n assert_type(c, type[Any])\n assert_type(d, type[Any])\n\n\nTA1.unknown # E\nTA2.unknown # E\nTA3.unknown # E\nTA4.unknown # E\n\nTA7: TypeAlias = type[T]\nTA8: TypeAlias = Type[T]\n\n\ndef func11(t1: TA7[T]) -> T:\n return t1()\n\n\ndef func12(t1: TA8[T]) -> T:\n return t1()\n\n\nassert_type(func11(int), int)\nassert_type(func12(int), int)\n\n\ndef func13(v: type):\n x1: Callable[..., Any] = v # OK\n x2: Callable[[int, int], int] = v # OK\n x3: object = v # OK\n x4: type = v # OK\n x5: type[int] = v # OK\n x6: type[Any] = v # OK\n\n\nclass ClassA(Generic[T]):\n def method1(self, v: type) -> type[T]:\n return v # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_type.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_07.py","code":"\"\"\"\nTests the handling of descriptors within a dataclass.\n\"\"\"\n\n# This portion of the dataclass spec is under-specified in the documentation,\n# but its behavior can be determined from the runtime implementation.\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, TypeVar, assert_type, overload\n\nT = TypeVar(\"T\")\n\n\nclass Desc1:\n @overload\n def __get__(self, __obj: None, __owner: Any) -> \"Desc1\":\n ...\n\n @overload\n def __get__(self, __obj: object, __owner: Any) -> int:\n ...\n\n def __get__(self, __obj: object | None, __owner: Any) -> \"int | Desc1\":\n raise NotImplementedError\n\n def __set__(self, __obj: object, __value: int) -> None:\n ...\n\n\n@dataclass\nclass DC1:\n y: Desc1 = Desc1()\n\n\ndc1 = DC1(3)\n\nassert_type(dc1.y, int)\nassert_type(DC1.y, Desc1)\n\n\nclass Desc2(Generic[T]):\n @overload\n def __get__(self, instance: None, owner: Any) -> list[T]:\n ...\n\n @overload\n def __get__(self, instance: object, owner: Any) -> T:\n ...\n\n def __get__(self, instance: object | None, owner: Any) -> list[T] | T:\n raise NotImplementedError\n\n\n@dataclass\nclass DC2:\n x: Desc2[int]\n y: Desc2[str]\n z: Desc2[str] = Desc2()\n\n\nassert_type(DC2.x, list[int])\nassert_type(DC2.y, list[str])\nassert_type(DC2.z, list[str])\n\ndc2 = DC2(Desc2(), Desc2(), Desc2())\nassert_type(dc2.x, int)\nassert_type(dc2.y, str)\nassert_type(dc2.z, str)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_descriptors.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_08.py","code":"\"\"\"\nTests validation of frozen dataclass instances.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#frozen-instances\n\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass DC1:\n a: float\n b: str\n\ndc1 = DC1(1, \"\")\n\ndc1.a = 1 # E: dataclass is frozen\ndc1.b = \"\" # E: dataclass is frozen\n\n\n# This should generate an error because a non-frozen dataclass\n# cannot inherit from a frozen dataclass.\n@dataclass # E[DC2]\nclass DC2(DC1): # E[DC2]\n pass\n\n@dataclass\nclass DC3:\n a: int\n\n# This should generate an error because a frozen dataclass\n# cannot inherit from a non-frozen dataclass.\n@dataclass(frozen=True) # E[DC4]\nclass DC4(DC3): # E[DC4]\n pass\n\n\n@dataclass(frozen=True)\nclass DC1Child(DC1):\n # This should be allowed because attributes within a frozen\n # dataclass are covariant rather than invariant.\n a: int\n","source":"typing_tests","origin":"conformance/tests/dataclasses_frozen.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_09.py","code":"\"\"\"\nTests the synthesis of the __hash__ method in a dataclass.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Callable, Hashable, assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n\n\nassert_type(DC1.__hash__, None)\n\n# These should generate errors because DC1 isn't hashable.\nDC1(0).__hash__() # E\nv1: Hashable = DC1(0) # E\n\n\n@dataclass(eq=True, frozen=True)\nclass DC2:\n a: int\n\n\ndc2_hash: Callable[..., int] = DC2.__hash__ # OK\nDC2(0).__hash__() # OK\nv2: Hashable = DC2(0) # OK\n\n\n@dataclass(eq=True)\nclass DC3:\n a: int\n\n\nassert_type(DC3.__hash__, None)\n\n# These should generate errors because DC3 isn't hashable.\nDC3(0).__hash__() # E\nv3: Hashable = DC3(0) # E\n\n\n@dataclass(frozen=True)\nclass DC4:\n a: int\n\n\ndc4_hash: Callable[..., int] = DC4.__hash__ # OK\nDC4(0).__hash__() # OK\nv4: Hashable = DC4(0) # OK\n\n\n@dataclass(eq=True, unsafe_hash=True)\nclass DC5:\n a: int\n\n\ndc5_hash: Callable[..., int] = DC5.__hash__ # OK\nDC5(0).__hash__() # OK\nv5: Hashable = DC5(0) # OK\n\n\n@dataclass(eq=True)\nclass DC6:\n a: int\n\n def __hash__(self) -> int:\n return 0\n\n\ndc6_hash: Callable[..., int] = DC6.__hash__ # OK\nDC6(0).__hash__() # OK\nv6: Hashable = DC6(0) # OK\n\n\n@dataclass(frozen=True)\nclass DC7:\n a: int\n\n def __eq__(self, other) -> bool:\n return self.a == other.a\n\n\ndc7_hash: Callable[..., int] = DC7.__hash__ # OK\nDC7(0).__hash__() # OK\nv7: Hashable = DC7(0) # OK\n","source":"typing_tests","origin":"conformance/tests/dataclasses_hash.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_10.py","code":"\"\"\"\nTests inheritance rules for dataclasses.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#inheritance\n\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar\n\n\n@dataclass\nclass DC1:\n a: int\n b: str = \"\"\n\n\n@dataclass\nclass DC2(DC1):\n b: str = \"\"\n a: int = 1\n\n\ndc2_1 = DC2(1, \"\")\n\ndc2_2 = DC2()\n\n\n@dataclass\nclass DC3:\n x: float = 15.0\n y: str = \"\"\n\n\n@dataclass\nclass DC4(DC3):\n z: tuple[int] = (10,)\n x: float = 15\n\n\ndc4_1 = DC4(0.0, \"\", (1,))\n\n\n@dataclass\nclass DC5:\n # While this generates an error at runtime for the stdlib dataclass,\n # other libraries that use dataclass_transform don't have similar\n # restrictions. It is therefore not required that a type checker\n # report an error here.\n x: list[int] = [] # E?\n\n\n@dataclass\nclass DC6:\n x: int\n y: ClassVar[int] = 1\n\n\n@dataclass\nclass DC7(DC6):\n # This should generate an error because a ClassVar cannot override\n # an instance variable of the same name.\n x: ClassVar[int] # E\n\n # This should generate an error because an instance variable cannot\n # override a class variable of the same name.\n y: int # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_11.py","code":"\"\"\"\nTests the keyword-only feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY, field\n\n\n@dataclass\nclass DC1:\n a: str\n _: KW_ONLY\n b: int = 0\n\n\nDC1(\"hi\")\nDC1(a=\"hi\")\nDC1(a=\"hi\", b=1)\nDC1(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC1(\"hi\", 1) # E\n\n\n@dataclass\nclass DC2:\n b: int = field(kw_only=True, default=3)\n a: str\n\n\nDC2(\"hi\")\nDC2(a=\"hi\")\nDC2(a=\"hi\", b=1)\nDC2(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC2(\"hi\", 1) # E\n\n\n@dataclass(kw_only=True)\nclass DC3:\n a: str = field(kw_only=False)\n b: int = 0\n\n\nDC3(\"hi\")\nDC3(a=\"hi\")\nDC3(a=\"hi\", b=1)\nDC3(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC3(\"hi\", 1) # E\n\n\n@dataclass\nclass DC4(DC3):\n c: float\n\n\nDC4(\"\", 0.2, b=3)\nDC4(a=\"\", b=3, c=0.2)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_kwonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_12.py","code":"\"\"\"\nTests the match_args feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY\nfrom typing import assert_type, Literal\n\n# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method\n\n@dataclass(match_args=True)\nclass DC1:\n x: int\n _: KW_ONLY\n y: str\n\nassert_type(DC1.__match_args__, tuple[Literal['x']])\n\n# The match_args default is True\n\n@dataclass\nclass DC2:\n x: int\n\nassert_type(DC2.__match_args__, tuple[Literal['x']])\n\n# __match_args__ is created even if __init__() is not generated\n\n@dataclass(match_args=True, init=False)\nclass DC3:\n x: int = 0\n\nassert_type(DC3.__match_args__, tuple[Literal['x']])\n\n# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.\n\n@dataclass(match_args=False)\nclass DC4:\n x: int\n\nDC4.__match_args__ # E\n\n@dataclass(match_args=True)\nclass DC5:\n __match_args__ = ()\n x: int\n\nassert_type(DC5.__match_args__, tuple[()])\n","source":"typing_tests","origin":"conformance/tests/dataclasses_match_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_13.py","code":"\"\"\"\nTests the synthesized comparison methods for dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass DC1:\n a: str\n b: int\n\n\n@dataclass(order=True)\nclass DC2:\n a: str\n b: int\n\n\ndc1_1 = DC1(\"\", 0)\ndc1_2 = DC1(\"\", 0)\n\nif dc1_1 < dc1_2:\n pass\n\nif dc1_1 <= dc1_2:\n pass\n\nif dc1_1 > dc1_2:\n pass\n\nif dc1_1 >= dc1_2:\n pass\n\nif dc1_1 == dc1_2:\n pass\n\nif dc1_1 != dc1_2:\n pass\n\nif dc1_1 == None:\n pass\n\nif dc1_1 != None:\n pass\n\ndc2_1 = DC2(\"hi\", 2)\n\n# This should generate an error because the types are\n# incompatible.\nif dc1_1 < dc2_1: # E:\n pass\n\nif dc1_1 != dc2_1:\n pass\n","source":"typing_tests","origin":"conformance/tests/dataclasses_order.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_14.py","code":"\"\"\"\nTests type checking of the __post_init__ method in a dataclass.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#post-init-processing\n\nfrom dataclasses import InitVar, dataclass, field, replace\nfrom typing import assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n b: int\n x: InitVar[int]\n c: int\n y: InitVar[str]\n\n def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y\n pass\n\n\ndc1 = DC1(1, 2, 3, 4, \"\")\n\nassert_type(dc1.a, int)\nassert_type(dc1.b, int)\nassert_type(dc1.c, int)\nprint(dc1.x) # E: cannot access InitVar\nprint(dc1.y) # E: cannot access InitVar\n\n@dataclass\nclass DC2:\n x: InitVar[int]\n y: InitVar[str]\n\n def __post_init__(self, x: int) -> None: # E: missing y\n pass\n\n\n@dataclass\nclass DC3:\n _name: InitVar[str] = field()\n name: str = field(init=False)\n\n def __post_init__(self, _name: str):\n ...\n\n\n@dataclass\nclass DC4(DC3):\n _age: InitVar[int] = field()\n age: int = field(init=False)\n\n def __post_init__(self, _name: str, _age: int):\n ...\n","source":"typing_tests","origin":"conformance/tests/dataclasses_postinit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_15.py","code":"\"\"\"\nTests the slots functionality of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass\n\n# This should generate an error because __slots__ is already defined.\n@dataclass(slots=True) # E[DC1]\nclass DC1: # E[DC1]\n x: int\n\n __slots__ = ()\n\n\n@dataclass(slots=True)\nclass DC2:\n x: int\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass(slots=False)\nclass DC3:\n x: int\n\n __slots__ = (\"x\",)\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass\nclass DC4:\n __slots__ = (\"y\", \"x\")\n x: int\n y: str\n\n\nDC4(1, \"bar\")\n\n\n@dataclass(slots=True)\nclass DC5:\n a: int\n\n\nDC5.__slots__\nDC5(1).__slots__\n\n\n@dataclass\nclass DC6:\n a: int\n\n\n# This should generate an error because __slots__ is not defined.\nDC6.__slots__ # E\n\n# This should generate an error because __slots__ is not defined.\nDC6(1).__slots__ # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_slots.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_16.py","code":"\"\"\"\nTests basic handling of the dataclass factory.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html\n# Also, see https://peps.python.org/pep-0557/\n\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar, assert_type\nimport sys\n\nT = TypeVar(\"T\")\n\n\n@dataclass(order=True)\nclass InventoryItem:\n x = 0\n name: str\n unit_price: float\n quantity_on_hand: int = 0\n\n def total_cost(self) -> float:\n return self.unit_price * self.quantity_on_hand\n\n\nv1 = InventoryItem(\"soap\", 2.3)\n\n\nclass InventoryItemInitProto(Protocol):\n def __call__(\n self, name: str, unit_price: float, quantity_on_hand: int = ...\n ) -> None: ...\n\n\n# Validate the type of the synthesized __init__ method.\nx1: InventoryItemInitProto = v1.__init__\n\n# Make sure the following additional methods were synthesized.\nprint(v1.__repr__)\nprint(v1.__eq__)\nprint(v1.__ne__)\nprint(v1.__lt__)\nprint(v1.__le__)\nprint(v1.__gt__)\nprint(v1.__ge__)\n\nassert_type(v1.name, str)\nassert_type(v1.unit_price, float)\nassert_type(v1.quantity_on_hand, int)\n\nv2 = InventoryItem(\"name\") # E: missing unit_price\nv3 = InventoryItem(\"name\", \"price\") # E: incorrect type for unit_price\nv4 = InventoryItem(\"name\", 3.1, 3, 4) # E: too many arguments\n\n\n# > TypeError will be raised if a field without a default value follows a\n# > field with a default value. This is true either when this occurs in a\n# > single class, or as a result of class inheritance.\n@dataclass # E[DC1]\nclass DC1:\n a: int = 0 # E[DC1]: field with default should follow a field with no default.\n b: int # E[DC1]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC2]\nclass DC2:\n a: int = field(default=1) # E[DC2]: field with default should follow a field with no default.\n b: int # E[DC2]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC3]\nclass DC3:\n a: InitVar[int] = 0 # E[DC3]: field with default should follow a field with no default.\n b: int # E[DC3]: field with no default cannot follow field with default.\n\n\n@dataclass\nclass DC4:\n a: int = field(init=False)\n b: int\n\n\nv5 = DC4(0)\nv6 = DC4(0, 1) # E: too many parameters\n\n\n@dataclass\nclass DC5:\n a: int = field(default_factory=str) # E: type mismatch\n\n\ndef f(s: str) -> int:\n return int(s)\n\n\n@dataclass\nclass DC6:\n a: ClassVar[int] = 0\n b: str\n c: Callable[[str], int] = f\n\n\ndc6 = DC6(\"\")\nassert_type(dc6.a, int)\nassert_type(DC6.a, int)\nassert_type(dc6.b, str)\nassert_type(dc6.c, Callable[[str], int])\n\n\n@dataclass\nclass DC7:\n x: int\n\n\n@dataclass(init=False)\nclass DC8(DC7):\n y: int\n\n def __init__(self, a: DC7, y: int):\n self.__dict__ = a.__dict__\n self.y = y\n\n\na = DC7(3)\nb = DC8(a, 5)\n\n# This should generate an error because there is an extra parameter\nDC7(3, 4) # E\n\n# This should generate an error because there is one too few parameters\nDC8(a) # E\n\n\n@dataclass\nclass DC9:\n a: str = field(init=False, default=\"s\")\n b: bool = field()\n\n\n@dataclass\nclass DC10(DC9):\n a: str = field()\n b: bool = field()\n\n\n@dataclass(init=False)\nclass DC11:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC11(3)\n\n\n@dataclass(init=True)\nclass DC12:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC12(3)\n\n\n@dataclass(init=False)\nclass DC13:\n x: int\n x_squared: int\n\n\n# This should generate an error because there is no matching\n# override __init__ method and no synthesized __init__.\nDC13(3) # E\n\n\n@dataclass\nclass DC14:\n prop_1: str = field(init=False)\n prop_2: str = field(default=\"hello\")\n prop_3: str = field(default_factory=lambda: \"hello\")\n\n\n@dataclass\nclass DC15(DC14):\n prop_2: str = \"\"\n\n\ndc15 = DC15(prop_2=\"test\")\n\nassert_type(dc15.prop_1, str)\nassert_type(dc15.prop_2, str)\nassert_type(dc15.prop_3, str)\n\n\nclass DataclassProto(Protocol):\n __dataclass_fields__: ClassVar[dict[str, Any]]\n\n\nv7: DataclassProto = dc15\n\n\n@dataclass\nclass DC16(Generic[T]):\n value: T\n\n\nassert_type(DC16(1), DC16[int])\n\n\nclass DC17(DC16[str]):\n pass\n\n\nassert_type(DC17(\"\"), DC17)\n\n\n@dataclass\nclass DC18:\n x: int = field()\n # This may generate a type checker error because an unannotated field\n # will result in a runtime exception.\n y = field() # E?\n\n\n# > Dataclass fields may be conditional, via checks of the same\n# > statically-known conditions that a type-checker understands elsewhere,\n# > such as Python version:\n\n@dataclass\nclass DC19:\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nDC19(1, 2)\nDC19(1, 2, 3) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_01.py","code":"\"\"\"\nTests the handling of ClassVar and Final in dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import assert_type, ClassVar, Final\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#dataclass-semantics\n\n# > A final class variable on a dataclass must be explicitly annotated as\n# e.g. x: ClassVar[Final[int]] = 3.\n\n\n@dataclass\nclass D:\n final_no_default: Final[int]\n final_with_default: Final[str] = \"foo\"\n final_classvar: ClassVar[Final[int]] = 4\n # we don't require support for Final[ClassVar[...]] because the dataclasses\n # runtime implementation won't recognize it as a ClassVar either\n\n\n# An explicitly marked ClassVar can be accessed on the class:\nassert_type(D.final_classvar, int)\n\n# ...but not assigned to, because it's Final:\nD.final_classvar = 10 # E: can't assign to final attribute\n\n# A non-ClassVar attribute (with or without default) is a dataclass field:\nd = D(final_no_default=1, final_with_default=\"bar\")\nassert_type(d.final_no_default, int)\nassert_type(d.final_with_default, str)\n\n# ... but can't be assigned to (on the class or on an instance):\nd.final_no_default = 10 # E: can't assign to final attribute\nd.final_with_default = \"baz\" # E: can't assign to final attribute\nD.final_no_default = 10 # E: can't assign to final attribute\nD.final_with_default = \"baz\" # E: can't assign to final attribute\n","source":"typing_tests","origin":"conformance/tests/dataclasses_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_02.py","code":"\"\"\"\nTests the typing.Final special form.\n\"\"\"\n\nfrom typing import ClassVar, Final, Literal, NamedTuple, TypedDict, assert_type\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#id1\n\nID1: Final[int] = 1\n\nID2: Final = 1\nassert_type(ID2, Literal[1])\n\n# > If the right hand side is omitted, there must be an explicit type argument to Final.\n\nBAD1: Final # E: missing assignment\n\nBAD2: Final[str, int] = \"\" # E: only one type argument allowed\n\n# > There can be at most one final declaration per module or class for a given\n# > attribute.\n\n# > As self.id: Final = 1 (also optionally with a type in square brackets).\n# > This is allowed only in __init__ methods, so that the final instance\n# > attribute is assigned only once when an instance is created.\n\n\nclass ClassA:\n ID1: Final = 1\n\n # > In class bodies and stub files you can omit the right hand side and just\n # > write ID: Final[float]. If the right hand side is omitted, there must be\n # > an explicit type argument to Final.\n ID2: Final # E: missing initialization\n\n # > A final attribute declared in a class body without an initializer must\n # > be initialized in the __init__ method (except in stub files):\n ID3: Final[int] # E: missing initialization\n\n ID4: Final[int] # OK because initialized in __init__\n\n ID5: Final[int] = 0\n\n ID6: Final[int]\n\n ID7: Final[int] = 0\n\n def __init__(self, cond: bool) -> None:\n self.id1: Final = 1\n self.id2: Final[int] = 1\n\n self.ID4 = 1\n\n self.ID5 = 0 # E: Already initialized\n\n if cond:\n self.ID6 = 1\n else:\n self.ID6 = 2\n\n def method1(self) -> None:\n self.id3: Final = 1 # E: not allowed outside of __init__ method.\n self.id4: Final[int] = 1 # E: not allowed outside of __init__ method.\n\n self.ID7 = 0 # E: cannot modify Final value\n\n self.ID7 += 1 # E: cannot modify Final value\n\n\nRATE: Final = 3000\nRATE = 300 # E: Cannot redefine Final value\n\n# > There can’t be separate class-level and instance-level constants\n# > with the same name.\n\n\nclass ClassB:\n DEFAULT_ID: Final = 0\n\n\nClassB.DEFAULT_ID = 0 # E: Cannot redefined value\n\n\n# > A type checker should prevent final attributes from being overridden in a subclass:\n\n\nclass ClassC:\n BORDER_WIDTH: Final = 2.5\n\n __private: Final = 0\n\n\nclass ClassCChild(ClassC):\n BORDER_WIDTH = 2.5 # E: Cannot override Final value\n\n __private = 0 # OK\n\n\n# > Type checkers should infer a final attribute that is initialized in a class\n# > body as being a class variable. Variables should not be annotated with both\n# > ClassVar and Final. (Except in a dataclass; see dataclasses_final.py.)\n\n\nclass ClassD:\n VALUE1: Final = 1\n\n VALUE2: ClassVar[Final] = 1 # E: Final cannot be used with ClassVar\n VALUE3: Final[ClassVar] = 1 # E: Final cannot be used with ClassVar\n\n\nClassD.VALUE1 # OK\n\n\n# > Final may only be used as the outermost type in assignments or variable\n# > annotations. Using it in any other position is an error. In particular,\n# > Final can’t be used in annotations for function arguments.\n\nx: list[Final[int]] = [] # E\n\n\ndef func1(x: Final[list[int]]) -> None: # E\n ...\n\n\n# > ``Final`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithFinal(TypedDict):\n a: int\n b: Final[int] # E: Final not allowed in a TypedDict\n\n\nclass NTWithFinal(NamedTuple):\n a: int\n b: Final[int] # E: Final not allowed in a NamedTuple\n\n\n# > Type checkers should treat uses of a final name that was initialized with\n# > a literal as if it was replaced by the literal. For example, the following\n# > should be allowed:\n\nX: Final = \"x\"\nY: Final = \"y\"\nN = NamedTuple(\"N\", [(X, int), (Y, int)])\n\nN(x=3, y=4) # OK\nN(a=1) # E\nN(x=\"\", y=\"\") # E\n\n\ndef func2() -> None:\n global ID1\n\n ID1 = 2 # E: cannot modify Final value\n\n x: Final = 3\n\n x += 1 # E: cannot modify Final value\n\n a = (x := 4) # E: cannot modify Final value\n\n for x in [1, 2, 3]: # E: cannot modify Final value\n pass\n\n with open(\"FileName\") as x: # E: cannot modify Final value\n pass\n\n (a, x) = (1, 2) # E: cannot modify Final value\n\n\n# > If a module declares a ``Final`` variable and another module imports that\n# > variable in an import statement by name or wildcard, the imported symbol\n# > inherits the ``Final`` type qualifier. Any attempt to assign a different value\n# > to this symbol should be flagged as an error by a type checker.\n\n\nfrom _qualifiers_final_annotation_1 import TEN\n\nTEN = 9 # E: Cannot redefine Final value\n\nfrom _qualifiers_final_annotation_2 import *\n\nPI = 3.14159 # E: Cannot redefine Final value\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_03.py","code":"\"\"\"\nTests the @final decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#final\n\nfrom typing import final, overload\nfrom _qualifiers_final_decorator import Base3, Base4\n\n# > A type checker should prohibit any class decorated with @final from being\n# > subclassed and any method decorated with @final from being overridden in a\n# > subclass. The method decorator version may be used with all of instance\n# > methods, class methods, static methods, and properties.\n\n\n@final\nclass Base1:\n ...\n\n\nclass Derived1(Base1): # E: Cannot inherit from final class \"Base\"\n ...\n\n\nclass Base2:\n @final\n def method1(self) -> None:\n pass\n\n @final\n @classmethod\n def method2(cls) -> None:\n pass\n\n @final\n @staticmethod\n def method3() -> None:\n pass\n\n # > For overloaded methods, @final should be placed on the implementation.\n\n @overload\n def method4(self, x: int) -> int:\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @final\n def method4(self, x: int | str) -> int | str:\n return 0\n\n\nclass Derived2(Base2):\n def method1(self) -> None: # E\n pass\n\n @classmethod # E[method2]\n def method2(cls) -> None: # E[method2]\n pass\n\n @staticmethod # E[method3]\n def method3() -> None: # E[method3]\n pass\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n def method4(self, x: int | str) -> int | str: # E[method4]\n return 0\n\n\nclass Derived3(Base3):\n @overload # E[Derived3]\n def method(self, x: int) -> int: # E[Derived3]\n ...\n\n @overload # E[Derived3-2]\n @final # E[Derived3-2]: should be applied only to implementation\n def method(self, x: str) -> str: # E[Derived3-2]\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived3]\n return 0\n\n\nclass Derived4(Base4):\n @overload # E[Derived4]\n def method(self, x: int) -> int: # E[Derived4]\n ...\n\n @overload\n def method(self, x: str) -> str:\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived4]\n return 0\n\n\nclass Base5_1:\n ...\n\n\nclass Base5_2:\n @final\n def method(self, v: int) -> None:\n ...\n\n\n# Test multiple inheritance case.\nclass Derived5(Base5_1, Base5_2):\n def method(self) -> None: # E\n ...\n\n\n# > It is an error to use @final on a non-method function.\n\n\n@final # E[func]: not allowed on non-method function.\ndef func1() -> int: # E[func]\n return 0\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_decorator.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_04.py","code":"\"\"\"\nTests the use of Final values when used with TypedDicts.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#use-of-final-values-and-literal-types\n\nfrom typing import Final, Literal, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\n# > Type checkers should allow final names (PEP 591) with string values to be\n# > used instead of string literals in operations on TypedDict objects.\nYEAR: Final = \"year\"\n\nm: Movie = {\"name\": \"Alien\", \"year\": 1979}\nyears_since_epoch = m[YEAR] - 1970\n\n\n# > An expression with a suitable literal type (PEP 586) can be used instead of\n# > a literal value.\ndef get_value(movie: Movie, key: Literal[\"year\", \"name\"]) -> int | str:\n return movie[key]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_04.py","code":"\"\"\"\nTests interactions between Literal types and other typing features.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#interactions-with-other-types-and-features\nfrom enum import Enum\nfrom typing import IO, Any, Final, Generic, Literal, TypeVar, LiteralString, assert_type, overload\n\n\ndef func1(v: tuple[int, str, list[bool]], a: Literal[0], b: Literal[5], c: Literal[-5]):\n assert_type(v[a], int)\n assert_type(v[2], list[bool])\n\n v[b] # E: index out of range\n v[c] # E: index out of range\n v[4] # E: index out of range\n v[-4] # E: index out of range\n\n\n_PathType = str | bytes | int\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"r\", \"w\", \"a\", \"x\", \"r+\", \"w+\", \"a+\", \"x+\"],\n) -> IO[str]:\n ...\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"rb\", \"wb\", \"ab\", \"xb\", \"r+b\", \"w+b\", \"a+b\", \"x+b\"],\n) -> IO[bytes]:\n ...\n\n\n@overload\ndef open(path: _PathType, mode: str) -> IO[Any]:\n ...\n\n\ndef open(path: _PathType, mode: Any) -> Any:\n raise NotImplementedError\n\n\nassert_type(open(\"path\", \"r\"), IO[str])\nassert_type(open(\"path\", \"wb\"), IO[bytes])\nassert_type(open(\"path\", \"other\"), IO[Any])\n\n\nA = TypeVar(\"A\", bound=int)\nB = TypeVar(\"B\", bound=int)\nC = TypeVar(\"C\", bound=int)\n\n\nclass Matrix(Generic[A, B]):\n def __add__(self, other: \"Matrix[A, B]\") -> \"Matrix[A, B]\":\n raise NotImplementedError\n\n def __matmul__(self, other: \"Matrix[B, C]\") -> \"Matrix[A, C]\":\n raise NotImplementedError\n\n def transpose(self) -> \"Matrix[B, A]\":\n raise NotImplementedError\n\n\ndef func2(a: Matrix[Literal[2], Literal[3]], b: Matrix[Literal[3], Literal[7]]):\n c = a @ b\n assert_type(c, Matrix[Literal[2], Literal[7]])\n\n\nT = TypeVar(\"T\", Literal[\"a\"], Literal[\"b\"], Literal[\"c\"])\nS = TypeVar(\"S\", bound=Literal[\"foo\"])\n\n\nclass Status(Enum):\n SUCCESS = 0\n INVALID_DATA = 1\n FATAL_ERROR = 2\n\n\ndef parse_status1(s: str | Status) -> None:\n if s is Status.SUCCESS:\n assert_type(s, Literal[Status.SUCCESS])\n elif s is Status.INVALID_DATA:\n assert_type(s, Literal[Status.INVALID_DATA])\n elif s is Status.FATAL_ERROR:\n assert_type(s, Literal[Status.FATAL_ERROR])\n else:\n assert_type(s, str)\n\n\n# > Type checkers may optionally perform additional analysis for both\n# > enum and non-enum Literal types beyond what is described in the section above.\n#\n# > For example, it may be useful to perform narrowing based on things\n# > like containment or equality checks:\n\ndef expects_bad_status(status: Literal[\"MALFORMED\", \"ABORTED\"]):\n ...\n\n\ndef expects_pending_status(status: Literal[\"PENDING\"]):\n ...\n\n\ndef parse_status2(status: LiteralString) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n\n# Narrowing `str` to `Literal` strings is unsound given the possiblity of\n# user-defined `str` subclasses that could have custom equality semantics,\n# but is explicitly listed by the spec as optional analysis that type checkers\n# may perform.\ndef parse_status3(status: str) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n\nfinal_val1: Final = 3\nassert_type(final_val1, Literal[3])\n\nfinal_val2: Final = True\nassert_type(final_val2, Literal[True])\n","source":"typing_tests","origin":"conformance/tests/literals_interactions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_05.py","code":"\"\"\"\nTests legal and illegal parameterizations of Literal.\n\"\"\"\n\n# > Literal must be parameterized with at least one type.\n\nfrom typing import Any, Literal, TypeVar\nfrom enum import Enum\n\n\nclass Color(Enum):\n RED = 0\n GREEN = 1\n BLUE = 2\n\n\ngood1: Literal[26]\ngood2: Literal[0x1A]\ngood3: Literal[-4]\ngood4: Literal[+5]\ngood5: Literal[\"hello world\"]\ngood6: Literal[b\"hello world\"]\ngood7: Literal[\"hello world\"]\ngood8: Literal[True]\ngood9: Literal[Color.RED]\ngood10: Literal[None]\n\nReadOnlyMode = Literal[\"r\", \"r+\"]\nWriteAndTruncateMode = Literal[\"w\", \"w+\", \"wt\", \"w+t\"]\nWriteNoTruncateMode = Literal[\"r+\", \"r+t\"]\nAppendMode = Literal[\"a\", \"a+\", \"at\", \"a+t\"]\n\nAllModes = Literal[ReadOnlyMode, WriteAndTruncateMode, WriteNoTruncateMode, AppendMode]\n\ngood11: Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n\nvariable = 3\nT = TypeVar(\"T\")\n\n# > Arbitrary expressions [are illegal]\nbad1: Literal[3 + 4] # E\nbad2: Literal[\"foo\".replace(\"o\", \"b\")] # E\nbad3: Literal[4 + 3j] # E\nbad4: Literal[~5] # E\nbad5: Literal[not False] # E\nbad6: Literal[(1, \"foo\", \"bar\")] # E\nbad7: Literal[{\"a\": \"b\", \"c\": \"d\"}] # E\nbad8: Literal[int] # E\nbad9: Literal[variable] # E\nbad10: Literal[T] # E\nbad11: Literal[3.14] # E\nbad12: Literal[Any] # E\nbad13: Literal[...] # E\n\n\ndef my_function(x: Literal[1 + 2]) -> int: # E\n return x * 3\n\n\nx: Literal # E\ny: Literal[my_function] = my_function # E\n\n\ndef func2(a: Literal[Color.RED]):\n x1: Literal[\"Color.RED\"] = a # E\n\n x2: \"Literal[Color.RED]\" = a # OK\n","source":"typing_tests","origin":"conformance/tests/literals_parameterizations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_06.py","code":"\"\"\"\nTests the semantics of the Literal special form.\n\"\"\"\n\nfrom typing import Literal\nfrom typing import Literal as L\n\n\nv1: Literal[3] = 3\nv2: Literal[3] = 4 # E\n\nv3: L[-3] = -3\n\n\n# > Literal[20] and Literal[0x14] are equivalent\ndef func1(a: Literal[20], b: Literal[0x14], c: Literal[0b10100]):\n x1: Literal[0x14] = a\n x2: Literal[0x14] = b\n x3: Literal[0x14] = c\n\n\n# > Literal[0] and Literal[False] are not equivalent\ndef func2(a: Literal[0], b: Literal[False]):\n x1: Literal[False] = a # E\n x2: Literal[0] = b # E\n\n\n# > Given some value v that is a member of type T, the type Literal[v] shall\n# > be treated as a subtype of T. For example, Literal[3] is a subtype of int.\ndef func3(a: L[3, 4, 5]):\n b = a.__add__(3)\n c = a + 3\n a += 3 # E\n\n\n# > When a Literal is parameterized with more than one value, it’s treated\n# > as exactly equivalent to the union of those types.\ndef func4(a: L[None, 3] | L[3, \"foo\", b\"bar\", True]):\n x1: Literal[3, b\"bar\", True, \"foo\", None] = a\n a = x1\n","source":"typing_tests","origin":"conformance/tests/literals_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_01.py","code":"\"\"\"\nTests the handling of class objects as implementations of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#type-and-class-objects-vs-protocols\n\n# > Variables and parameters annotated with Type[Proto] accept only concrete\n# (non-protocol) subtypes of Proto.\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Protocol\n\n\nclass Proto(Protocol):\n @abstractmethod\n def meth(self) -> int:\n ...\n\n\nclass Concrete:\n def meth(self) -> int:\n return 42\n\n\ndef fun(cls: type[Proto]) -> int:\n return cls().meth() # OK\n\n\nfun(Proto) # E\nfun(Concrete) # OK\n\n\nvar: type[Proto]\nvar = Proto # E\nvar = Concrete # OK\nvar().meth() # OK\n\n\n# > A class object is considered an implementation of a protocol if accessing\n# > all members on it results in types compatible with the protocol members.\n\n\nclass ProtoA1(Protocol):\n def method1(self, x: int) -> int:\n ...\n\n\nclass ProtoA2(Protocol):\n def method1(_self, self: Any, x: int) -> int:\n ...\n\n\nclass ConcreteA:\n def method1(self, x: int) -> int:\n return 0\n\n\npa1: ProtoA1 = ConcreteA # E: signatures don't match\npa2: ProtoA2 = ConcreteA # OK\n\n\nclass ProtoB1(Protocol):\n @property\n def prop1(self) -> int:\n ...\n\n\nclass ConcreteB:\n @property\n def prop1(self) -> int:\n return 0\n\n\npb1: ProtoB1 = ConcreteB # E\n\n\nclass ProtoC1(Protocol):\n attr1: ClassVar[int]\n\n\nclass ProtoC2(Protocol):\n attr1: int\n\n\nclass ConcreteC1:\n attr1: ClassVar[int] = 1\n\n\nclass ConcreteC2:\n attr1: int = 1\n\n\nclass CMeta(type):\n attr1: int\n\n def __init__(self, *args, **kwargs) -> None:\n self.attr1: int = 1\n\n\nclass ConcreteC3(metaclass=CMeta):\n pass\n\n\npc1: ProtoC1 = ConcreteC1 # E\npc2: ProtoC2 = ConcreteC1 # OK\npc3: ProtoC1 = ConcreteC2 # E\npc4: ProtoC2 = ConcreteC2 # E\npc5: ProtoC1 = ConcreteC3 # E?: Explicit ClassVar matching is unspecified\npc6: ProtoC2 = ConcreteC3 # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_class_objects.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_02.py","code":"\"\"\"\nTests the basic definition rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#defining-a-protocol\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Iterable, NamedTuple, Protocol, Sequence\nfrom dataclasses import dataclass\n\n\nclass SupportsClose(Protocol):\n def close(self) -> None:\n ...\n\n\nclass Resource:\n def close(self) -> None:\n pass\n\n\ndef close_all(things: Iterable[SupportsClose]) -> None:\n for t in things:\n t.close()\n\n\nf = open(\"foo.txt\")\nr = Resource()\nclose_all([f, r]) # OK\nclose_all([1]) # E: 'int' has no 'close' method\n\n\nclass Example(Protocol):\n def first(self) -> int: # This is a protocol member\n return 42\n\n @abstractmethod\n def second(self) -> int: # Method without a default implementation\n raise NotImplementedError\n\n # > Static methods, class methods, and properties are equally allowed in protocols.\n\n @staticmethod\n def third() -> int:\n ...\n\n @classmethod\n def fourth(cls) -> int:\n ...\n\n @property\n def fifth(self) -> int:\n ...\n\n\n# > To define a protocol variable, one can use PEP 526 variable annotations\n# > in the class body. Additional attributes only defined in the body of a\n# > method by assignment via self are not allowed.\n\n\nclass Template(Protocol):\n name: str # This is a protocol member\n value: int = 0 # This one too (with default)\n\n def method(self) -> None:\n self.name = \"name\" # OK\n self.temp: list[int] = [] # E: use of self variables not allowed\n\n\nclass Concrete:\n def __init__(self, name: str, value: int) -> None:\n self.name = name\n self.value = value\n\n def method(self) -> None:\n return\n\n\nvar: Template = Concrete(\"value\", 42) # OK\n\n\n# > To distinguish between protocol class variables and protocol instance\n# > variables, the special ClassVar annotation should be used as specified\n# > by PEP 526. By default, protocol variables as defined above are considered\n# > readable and writable. To define a read-only protocol variable, one can\n# > use an (abstract) property.\n\n\nclass Template2(Protocol):\n val1: ClassVar[Sequence[int]]\n\n\nclass Concrete2_Good1:\n val1: ClassVar[Sequence[int]] = [2]\n\n\nclass Concrete2_Bad1:\n ...\n\n\nclass Concrete2_Bad2:\n val1: Sequence[float] = [2]\n\n\nclass Concrete2_Bad3:\n val1: list[int] = [2]\n\n\nclass Concrete2_Bad4:\n val1: Sequence[int] = [2]\n\n\nv2_good1: Template2 = Concrete2_Good1() # OK\nv2_bad1: Template2 = Concrete2_Bad1() # E\nv2_bad2: Template2 = Concrete2_Bad2() # E\nv2_bad3: Template2 = Concrete2_Bad3() # E\nv2_bad4: Template2 = Concrete2_Bad4() # E?: Explicit ClassVar matching is unspecified\n\n\nclass Template3(Protocol):\n val1: Sequence[int]\n\n\nclass Concrete3_Good1:\n val1: Sequence[int] = [0]\n\n\nclass Concrete3_Good2:\n def __init__(self) -> None:\n self.val1: Sequence[int] = [0]\n\n\nclass Concrete3_Bad1:\n ...\n\n\nclass Concrete3_Bad2:\n val1: ClassVar[Sequence[int]] = [0]\n\n\nclass Concrete3_Bad3:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete3_Bad4:\n val1: Sequence[float] = [0]\n\n\nclass Concrete3_Bad5:\n val1: list[int] = [0]\n\n\nv3_good1: Template3 = Concrete3_Good1() # OK\nv3_bad1: Template3 = Concrete3_Bad1() # E\nv3_bad2: Template3 = Concrete3_Bad2() # E\nv3_bad3: Template3 = Concrete3_Bad3() # E\nv3_bad4: Template3 = Concrete3_Bad4() # E\nv3_bad5: Template3 = Concrete3_Bad5() # E\n\n\nclass Template4(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n\nclass Concrete4_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete4_Good2:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete4_Good3:\n val1: Sequence[float] = [0]\n\n\nclass Concrete4_Good4:\n val1: Sequence[int] = [0]\n\n\nclass Concrete4_Good5:\n val1: list[float] = [0]\n\n\nclass Concrete4_Good6(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete4_Good7:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete4_Bad1:\n def val1(self) -> Sequence[int]: # Not a property\n return [0]\n\n\nclass Concrete4_Bad2:\n ...\n\n\nv4_good1: Template4 = Concrete4_Good1() # OK\nv4_good2: Template4 = Concrete4_Good2() # OK\nv4_good3: Template4 = Concrete4_Good3() # OK\nv4_good4: Template4 = Concrete4_Good4() # OK\nv4_good5: Template4 = Concrete4_Good5() # OK\nv4_good6: Template4 = Concrete4_Good6() # OK\nv4_good7: Template4 = Concrete4_Good7() # OK\nv4_bad1: Template4 = Concrete4_Bad1() # E\nv4_bad2: Template4 = Concrete4_Bad2() # E\n\n\nclass Template5(Protocol):\n def method1(self, a: int, b: int) -> float:\n ...\n\n\nclass Concrete5_Good1:\n def method1(self, a: float, b: float) -> int:\n return 0\n\n\nclass Concrete5_Good2:\n def method1(self, *args: float, **kwargs: float) -> Any:\n return 0.0\n\n\nclass Concrete5_Good3:\n def method1(self, a, b) -> Any:\n return 0.0\n\n\nclass Concrete5_Good4:\n @classmethod\n def method1(cls, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Good5:\n @staticmethod\n def method1(a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad1:\n def method1(self, a, c) -> int:\n return 0\n\n\nclass Concrete5_Bad2:\n def method1(self, a: int, c: int) -> int:\n return 0\n\n\nclass Concrete5_Bad3:\n def method1(self, *, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad4:\n def method1(self, a: int, b: int, /) -> float:\n return 0\n\n\nclass Concrete5_Bad5:\n @staticmethod\n def method1(self, a: int, b: int) -> float:\n return 0\n\n\nv5_good1: Template5 = Concrete5_Good1() # OK\nv5_good2: Template5 = Concrete5_Good2() # OK\nv5_good3: Template5 = Concrete5_Good3() # OK\nv5_good4: Template5 = Concrete5_Good4() # OK\nv5_good5: Template5 = Concrete5_Good5() # OK\nv5_bad1: Template5 = Concrete5_Bad1() # E\nv5_bad2: Template5 = Concrete5_Bad2() # E\nv5_bad3: Template5 = Concrete5_Bad3() # E\nv5_bad4: Template5 = Concrete5_Bad4() # E\nv5_bad5: Template5 = Concrete5_Bad5() # E\n\n\nclass Template6(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n ...\n\n\nclass Concrete6_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n pass\n\n\nclass Concrete6_Good2:\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete6_Good3:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete6_Bad1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete6_Bad2(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=True)\nclass Concrete6_Bad3:\n val1: Sequence[float] = (0,)\n\n\nv6_good1: Template6 = Concrete6_Good1() # OK\nv6_good2: Template6 = Concrete6_Good2() # OK\nv6_good3: Template6 = Concrete6_Good3() # OK\nv6_bad1: Template6 = Concrete6_Bad1() # E\nv6_bad2: Template6 = Concrete6_Bad2() # E: named tuple is immutable\nv6_bad3: Template6 = Concrete6_Bad3() # E: dataclass is frozen\n\n\n# The specification leaves two possible interpretations of a ClassVar protocol\n# member. One interpretation requires the implementing attribute to be explicitly\n# declared with ClassVar. The other interpretation imposes only structural\n# requirements: the attribute must be readable and writable on the class object\n# and readable on instances of the class. Both interpretations therefore require\n# the following assignments to be rejected.\n\n\nclass Template7(Protocol):\n val1: ClassVar[int]\n\n\nclass Concrete7_Bad1:\n def __init__(self) -> None:\n self.val1: int = 42\n\n\nclass Concrete7Meta(type):\n val1: int = 42\n\n\nclass Concrete7_Bad2(metaclass=Concrete7Meta):\n pass\n\n\nv7_bad1: Template7 = Concrete7_Bad1() # E: val1 is not readable on the class object\nv7_bad2: Template7 = Concrete7_Bad2() # E: val1 is not readable on instances\n","source":"typing_tests","origin":"conformance/tests/protocols_definition.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_03.py","code":"\"\"\"\nTests the handling of explicit protocol classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#explicitly-declaring-implementation\n\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar, Protocol\n\n\nclass PColor(Protocol):\n @abstractmethod\n def draw(self) -> str:\n ...\n\n def complex_method(self) -> int:\n return 1\n\n\nclass NiceColor(PColor):\n def draw(self) -> str:\n return \"deep blue\"\n\n\nclass BadColor(PColor):\n def draw(self) -> str:\n return super().draw() # E: no default implementation\n\n\nclass ImplicitColor: # Note no 'PColor' base here\n def draw(self) -> str:\n return \"probably gray\"\n\n def complex_method(self) -> int:\n return 0\n\n\nv1: PColor = NiceColor() # OK\nv2: PColor = ImplicitColor() # OK\n\n\nclass RGB(Protocol):\n rgb: tuple[int, int, int]\n other: int\n\n @abstractmethod\n def intensity(self) -> int:\n return 1\n\n def transparency(self) -> int:\n ...\n\n\nclass Point(RGB):\n def __init__(self, red: int, green: int, blue: str) -> None:\n self.rgb = red, green, blue # E: 'blue' must be 'int'\n self.other = 0\n\n\np = Point(0, 0, \"\") # E: Cannot instantiate abstract class\n\n\nclass Proto1(Protocol):\n cm1: ClassVar[int]\n cm2: ClassVar[int] = 0\n\n im1: int\n im2: int = 2\n im3: int\n\n def __init__(self):\n self.im3 = 3\n\n\nclass Proto2(Protocol):\n cm10: int\n\n\nclass Proto3(Proto2, Protocol):\n cm11: int\n\n\nclass Concrete1(Proto1):\n def __init__(self):\n self.im1 = 1\n self.im3 = 3\n\n\nc1 = Concrete1() # E: cannot instantiate abstract class\n\n\nclass Concrete2(Proto1):\n cm1 = 3\n im1 = 0\n\n\nc2 = Concrete2()\n\n\nclass Concrete3(Proto1, Proto3):\n cm1 = 3\n\n def __init__(self):\n self.im1 = 0\n self.cm10 = 10\n self.cm11 = 11\n\n\nc3 = Concrete3()\n\n\nclass Concrete4(Proto1, Proto3):\n cm1 = 3\n cm10 = 3\n\n def __init__(self):\n self.im1 = 3\n self.im10 = 10\n self.cm11 = 3\n\n\nc4 = Concrete4()\n\n\nclass Proto5(Protocol):\n def method1(self) -> int:\n ...\n\n\nclass Concrete5(Proto5):\n pass\n\n\nc5 = Concrete5() # E: cannot instantiate abstract class\n\n\nclass Proto6(Protocol):\n x: int\n\n\nclass Mixin:\n x = 3\n\n\nclass Concrete6(Mixin, Proto6):\n pass\n\n\nclass Proto7(Protocol):\n @abstractmethod\n def method1(self):\n ...\n\n\nclass Mixin7(Proto7, ABC):\n def method1(self) -> None:\n pass\n\n\nclass Concrete7A(Proto7):\n pass\n\n\nc7a = Concrete7A() # E: cannot instantiate abstract class\n\n\nclass Concrete7B(Mixin7, Proto7):\n pass\n\n\nc7b = Concrete7B()\n","source":"typing_tests","origin":"conformance/tests/protocols_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_04.py","code":"\"\"\"\nTests the handling of generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\n\nfrom typing import Callable, Generic, Iterator, Protocol, Self, TypeVar, assert_type\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Iterable(Protocol[T_co]):\n def __iter__(self) -> Iterator[T_co]:\n ...\n\n\n# > Protocol[T, S, ...] is allowed as a shorthand for Protocol, Generic[T, S, ...].\n# In particular, the implicit order of type parameters is dictated by\n# the order in which they appear in the `Protocol` subscript.\n\n\nclass Proto1(Iterable[T_co], Protocol[S, T_co]):\n def method1(self, x: S) -> S:\n ...\n\n\nclass Concrete1:\n def __iter__(self) -> Iterator[int]:\n return (x for x in [1, 2, 3])\n\n def method1(self, x: str) -> str:\n return \"\"\n\n\np1: Proto1[str, int] = Concrete1() # OK\np2: Proto1[int, str] = Concrete1() # E: incompatible type\n\n\n# > It is an error to combine the shorthand with Generic[T, S, ...]\nclass Proto2(Protocol[T_co], Generic[T_co]): # E\n ...\n\n\n# > User-defined generic protocols support explicitly declared variance.\nclass Box(Protocol[T_co]):\n def content(self) -> T_co:\n ...\n\n\ndef func1(box_int: Box[int], box_float: Box[float]):\n v1: Box[float] = box_int # OK\n v2: Box[int] = box_float # E\n\n\nclass Sender(Protocol[T_contra]):\n def send(self, data: T_contra) -> int:\n return 0\n\n\ndef func2(sender_int: Sender[int], sender_float: Sender[float]):\n v1: Sender[int] = sender_float # OK\n v2: Sender[float] = sender_int # E\n\n\nclass AttrProto(Protocol[T]):\n attr: T\n\n\ndef func3(attr_int: AttrProto[int], attr_float: AttrProto[float]):\n v1: AttrProto[float] = attr_int # E\n v2: AttrProto[int] = attr_float # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n# > The self-types in protocols follow the rules for other methods.\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n# > In addition, the first argument in an instance method can be annotated\n# > with a type variable. In this case the return type may use the same\n# > type variable, thus making that method a generic function.\n\n\nT_bounded = TypeVar(\"T_bounded\", bound=\"HasParent\")\n\n\nclass HasParent(Protocol):\n def get_parent(self: T_bounded) -> T_bounded:\n ...\n\n\nGenericHasParent = TypeVar(\"GenericHasParent\", bound=HasParent)\n\n\ndef generic_get_parent(n: GenericHasParent) -> GenericHasParent:\n return n.get_parent()\n\n\nclass ConcreteHasParent:\n def get_parent(self) -> Self:\n return self\n\n\nparent = generic_get_parent(ConcreteHasParent()) # OK\nassert_type(parent, ConcreteHasParent)\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > `Self` is valid within Protocols, similar to its use in classes:\n\n\nclass HasParentProperty(Protocol):\n @property\n def parent(self) -> Self:\n ...\n\n\nclass ConcreteParentProperty:\n @property\n def parent(self) -> Self:\n return self\n\n\nclass InvalidParentProperty:\n @property\n def parent(self) -> HasParentProperty:\n return ConcreteParentProperty()\n\n\nhp1: HasParentProperty = ConcreteParentProperty() # OK\nhp2: HasParentProperty = InvalidParentProperty() # E\n\n\n\nclass HasMethod(Protocol):\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n ...\n\n\nclass ConcreteHasMethod:\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n return \"\"\n\n\nclass InvalidHasMethod:\n def m(self, item: int, callback: Callable[[int], str]) -> str:\n return \"\"\n\n\nhm1: HasMethod = ConcreteHasMethod() # OK\nhm2: HasMethod = InvalidHasMethod() # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > Checking a class for assignability to a protocol: If a protocol uses `Self`\n# > in methods or attribute annotations, then a class `Foo` is assignable\n# > to the protocol if its corresponding methods and attribute annotations use\n# > either `Self` or `Foo` or any of `Foo`'s subclasses.\n\n\nclass HasGreaterThan(Protocol):\n def __gt__(self, other: Self) -> bool:\n ...\n\n\nclass ConcreteGreaterThan1:\n def __gt__(self, other: Self) -> bool:\n return False\n\n\nclass ConcreteGreaterThan2:\n def __gt__(self, other: \"ConcreteGreaterThan2\") -> bool:\n return False\n\n\nclass InvalidGreaterThan:\n def __gt__(self, other: int) -> bool:\n return False\n\n\nhg1: HasGreaterThan = ConcreteGreaterThan1() # OK\nhg2: HasGreaterThan = ConcreteGreaterThan2() # OK\nhg3: HasGreaterThan = InvalidGreaterThan() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_generic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_05.py","code":"\"\"\"\nTests merging and extending of protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#merging-and-extending-protocols\n\nfrom abc import abstractmethod\nfrom typing import Protocol\nfrom collections.abc import Sized\n\n\nclass SizedAndClosable1(Sized, Protocol):\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable2(Protocol):\n def __len__(self) -> int:\n ...\n\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable3(SizedAndClosable1): # Note: not a protocol\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete1:\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete2:\n def close(self) -> None:\n pass\n\n\ns1: SizedAndClosable1 = SCConcrete1() # OK\ns2: SizedAndClosable2 = SCConcrete1() # OK\ns3: SizedAndClosable1 = SizedAndClosable3() # OK\ns4: SizedAndClosable2 = SizedAndClosable3() # OK\ns5: Sized = SCConcrete1() # OK\n\ns6: SizedAndClosable1 = SCConcrete2() # E: doesn't implement `__len__`\ns7: SizedAndClosable2 = SCConcrete2() # E: doesn't implement `__len__`\ns8: SizedAndClosable3 = SCConcrete2() # E: SizedAndClosable3 is not a protocol\n\n\ndef func1(s1: SizedAndClosable1, s2: SizedAndClosable2):\n # > The two definitions of SizedAndClosable are equivalent.\n v1: SizedAndClosable2 = s1\n v2: SizedAndClosable1 = s2\n\n\n# > If Protocol is included in the base class list, all the other base classes\n# > must be protocols.\n\n\nclass BadProto(SizedAndClosable3, Protocol): # E: SizedAndClosable3 is not a protocol\n ...\n\n\n# > Without this base, the class is “downgraded” to a regular ABC that\n# > cannot be used with structural subtyping.\nclass SizedAndClosable4(SizedAndClosable1):\n def __len__(self) -> int:\n return 0\n\n @abstractmethod\n def close(self) -> None:\n raise NotImplementedError\n\n\nx = SizedAndClosable4() # E: cannot instantiate abstract class\ny: SizedAndClosable4 = SCConcrete1() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_merging.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_06.py","code":"\"\"\"\nTests the handling of modules as the implementation of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#modules-as-implementations-of-protocols\n\n# > A module object is accepted where a protocol is expected if the public\n# > interface of the given module is compatible with the expected protocol.\n\nimport _protocols_modules1\nimport _protocols_modules2\nfrom typing import Protocol\n\n\nclass Options1(Protocol):\n timeout: int\n one_flag: bool\n other_flag: bool\n\n\nclass Options2(Protocol):\n timeout: str\n\n\nop1: Options1 = _protocols_modules1 # OK\nop2: Options2 = _protocols_modules1 # E\n\n\nclass Reporter1(Protocol):\n def on_error(self, x: int) -> None:\n ...\n\n def on_success(self) -> None:\n ...\n\n\nclass Reporter2(Protocol):\n def on_error(self, x: int) -> int:\n ...\n\n\nclass Reporter3(Protocol):\n def not_implemented(self, x: int) -> int:\n ...\n\n\nrp1: Reporter1 = _protocols_modules2 # OK\nrp2: Reporter2 = _protocols_modules2 # E\nrp3: Reporter3 = _protocols_modules2 # E\n","source":"typing_tests","origin":"conformance/tests/protocols_modules.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_07.py","code":"\"\"\"\nTests the handling of recursive protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#recursive-protocols\n\n\nfrom typing import Generic, Iterable, Never, Protocol, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Traversable(Protocol):\n def leaves(self) -> Iterable[\"Traversable\"]:\n ...\n\n\nclass SimpleTree:\n def leaves(self) -> list[\"SimpleTree\"]:\n return []\n\n\nroot: Traversable = SimpleTree() # OK\n\n\nclass Tree(Generic[T]):\n def leaves(self) -> list[\"Tree[T]\"]:\n return []\n\n\ndef walk(graph: Traversable) -> None:\n pass\n\n\ntree: Tree[float] = Tree()\nwalk(tree) # OK\n\n\nclass ProtoA(Protocol[T_co, T_contra]):\n def method1(self) -> \"ProtoA[T_co, T_contra]\":\n ...\n\n @classmethod\n def method2(cls, value: T_contra) -> None:\n ...\n\n\nclass ProtoB(Protocol[T_co, T_contra]):\n def method3(self) -> ProtoA[T_co, T_contra]:\n ...\n\n\nclass ImplA:\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls, value: int) -> None:\n pass\n\n\nclass ImplB:\n def method3(self) -> ImplA:\n return ImplA()\n\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls: type[ProtoB[object, T]], value: list[T]) -> None:\n pass\n\n\ndef func1(x: ProtoA[Never, T]) -> T:\n raise NotImplementedError\n\n\nv1 = func1(ImplB())\nassert_type(v1, list[int])\n","source":"typing_tests","origin":"conformance/tests/protocols_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_08.py","code":"\"\"\"\nTests the handling of the @runtime_checkable decorator for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#runtime-checkable-decorator-and-narrowing-types-by-isinstance\n\n# > A protocol can be used as a second argument in isinstance() and\n# > issubclass() only if it is explicitly opt-in by @runtime_checkable decorator.\n\nfrom typing import Any, Protocol, runtime_checkable\n\n\nclass Proto1(Protocol):\n name: str\n\n\n@runtime_checkable\nclass Proto2(Protocol):\n name: str\n\n\ndef func1(a: Any):\n if isinstance(a, Proto1): # E: not runtime_checkable\n return\n\n if isinstance(a, Proto2): # OK\n return\n\n\n# > isinstance() can be used with both data and non-data protocols, while\n# > issubclass() can be used only with non-data protocols.\n\n\n@runtime_checkable\nclass DataProtocol(Protocol):\n name: str\n\n def method1(self) -> int:\n ...\n\n\n@runtime_checkable\nclass NonDataProtocol(Protocol):\n def method1(self) -> int:\n ...\n\n\ndef func2(a: Any):\n if isinstance(a, DataProtocol): # OK\n return\n\n if isinstance(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, DataProtocol): # E\n return\n\n if issubclass(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, (NonDataProtocol, DataProtocol)): # E\n return\n\n\n# > Type checkers should reject an isinstance() or issubclass() call if there\n# > is an unsafe overlap between the type of the first argument and the protocol.\n\n\n@runtime_checkable\nclass Proto3(Protocol):\n def method1(self, a: int) -> int:\n ...\n\n\nclass Concrete3A:\n def method1(self, a: str) -> None:\n pass\n\n\nclass Concrete3B:\n method1: int = 1\n\n\ndef func3():\n if isinstance(Concrete3A(), Proto2): # OK\n pass\n\n if isinstance(Concrete3A(), Proto3): # E: unsafe overlap\n pass\n\n if isinstance(Concrete3B(), (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n\n if issubclass(Concrete3A, (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n","source":"typing_tests","origin":"conformance/tests/protocols_runtime_checkable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_09.py","code":"\"\"\"\nTests the handling of annotated \"self\" parameters in a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n\nfrom typing import Generic, Protocol, Self, TypeVar\n\n\nC = TypeVar(\"C\", bound=\"Copyable\")\n\n\nclass Copyable(Protocol):\n def copy(self: C) -> C:\n return self\n\n\nclass One:\n def copy(self) -> \"One\":\n return One()\n\n\nT = TypeVar(\"T\", bound=\"Other\")\n\n\nclass Other:\n def copy(self: T) -> T:\n return self\n\n\nc: Copyable\nc = One() # OK\nc = Other() # OK\n\n\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT2_co = TypeVar(\"T2_co\", covariant=True)\n\n\nclass P1Parent(Protocol[T2_co]):\n def f0(self, /) -> Self:\n ...\n\n\nclass P1Child(P1Parent[T2_co], Protocol[T2_co]):\n ...\n\n\nclass C1(Generic[T1_co]):\n def f0(self, /) -> Self:\n return self\n\n\na1: P1Parent[str] = C1[str]()\nb1: P1Child[str] = C1[str]()\n\n\nclass P2Parent(Protocol[T1_co]):\n def f0(self, right: Self, /) -> \"P2Parent[T1_co]\":\n return right\n\n\nclass P2Child(P2Parent[T1_co], Protocol[T1_co]):\n ...\n\n\nclass C2(Generic[T2_co]):\n def f0(self, other: Self) -> \"C2[T2_co]\":\n return other\n\n\na2: P2Parent[str] = C2[str]() # OK\nb2: P2Child[str] = C2[str]() # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_self.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_10.py","code":"\"\"\"\nTests subtyping rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#subtyping-relationships-with-other-types\n\n# > Protocols cannot be instantiated.\n\nfrom typing import Hashable, Iterable, Protocol, Sequence, TypeVar\n\n\nclass Proto1(Protocol):\n pass\n\n\np1 = Proto1() # E: protocol cannot be instantiated\n\n\n# > A protocol is never a subtype of a concrete type.\n\n# > A concrete type X is a subtype of protocol P if and only if X implements\n# > all protocol members of P with compatible types. In other words, subtyping\n# > with respect to a protocol is always structural.\n\n\nclass Proto2(Protocol):\n def method1(self) -> None:\n ...\n\n\nclass Concrete2:\n def method1(self) -> None:\n pass\n\n\ndef func1(p2: Proto2, c2: Concrete2):\n v1: Proto2 = c2 # OK\n v2: Concrete2 = p2 # E\n\n\n# > A protocol P1 is a subtype of another protocol P2 if P1 defines all\n# > protocol members of P2 with compatible types.\n\n\nclass Proto3(Protocol):\n def method1(self) -> None:\n ...\n\n def method2(self) -> None:\n ...\n\n\ndef func2(p2: Proto2, p3: Proto3):\n v1: Proto2 = p3 # OK\n v2: Proto3 = p2 # E\n\n\n# > Generic protocols follow the rules for generic abstract classes, except\n# > for using structural compatibility instead of compatibility defined by\n# > inheritance relationships.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n\nclass Proto4(Protocol[S, T]):\n def method1(self, a: S, b: T) -> tuple[S, T]:\n ...\n\n\nclass Proto5(Protocol[T]):\n def method1(self, a: T, b: T) -> tuple[T, T]:\n ...\n\n\ndef func3(p4_int: Proto4[int, int], p5_int: Proto5[int]):\n v1: Proto4[int, int] = p5_int # OK\n v2: Proto5[int] = p4_int # OK\n v3: Proto4[int, float] = p5_int # E\n v4: Proto5[float] = p4_int # E\n\n\nS_co = TypeVar(\"S_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Proto6(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\nclass Proto7(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\ndef func4(p6: Proto6[float, float]):\n v1: Proto7[object, int] = p6 # OK\n v2: Proto7[float, float] = p6 # OK\n v3: Proto7[complex, int] = p6 # OK\n\n v4: Proto7[int, float] = p6 # E\n v5: Proto7[float, object] = p6 # E\n\n\n# > Unions of protocol classes behaves the same way as for non-protocol classes.\n\n\nclass SupportsExit(Protocol):\n def exit(self) -> int:\n ...\n\n\nclass SupportsQuit(Protocol):\n def quit(self) -> int | None:\n ...\n\n\ndef finish(task: SupportsExit | SupportsQuit) -> int:\n return 0\n\n\nclass DefaultJob:\n def quit(self) -> int:\n return 0\n\n\nfinish(DefaultJob()) # OK\n\n\n# > One can use multiple inheritance to define an intersection of protocols.\n\n\nclass HashableFloats(Iterable[float], Hashable, Protocol):\n pass\n\n\ndef cached_func(args: HashableFloats) -> float:\n return 0.0\n\n\ncached_func((1, 2, 3)) # OK, tuple is both hashable and iterable\n","source":"typing_tests","origin":"conformance/tests/protocols_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_11.py","code":"\"\"\"\nTests type variable variance inference for generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\nfrom typing import Protocol, TypeVar\nfrom typing_extensions import ParamSpec\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", bound=int)\nT3 = TypeVar(\"T3\", bytes, str)\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT1_contra = TypeVar(\"T1_contra\", contravariant=True)\nP = ParamSpec(\"P\", contravariant=True)\nR = TypeVar(\"R\", covariant=True)\n\n# > Type checkers will warn if the inferred variance is different from the\n# > declared variance.\n\n\nclass AnotherBox(Protocol[T1]): # E: T should be covariant\n def content(self) -> T1:\n ...\n\n\nclass Protocol1(Protocol[T1, T2, T3]): # OK\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1 | T2:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n def m4(self) -> T3:\n ...\n\n\nclass Protocol2(Protocol[T1, T2, T3]): # E: T3 should be contravariant\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n\nclass Protocol3(Protocol[T1_co]):\n def m1(self) -> None:\n pass\n\n\nclass Protocol4(Protocol[T1]): # E: T1 should be contravariant\n def m1(self, p0: T1) -> None:\n ...\n\n\nclass Protocol5(Protocol[T1_co]): # E[covariant_in_input+]\n def m1(self, p0: T1_co) -> None: # E[covariant_in_input+]\n ...\n\n\nclass Protocol6(Protocol[T1]): # E: T1 should be covariant\n def m1(self) -> T1:\n ...\n\n\nclass Protocol7(Protocol[T1_contra]): # E[contravariant_in_output+]\n def m1(self) -> T1_contra: # E[contravariant_in_output+]\n ...\n\n\nclass Protocol8(Protocol[T1]): # OK\n def m1(self) -> T1:\n ...\n\n def m2(self, p1: T1) -> None:\n pass\n\n\nclass Callback(Protocol[P, R]): # OK\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\nclass Protocol9(Protocol[T1_co]): # OK\n @property\n def prop1(self) -> T1_co:\n ...\n\n\nclass Protocol10(Protocol[T1_co]): # OK\n def m1(self) -> type[T1_co]:\n ...\n\n\nclass Protocol11(Protocol[T1]): # OK\n x: T1 | None\n\n\nclass Protocol12(Protocol[T1]): # E: T1 should be covariant\n # __init__ method is exempt from variance calculations.\n def __init__(self, x: T1) -> None:\n ...\n\n\nclass Protocol13(Protocol[T1_contra]): # OK\n def m1(self: \"Protocol13[T1_contra]\", x: T1_contra) -> None:\n ...\n\n @classmethod\n def m2(cls: \"type[Protocol13[T1_contra]]\") -> None:\n ...\n\n\nclass Protocol14(Protocol[T1]): # OK\n def m1(self) -> list[T1]:\n ...\n","source":"typing_tests","origin":"conformance/tests/protocols_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_13.py","code":"\"\"\"\nTests the \"alternative\" (non-class) syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#alternative-syntax\n\nfrom typing import TypedDict\n\n\nMovie = TypedDict(\"Movie\", {\"name\": str, \"year\": int, \"illegal key name\": bool})\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982, \"illegal key name\": True}\n\nMovieOptional = TypedDict(\"MovieOptional\", {\"name\": str, \"year\": int}, total=False)\n\nmovie_opt1: MovieOptional = {}\nmovie_opt2: MovieOptional = {\"year\": 1982}\n\n# > A type checker is only expected to accept a dictionary display expression as\n# > the second argument to TypedDict. In particular, a variable that refers to a\n# > dictionary object does not need to be supported, to simplify implementation.\nmy_dict = {\"name\": str}\nBadTypedDict1 = TypedDict(\"BadTypedDict1\", my_dict) # E\n\n\n# This should generate an error because it uses a non-str key.\nBadTypedDict2 = TypedDict(\"BadTypedDict2\", {1: str}) # E\n\n\n# This should generate an error because it uses a non-matching name.\nBadTypedDict3 = TypedDict(\"WrongName\", {\"name\": str}) # E\n\n\n# This should generate an error because of the additional parameter.\nBadTypedDict4 = TypedDict(\"BadTypedDict4\", {\"name\": str}, total=False, other=False) # E\n\n\n# > The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13.\n# > It may also be unsupported by static type checkers.\n\nMovie2 = TypedDict(\"Movie2\", name=str, year=int) # E?\n\nmovie2: Movie2\nmovie2 = {\"name\": \"Blade Runner\", \"year\": 1982} # E?: May generate errors if keyword-argument syntax is unsupported\nmovie2 = {\"name\": \"Blade Runner\", \"year\": \"\"} # E?: Incorrect type for year\n","source":"typing_tests","origin":"conformance/tests/typeddicts_alt_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_14.py","code":"\"\"\"\nTests the class syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import Generic, TypeVar, TypedDict\nimport sys\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n # > String literal forward references are valid in the value types.\n director: \"Person\"\n\n\nclass Person(TypedDict):\n name: str\n age: int\n\n\n# > Methods are not allowed, since the runtime type of a TypedDict object\n# > will always be just dict (it is never a subclass of dict).\nclass BadTypedDict1(TypedDict):\n name: str\n\n # Methods are not allowed, so this should generate an error.\n def method1(self): # E\n pass\n\n # Methods are not allowed, so this should generate an error.\n @classmethod # E[method2]\n def method2(cls): # E[method2]\n pass\n\n # Methods are not allowed, so this should generate an error.\n @staticmethod # E[method3]\n def method3(): # E[method3]\n pass\n\n\nclass CustomMeta(type):\n pass\n\n\n# > Specifying a custom metaclass is not allowed.\nclass BadTypedDict2(TypedDict, metaclass=CustomMeta): # E\n name: str\n\n\n# This should generate an error because \"other\" is not an allowed keyword argument.\nclass BadTypedDict3(TypedDict, other=True): # E\n name: str\n\n# > `if` conditions that the type checker is able to\n# > statically evaluate are also permitted (e.g. `if sys.version_info > (3, 14)`),\n# > in order to specify items that exist only under the given conditions.\nclass ConditionalField(TypedDict):\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nConditionalField(x=1, y=2)\nConditionalField(x=1, y=2, z=3) # E\n\n\n# > TypedDicts may be made generic by adding Generic[T] among the bases.\nT = TypeVar(\"T\")\n\n\nclass GenericTypedDict(TypedDict, Generic[T]):\n name: str\n value: T\n\n\n# > An empty TypedDict can be created by only including pass in the\n# > body (if there is a docstring, pass can be omitted):\nclass EmptyDict1(TypedDict):\n pass\n\n\nclass EmptyDict2(TypedDict):\n \"\"\"Docstring\"\"\"\n\n\nclass MovieTotal(TypedDict, total=True):\n name: str\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n","source":"typing_tests","origin":"conformance/tests/typeddicts_class_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_15.py","code":"\"\"\"\nTests inheritance rules for TypedDict classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclass BookBasedMovie(Movie):\n based_on: str\n\nclass BookBasedMovieAlso(TypedDict):\n name: str\n year: int\n based_on: str\n\nb1: BookBasedMovie = {\"name\": \"Little Women\", \"year\": 2019, \"based_on\": \"Little Women\"}\n\nb2: BookBasedMovieAlso = b1\n\n\nclass X(TypedDict):\n x: int\n\nclass Y(TypedDict):\n y: str\n\nclass XYZ(X, Y):\n z: bool\n\nx1 = XYZ(x=1, y=\"\", z=True)\n\n# > A TypedDict cannot inherit from both a TypedDict type and a\n# > non-TypedDict base class other than Generic.\n\nclass NonTypedDict:\n pass\n\nclass BadTypedDict(TypedDict, NonTypedDict): # E\n pass\n\n\n# > Changing a field type of a parent TypedDict class in a subclass is\n# > not allowed.\n\nclass X1(TypedDict):\n x: str\n\nclass Y1(X1): # E[Y1]\n x: int # E[Y1]: cannot overwrite TypedDict field \"x\"\n\n\n# > Multiple inheritance does not allow conflict types for the same name field:\nclass X2(TypedDict):\n x: int\n\nclass Y2(TypedDict):\n x: str\n\nclass XYZ2(X2, Y2): # E: cannot overwrite TypedDict field \"x\" while merging\n xyz: bool\n","source":"typing_tests","origin":"conformance/tests/typeddicts_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_16.py","code":"\"\"\"\nTests operations provided by a TypedDict object.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#supported-and-unsupported-operations\n\n\nfrom typing import TypedDict, assert_type\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie\n\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982}\nmovie[\"name\"] = \"Other\"\nmovie[\"year\"] = 1981\n\nmovie[\"name\"] = 1982 # E: wrong type\nmovie[\"year\"] = \"\" # E: wrong type\nmovie[\"other\"] = \"\" # E: unknown key added\n\nprint(movie[\"other\"]) # E: unknown key referenced\n\nmovie = {\"name\": \"Blade Runner\"} # E: year is missing\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982.1} # E: year is wrong type\n\n# > The use of a key that is not known to exist should be reported as an error.\nmovie = {\"name\": \"\", \"year\": 1900, \"other\": 2} # E: extra key\n\n\ndef func1(variable_key: str):\n # > A key that is not a literal should generally be rejected.\n movie: Movie = {variable_key: \"\", \"year\": 1900} # E: variable key\n\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"name\")\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"other\") # E?\n\n\nmovie.clear() # E: clear not allowed\n\ndel movie[\"name\"] # E: del not allowed for required key\n\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n year: int\n\n\nmovie_optional: MovieOptional = {}\n\nassert_type(movie_optional.get(\"name\"), str | None)\n\nmovie_optional.clear() # E: clear not allowed\n\ndel movie_optional[\"name\"]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_operations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_17.py","code":"\"\"\"\nTests the type consistency rules for TypedDict objects.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#type-consistency\n\nfrom typing import Any, Literal, Mapping, TypedDict\n\n\nclass A1(TypedDict):\n x: int | None\n\n\nclass B1(TypedDict):\n x: int\n\n\nb1: B1 = {\"x\": 0}\n\n# > Value types behave invariantly.\na1: A1 = b1 # E: 'B1' not compatible with 'A1'\n\n# > any TypedDict type is consistent with Mapping[str, object]\nv1: Mapping[str, object] = b1\n\n# > A TypedDict type with a required key is not consistent with a TypedDict\n# > type where the same key is a non-required key.\n\nclass A2(TypedDict, total=False):\n x: int\n\n\nclass B2(TypedDict):\n x: int\n\n\nb2: B2 = {\"x\": 0}\na2: A2 = b2 # E: 'B2' not compatible with 'A2'\n\n\n# > A TypedDict type A is consistent with TypedDict B if A is structurally\n# > compatible with B. This is true if and only if both of these conditions\n# > are satisfied:\n# > 1. For each key in B, A has the corresponding key and the corresponding\n# > value type in A is consistent with the value type in B. For each key in B,\n# > the value type in B is also consistent with the corresponding value type\n# > in A.\n# > 2. For each required key in B, the corresponding key is required in A. For\n# > each non-required key in B, the corresponding key is not required in A.\n\n\nclass A3(TypedDict):\n x: int\n\n\nclass B3(TypedDict):\n x: int\n y: int\n\n\nb3: B3 = {\"x\": 0, \"y\": 0}\na3: A3 = b3\n\na3 = {\"x\": 0}\nb3 = a3 # E\n\n\n# This should generate an error because it's a literal assignment.\na3_1: A3 = {\"x\": 0, \"y\": 0} # E\n\n# This should not generate an error.\na3_2 = b3\n\n# > A TypedDict isn’t consistent with any Dict[...] type.\n\nd1: dict[str, int] = b3 # E\nd2: dict[str, object] = b3 # E\nd3: dict[Any, Any] = b3 # E\n\n# > A TypedDict with all int values is not consistent with Mapping[str, int].\n\nm1: Mapping[str, int] = b3 # E\nm2: Mapping[str, object] = b3 # OK\nm3: Mapping[str, Any] = b3 # OK\n\n\n# Test \"get\" method.\nUserType1 = TypedDict(\"UserType1\", {\"name\": str, \"age\": int}, total=False)\nuser1: UserType1 = {\"name\": \"Bob\", \"age\": 40}\n\nname1: str = user1.get(\"name\", \"n/a\")\nage1: int = user1.get(\"age\", 42)\n\nUserType2 = TypedDict(\"UserType2\", {\"name\": str, \"age\": int})\nuser2: UserType2 = {\"name\": \"Bob\", \"age\": 40}\n\nname2: str | None = user2.get(\"name\")\n\n# The spec does not say whether type checkers should adjust the return type of `.get()`\n# to exclude `None` if it is known that the key exists. Either option is acceptable.\nname3: str = user2.get(\"name\") # E?\n\nage2: int = user2.get(\"age\", 42)\n\nage3: int | str = user2.get(\"age\", \"42\")\n\nage4: int = user2.get(\"age\", \"42\") # E?\n\n# Test nested TypedDicts.\nclass Inner1(TypedDict):\n inner_key: str\n\n\nclass Inner2(TypedDict):\n inner_key: Inner1\n\n\nclass Outer1(TypedDict):\n outer_key: Inner2\n\n\no1: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": \"hi\"}}}\n\n# This should generate an error because the inner-most value\n# should be a string.\no2: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": 1}}} # E\n\n\nclass Inner3(TypedDict):\n x: int\n\n\nclass Inner4(TypedDict):\n x: int\n\n\nclass Outer2(TypedDict):\n y: str\n z: Literal[\"\"] | Inner3\n\n\nclass Outer3(TypedDict):\n y: str\n z: Literal[\"\"] | Inner4\n\n\ndef func1(td: Outer3):\n ...\n\n\no3: Outer2 = {\"y\": \"\", \"z\": {\"x\": 0}}\no4: Outer3 = o3\n","source":"typing_tests","origin":"conformance/tests/typeddicts_type_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_18.py","code":"\"\"\"\nTests for basic usage of TypedDict.\n\"\"\"\n\nfrom typing import TypeVar, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982}\n\n\ndef record_movie(movie: Movie) -> None:\n ...\n\n\nrecord_movie({\"name\": \"Blade Runner\", \"year\": 1982})\n\n\nmovie[\"director\"] = \"Ridley Scott\" # E: invalid key 'director'\nmovie[\"year\"] = \"1982\" # E: invalid value type (\"int\" expected)\n\n# The code below should be rejected, since 'title' is not a valid key,\n# and the 'name' key is missing:\nmovie2: Movie = {\"title\": \"Blade Runner\", \"year\": 1982} # E\n\nm = Movie(name='Blade Runner', year=1982)\n\n\n# > TypedDict type objects cannot be used in isinstance() tests such as\n# > isinstance(d, Movie).\nif isinstance(movie, Movie): # E\n pass\n\n\n# TypedDict should not be allowed as a bound for a TypeVar.\nT = TypeVar(\"T\", bound=TypedDict) # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport types\nimport unittest\nfrom test.support import import_module\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport types\nimport unittest\nfrom test.support import import_module\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n an = g.__anext__()\n try:\n while True:\n try:\n an.__next__()\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n break\n else:\n res.append('EMPTY StopIteration')\n break\n except StopAsyncIteration:\n raise\n except Exception as ex:\n res.append(str(type(ex)))\n break\n except StopAsyncIteration:\n res.append('STOP')\n break\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_exception_11(self):\n def sync_gen():\n yield 10\n yield 20\n\n def sync_gen_wrapper():\n yield 1\n sg = sync_gen()\n sg.send(None)\n try:\n sg.throw(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n async def async_gen():\n yield 10\n yield 20\n\n async def async_gen_wrapper():\n yield 1\n asg = async_gen()\n await asg.asend(None)\n try:\n await asg.athrow(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n\n self.assertTrue(inspect.isawaitable(g.aclose()))\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport types\nimport unittest\nfrom test.support import import_module\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n asyncio.set_event_loop_policy(None)\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n await asyncio.sleep(0.01)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n\n await asyncio.sleep(0.1)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_aclose_12(self):\n DONE = 0\n\n async def target():\n await asyncio.sleep(0.01)\n 1 / 0\n\n async def foo():\n nonlocal DONE\n task = asyncio.create_task(target())\n try:\n yield 1\n finally:\n try:\n await task\n except ZeroDivisionError:\n DONE = 1\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout)\n yield 1\n finally:\n await asyncio.sleep(0)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1))\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t1)\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t2)\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(finalized, 2)\n\n def test_async_gen_expression_01(self):\n async def arange(n):\n for i in range(n):\n await asyncio.sleep(0.01)\n yield i\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 async for i in arange(n))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(10)])\n\n def test_async_gen_expression_02(self):\n async def wrap(n):\n await asyncio.sleep(0.01)\n return n\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 for i in range(n) if await wrap(i))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(1, 10)])\n\n def test_asyncgen_nonstarted_hooks_are_cancellable(self):\n # See https://bugs.python.org/issue38013\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n\n asyncio.run(main())\n\n self.assertEqual([], messages)\n\n def test_async_gen_await_same_anext_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.__anext__()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"\n ):\n await nxt\n\n await it.aclose() # prevent unfinished iterator warning\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_await_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.aclose()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n await nxt\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_twice_with_different_coros(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n await it.aclose()\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_after_exhaustion(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n async for _ in it:\n pass\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_compatible_with_get_stack(self):\n async def async_generator():\n yield object()\n\n async def run():\n ag = async_generator()\n asyncio.create_task(ag.aclose())\n tasks = asyncio.all_tasks()\n for task in tasks:\n # No AttributeError raised\n task.get_stack()\n\n self.loop.run_until_complete(run())\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"breakpoint","pep":"553","introduced_in":"3.7","form":"modern","file":"breakpoint/modern_01.py","code":"import ast\nimport asyncio\nimport builtins\nimport collections\nimport decimal\nimport fractions\nimport io\nimport locale\nimport os\nimport pickle\nimport platform\nimport random\nimport re\nimport sys\nimport traceback\nimport types\nimport unittest\nimport warnings\nfrom contextlib import ExitStack\nfrom functools import partial\nfrom inspect import CO_COROUTINE\nfrom itertools import product\nfrom textwrap import dedent\nfrom types import AsyncGeneratorType, FunctionType\nfrom operator import neg\nfrom test import support\nfrom test.support import (\n EnvironmentVarGuard, TESTFN, check_warnings, swap_attr, unlink,\n maybe_get_event_loop_policy)\nfrom test.support.script_helper import assert_python_ok\nfrom unittest.mock import MagicMock, patch\n\n\nclass TestBreakpoint(unittest.TestCase):\n def setUp(self):\n # These tests require a clean slate environment. For example, if the\n # test suite is run with $PYTHONBREAKPOINT set to something else, it\n # will mess up these tests. Similarly for sys.breakpointhook.\n # Cleaning the slate here means you can't use breakpoint() to debug\n # these tests, but I think that's okay. Just use pdb.set_trace() if\n # you must.\n self.resources = ExitStack()\n self.addCleanup(self.resources.close)\n self.env = self.resources.enter_context(EnvironmentVarGuard())\n del self.env['PYTHONBREAKPOINT']\n self.resources.enter_context(\n swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))\n\n def test_breakpoint(self):\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once()\n\n def test_breakpoint_with_breakpointhook_set(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_breakpointhook_reset(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n # Reset the hook and it will not be called again.\n sys.breakpointhook = sys.__breakpointhook__\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_args_and_keywords(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint(1, 2, 3, four=4, five=5)\n my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)\n\n def test_breakpoint_with_passthru_error(self):\n def my_breakpointhook():\n pass\n sys.breakpointhook = my_breakpointhook\n self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_builtin(self):\n self.env['PYTHONBREAKPOINT'] = 'int'\n with patch('builtins.int') as mock:\n breakpoint('7')\n mock.assert_called_once_with('7')\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_other(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_noop_0(self):\n self.env['PYTHONBREAKPOINT'] = '0'\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_not_called()\n\n def test_envar_good_path_empty_string(self):\n # PYTHONBREAKPOINT='' is the same as it not being set.\n self.env['PYTHONBREAKPOINT'] = ''\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_unimportable(self):\n for envar in (\n '.', '..', '.foo', 'foo.', '.int', 'int.',\n '.foo.bar', '..foo.bar', '/./',\n 'nosuchbuiltin',\n 'nosuchmodule.nosuchcallable',\n ):\n with self.subTest(envar=envar):\n self.env['PYTHONBREAKPOINT'] = envar\n mock = self.resources.enter_context(patch('pdb.set_trace'))\n w = self.resources.enter_context(check_warnings(quiet=True))\n breakpoint()\n self.assertEqual(\n str(w.message),\n f'Ignoring unimportable $PYTHONBREAKPOINT: \"{envar}\"')\n self.assertEqual(w.category, RuntimeWarning)\n mock.assert_not_called()\n\n def test_envar_ignored_when_hook_is_set(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n sys.breakpointhook = int\n breakpoint()\n mock.assert_not_called()\n","source":"cpython_tests","origin":"Lib/test/test_builtin.py::TestBreakpoint","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, ZeroDivisionError)\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, TypeError)\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_03.py","code":"import concurrent.futures\nimport contextvars\nimport functools\nimport gc\nimport random\nimport time\nimport unittest\nimport weakref\n\n\nclass ContextTest(unittest.TestCase):\n def test_context_var_new_1(self):\n with self.assertRaisesRegex(TypeError, 'takes exactly 1'):\n contextvars.ContextVar()\n\n with self.assertRaisesRegex(TypeError, 'must be a str'):\n contextvars.ContextVar(1)\n\n c = contextvars.ContextVar('aaa')\n self.assertEqual(c.name, 'aaa')\n\n with self.assertRaises(AttributeError):\n c.name = 'bbb'\n\n self.assertNotEqual(hash(c), hash('aaa'))\n\n @isolated_context\n def test_context_var_repr_1(self):\n c = contextvars.ContextVar('a')\n self.assertIn('a', repr(c))\n\n c = contextvars.ContextVar('a', default=123)\n self.assertIn('123', repr(c))\n\n lst = []\n c = contextvars.ContextVar('a', default=lst)\n lst.append(c)\n self.assertIn('...', repr(c))\n self.assertIn('...', repr(lst))\n\n t = c.set(1)\n self.assertIn(repr(c), repr(t))\n self.assertNotIn(' used ', repr(t))\n c.reset(t)\n self.assertIn(' used ', repr(t))\n\n def test_context_subclassing_1(self):\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContextVar(contextvars.ContextVar):\n # Potentially we might want ContextVars to be subclassable.\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContext(contextvars.Context):\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyToken(contextvars.Token):\n pass\n\n def test_context_new_1(self):\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1, a=1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(a=1)\n contextvars.Context(**{})\n\n def test_context_typerrors_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx[1]\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n 1 in ctx\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx.get(1)\n\n def test_context_get_context_1(self):\n ctx = contextvars.copy_context()\n self.assertIsInstance(ctx, contextvars.Context)\n\n def test_context_run_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required'):\n ctx.run()\n\n def test_context_run_2(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n kwargs['spam'] = 'foo'\n args += ('bar',)\n return args, kwargs\n\n for f in (func, functools.partial(func)):\n # partial doesn't support FASTCALL\n\n self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))\n self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, a=2),\n (('bar',), {'a': 2, 'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, 11, a=2),\n ((11, 'bar'), {'a': 2, 'spam': 'foo'}))\n\n a = {}\n self.assertEqual(\n ctx.run(f, 11, **a),\n ((11, 'bar'), {'spam': 'foo'}))\n self.assertEqual(a, {})\n\n def test_context_run_3(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2, a=123)\n\n @isolated_context\n def test_context_run_4(self):\n ctx1 = contextvars.Context()\n ctx2 = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func2():\n self.assertIsNone(var.get(None))\n\n def func1():\n self.assertIsNone(var.get(None))\n var.set('spam')\n ctx2.run(func2)\n self.assertEqual(var.get(None), 'spam')\n\n cur = contextvars.copy_context()\n self.assertEqual(len(cur), 1)\n self.assertEqual(cur[var], 'spam')\n return cur\n\n returned_ctx = ctx1.run(func1)\n self.assertEqual(ctx1, returned_ctx)\n self.assertEqual(returned_ctx[var], 'spam')\n self.assertIn(var, returned_ctx)\n\n def test_context_run_5(self):\n ctx = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func():\n self.assertIsNone(var.get(None))\n var.set('spam')\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n\n self.assertIsNone(var.get(None))\n\n def test_context_run_6(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('a', default=0)\n\n def fun():\n self.assertEqual(c.get(), 0)\n self.assertIsNone(ctx.get(c))\n\n c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(ctx.get(c), 42)\n\n ctx.run(fun)\n\n def test_context_run_7(self):\n ctx = contextvars.Context()\n\n def fun():\n with self.assertRaisesRegex(RuntimeError, 'is already entered'):\n ctx.run(fun)\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_1(self):\n c = contextvars.ContextVar('c')\n with self.assertRaises(LookupError):\n c.get()\n\n self.assertIsNone(c.get(None))\n\n t0 = c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n self.assertIs(t0.old_value, t0.MISSING)\n self.assertIs(t0.old_value, contextvars.Token.MISSING)\n self.assertIs(t0.var, c)\n\n t = c.set('spam')\n self.assertEqual(c.get(), 'spam')\n self.assertEqual(c.get(None), 'spam')\n self.assertEqual(t.old_value, 42)\n c.reset(t)\n\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n\n c.set('spam2')\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t)\n self.assertEqual(c.get(), 'spam2')\n\n ctx1 = contextvars.copy_context()\n self.assertIn(c, ctx1)\n\n c.reset(t0)\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t0)\n self.assertIsNone(c.get(None))\n\n self.assertIn(c, ctx1)\n self.assertEqual(ctx1[c], 'spam2')\n self.assertEqual(ctx1.get(c, 'aa'), 'spam2')\n self.assertEqual(len(ctx1), 1)\n self.assertEqual(list(ctx1.items()), [(c, 'spam2')])\n self.assertEqual(list(ctx1.values()), ['spam2'])\n self.assertEqual(list(ctx1.keys()), [c])\n self.assertEqual(list(ctx1), [c])\n\n ctx2 = contextvars.copy_context()\n self.assertNotIn(c, ctx2)\n with self.assertRaises(KeyError):\n ctx2[c]\n self.assertEqual(ctx2.get(c, 'aa'), 'aa')\n self.assertEqual(len(ctx2), 0)\n self.assertEqual(list(ctx2), [])\n\n @isolated_context\n def test_context_getset_2(self):\n v1 = contextvars.ContextVar('v1')\n v2 = contextvars.ContextVar('v2')\n\n t1 = v1.set(42)\n with self.assertRaisesRegex(ValueError, 'by a different'):\n v2.reset(t1)\n\n @isolated_context\n def test_context_getset_3(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n def fun():\n self.assertEqual(c.get(), 42)\n with self.assertRaises(KeyError):\n ctx[c]\n self.assertIsNone(ctx.get(c))\n self.assertEqual(ctx.get(c, 'spam'), 'spam')\n self.assertNotIn(c, ctx)\n self.assertEqual(list(ctx.keys()), [])\n\n t = c.set(1)\n self.assertEqual(list(ctx.keys()), [c])\n self.assertEqual(ctx[c], 1)\n\n c.reset(t)\n self.assertEqual(list(ctx.keys()), [])\n with self.assertRaises(KeyError):\n ctx[c]\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_4(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n tok = ctx.run(c.set, 1)\n\n with self.assertRaisesRegex(ValueError, 'different Context'):\n c.reset(tok)\n\n @isolated_context\n def test_context_getset_5(self):\n c = contextvars.ContextVar('c', default=42)\n c.set([])\n\n def fun():\n c.set([])\n c.get().append(42)\n self.assertEqual(c.get(), [42])\n\n contextvars.copy_context().run(fun)\n self.assertEqual(c.get(), [])\n\n def test_context_copy_1(self):\n ctx1 = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def ctx1_fun():\n c.set(10)\n\n ctx2 = ctx1.copy()\n self.assertEqual(ctx2[c], 10)\n\n c.set(20)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 10)\n\n ctx2.run(ctx2_fun)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 30)\n\n def ctx2_fun():\n self.assertEqual(c.get(), 10)\n c.set(30)\n self.assertEqual(c.get(), 30)\n\n ctx1.run(ctx1_fun)\n\n @isolated_context\n def test_context_threads_1(self):\n cvar = contextvars.ContextVar('cvar')\n\n def sub(num):\n for i in range(10):\n cvar.set(num + i)\n time.sleep(random.uniform(0.001, 0.05))\n self.assertEqual(cvar.get(), num + i)\n return num\n\n tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)\n try:\n results = list(tp.map(sub, range(10)))\n finally:\n tp.shutdown()\n self.assertEqual(results, list(range(10)))\n","source":"cpython_tests","origin":"Lib/test/test_context.py::ContextTest","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_17.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFieldNoAnnotation(unittest.TestCase):\n def test_field_without_annotation(self):\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n @dataclass\n class C:\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base(self):\n @dataclass\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base_not_dataclass(self):\n # Same test, but with the base class not a dataclass.\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFieldNoAnnotation","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_18.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDocString(unittest.TestCase):\n def assertDocStrEqual(self, a, b):\n # Because 3.6 and 3.7 differ in how inspect.signature work\n # (see bpo #32108), for the time being just compare them with\n # whitespace stripped.\n self.assertEqual(a.replace(' ', ''), b.replace(' ', ''))\n\n def test_existing_docstring_not_overridden(self):\n @dataclass\n class C:\n \"\"\"Lorem ipsum\"\"\"\n x: int\n\n self.assertEqual(C.__doc__, \"Lorem ipsum\")\n\n def test_docstring_no_fields(self):\n @dataclass\n class C:\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C()\")\n\n def test_docstring_one_field(self):\n @dataclass\n class C:\n x: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int)\")\n\n def test_docstring_two_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int)\")\n\n def test_docstring_three_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n z: str\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int, z:str)\")\n\n def test_docstring_one_field_with_default(self):\n @dataclass\n class C:\n x: int = 3\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int=3)\")\n\n def test_docstring_one_field_with_default_none(self):\n @dataclass\n class C:\n x: Union[int, type(None)] = None\n\n self.assertDocStrEqual(C.__doc__, \"C(x:Optional[int]=None)\")\n\n def test_docstring_list_field(self):\n @dataclass\n class C:\n x: List[int]\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int])\")\n\n def test_docstring_list_field_with_default_factory(self):\n @dataclass\n class C:\n x: List[int] = field(default_factory=list)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int]=)\")\n\n def test_docstring_deque_field(self):\n @dataclass\n class C:\n x: deque\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque)\")\n\n def test_docstring_deque_field_with_default_factory(self):\n @dataclass\n class C:\n x: deque = field(default_factory=deque)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque=)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDocString","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_19.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestInit(unittest.TestCase):\n def test_base_has_init(self):\n class B:\n def __init__(self):\n self.z = 100\n pass\n\n # Make sure that declaring this class doesn't raise an error.\n # The issue is that we can't override __init__ in our class,\n # but it should be okay to add __init__ to us if our base has\n # an __init__.\n @dataclass\n class C(B):\n x: int = 0\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertNotIn('z', vars(c))\n\n # Make sure that if we don't add an init, the base __init__\n # gets called.\n @dataclass(init=False)\n class C(B):\n x: int = 10\n c = C()\n self.assertEqual(c.x, 10)\n self.assertEqual(c.z, 100)\n\n def test_no_init(self):\n dataclass(init=False)\n class C:\n i: int = 0\n self.assertEqual(C().i, 0)\n\n dataclass(init=False)\n class C:\n i: int = 2\n def __init__(self):\n self.i = 3\n self.assertEqual(C().i, 3)\n\n def test_overwriting_init(self):\n # If the class has __init__, use it no matter the value of\n # init=.\n\n @dataclass\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(3).x, 6)\n\n @dataclass(init=True)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(4).x, 8)\n\n @dataclass(init=False)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(5).x, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestInit","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_20.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestRepr(unittest.TestCase):\n def test_repr(self):\n @dataclass\n class B:\n x: int\n\n @dataclass\n class C(B):\n y: int = 10\n\n o = C(4)\n self.assertEqual(repr(o), 'TestRepr.test_repr..C(x=4, y=10)')\n\n @dataclass\n class D(C):\n x: int = 20\n self.assertEqual(repr(D()), 'TestRepr.test_repr..D(x=20, y=10)')\n\n @dataclass\n class C:\n @dataclass\n class D:\n i: int\n @dataclass\n class E:\n pass\n self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr..C.D(i=0)')\n self.assertEqual(repr(C.E()), 'TestRepr.test_repr..C.E()')\n\n def test_no_repr(self):\n # Test a class with no __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n self.assertIn(f'{__name__}.TestRepr.test_no_repr..C object at',\n repr(C(3)))\n\n # Test a class with a __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'C-class'\n self.assertEqual(repr(C(3)), 'C-class')\n\n def test_overwriting_repr(self):\n # If the class has __repr__, use it no matter the value of\n # repr=.\n\n @dataclass\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=True)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestRepr","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_21.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestEq(unittest.TestCase):\n def test_no_eq(self):\n # Test a class with no __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n self.assertNotEqual(C(0), C(0))\n c = C(3)\n self.assertEqual(c, c)\n\n # Test a class with an __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 10\n self.assertEqual(C(3), 10)\n\n def test_overwriting_eq(self):\n # If the class has __eq__, use it no matter the value of\n # eq=.\n\n @dataclass\n class C:\n x: int\n def __eq__(self, other):\n return other == 3\n self.assertEqual(C(1), 3)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=True)\n class C:\n x: int\n def __eq__(self, other):\n return other == 4\n self.assertEqual(C(1), 4)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 5\n self.assertEqual(C(1), 5)\n self.assertNotEqual(C(1), 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestEq","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_22.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestOrdering(unittest.TestCase):\n def test_functools_total_ordering(self):\n # Test that functools.total_ordering works with this class.\n @total_ordering\n @dataclass\n class C:\n x: int\n def __lt__(self, other):\n # Perform the test \"backward\", just to make\n # sure this is being called.\n return self.x >= other\n\n self.assertLess(C(0), -1)\n self.assertLessEqual(C(0), -1)\n self.assertGreater(C(0), 1)\n self.assertGreaterEqual(C(0), 1)\n\n def test_no_order(self):\n # Test that no ordering functions are added by default.\n @dataclass(order=False)\n class C:\n x: int\n # Make sure no order methods are added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__lt__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n # Test that __lt__ is still called\n @dataclass(order=False)\n class C:\n x: int\n def __lt__(self, other):\n return False\n # Make sure other methods aren't added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n def test_overwriting_order(self):\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __lt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __lt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __le__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __le__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __gt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __gt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __ge__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __ge__(self):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestOrdering","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_23.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestHash(unittest.TestCase):\n def test_unsafe_hash(self):\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n y: str\n self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))\n\n def test_hash_rules(self):\n def non_bool(value):\n # Map to something else that's True, but not a bool.\n if value is None:\n return None\n if value:\n return (3,)\n return 0\n\n def test(case, unsafe_hash, eq, frozen, with_hash, result):\n with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,\n frozen=frozen):\n if result != 'exception':\n if with_hash:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n else:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n pass\n\n # See if the result matches what's expected.\n if result == 'fn':\n # __hash__ contains the function we generated.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNotNone(C.__dict__['__hash__'])\n\n elif result == '':\n # __hash__ is not present in our class.\n if not with_hash:\n self.assertNotIn('__hash__', C.__dict__)\n\n elif result == 'none':\n # __hash__ is set to None.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNone(C.__dict__['__hash__'])\n\n elif result == 'exception':\n # Creating the class should cause an exception.\n # This only happens with with_hash==True.\n assert(with_hash)\n with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n\n else:\n assert False, f'unknown result {result!r}'\n\n # There are 8 cases of:\n # unsafe_hash=True/False\n # eq=True/False\n # frozen=True/False\n # And for each of these, a different result if\n # __hash__ is defined or not.\n for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([\n (False, False, False, '', ''),\n (False, False, True, '', ''),\n (False, True, False, 'none', ''),\n (False, True, True, 'fn', ''),\n (True, False, False, 'fn', 'exception'),\n (True, False, True, 'fn', 'exception'),\n (True, True, False, 'fn', 'exception'),\n (True, True, True, 'fn', 'exception'),\n ], 1):\n test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)\n test(case, unsafe_hash, eq, frozen, True, res_defined_hash)\n\n # Test non-bool truth values, too. This is just to\n # make sure the data-driven table in the decorator\n # handles non-bool values.\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)\n\n\n def test_eq_only(self):\n # If a class defines __eq__, __hash__ is automatically added\n # and set to None. This is normal Python behavior, not\n # related to dataclasses. Make sure we don't interfere with\n # that (see bpo=32546).\n\n @dataclass\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1))\n self.assertNotEqual(C(1), C(4))\n\n # And make sure things work in this case if we specify\n # unsafe_hash=True.\n @dataclass(unsafe_hash=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1.0))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n # And check that the classes __eq__ is being used, despite\n # specifying eq=True.\n @dataclass(unsafe_hash=True, eq=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == 3 and self.i == other.i\n self.assertEqual(C(3), C(3))\n self.assertNotEqual(C(1), C(1))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n def test_0_field_hash(self):\n @dataclass(frozen=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n @dataclass(unsafe_hash=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n def test_1_field_hash(self):\n @dataclass(frozen=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n def test_hash_no_args(self):\n # Test dataclasses with no hash= argument. This exists to\n # make sure that if the @dataclass parameter name is changed\n # or the non-default hashing behavior changes, the default\n # hashability keeps working the same way.\n\n class Base:\n def __hash__(self):\n return 301\n\n # If frozen or eq is None, then use the default value (do not\n # specify any value in the decorator).\n for frozen, eq, base, expected in [\n (None, None, object, 'unhashable'),\n (None, None, Base, 'unhashable'),\n (None, False, object, 'object'),\n (None, False, Base, 'base'),\n (None, True, object, 'unhashable'),\n (None, True, Base, 'unhashable'),\n (False, None, object, 'unhashable'),\n (False, None, Base, 'unhashable'),\n (False, False, object, 'object'),\n (False, False, Base, 'base'),\n (False, True, object, 'unhashable'),\n (False, True, Base, 'unhashable'),\n (True, None, object, 'tuple'),\n (True, None, Base, 'tuple'),\n (True, False, object, 'object'),\n (True, False, Base, 'base'),\n (True, True, object, 'tuple'),\n (True, True, Base, 'tuple'),\n ]:\n\n with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):\n # First, create the class.\n if frozen is None and eq is None:\n @dataclass\n class C(base):\n i: int\n elif frozen is None:\n @dataclass(eq=eq)\n class C(base):\n i: int\n elif eq is None:\n @dataclass(frozen=frozen)\n class C(base):\n i: int\n else:\n @dataclass(frozen=frozen, eq=eq)\n class C(base):\n i: int\n\n # Now, make sure it hashes as expected.\n if expected == 'unhashable':\n c = C(10)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(c)\n\n elif expected == 'base':\n self.assertEqual(hash(C(10)), 301)\n\n elif expected == 'object':\n # I'm not sure what test to use here. object's\n # hash isn't based on id(), so calling hash()\n # won't tell us much. So, just check the\n # function used is object's.\n self.assertIs(C.__hash__, object.__hash__)\n\n elif expected == 'tuple':\n self.assertEqual(hash(C(42)), hash((42,)))\n\n else:\n assert False, f'unknown value for expected={expected!r}'\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestHash","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_24.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFrozen(unittest.TestCase):\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n c = C(10)\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertEqual(c.i, 10)\n\n def test_inherit(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n @dataclass(frozen=True)\n class D(C):\n j: int\n\n d = D(0, 10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n with self.assertRaises(FrozenInstanceError):\n d.j = 6\n self.assertEqual(d.i, 0)\n self.assertEqual(d.j, 10)\n\n # Test both ways: with an intermediate normal (non-dataclass)\n # class and without an intermediate class.\n def test_inherit_nonfrozen_from_frozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass(frozen=True)\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(I):\n pass\n\n def test_inherit_frozen_from_nonfrozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one'):\n @dataclass(frozen=True)\n class D(I):\n pass\n\n def test_inherit_from_normal_class(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n class C:\n pass\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n @dataclass(frozen=True)\n class D(I):\n i: int\n\n d = D(10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n\n def test_non_frozen_normal_derived(self):\n # See bpo-32953.\n\n @dataclass(frozen=True)\n class D:\n x: int\n y: int = 10\n\n class S(D):\n pass\n\n s = S(3)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n s.cached = True\n\n # But can't change the frozen attributes.\n with self.assertRaises(FrozenInstanceError):\n s.x = 5\n with self.assertRaises(FrozenInstanceError):\n s.y = 5\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.cached, True)\n\n def test_overwriting_frozen(self):\n # frozen uses __setattr__ and __delattr__.\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __setattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __setattr__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __delattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __delattr__(self):\n pass\n\n @dataclass(frozen=False)\n class C:\n x: int\n def __setattr__(self, name, value):\n self.__dict__['x'] = value * 2\n self.assertEqual(C(10).x, 20)\n\n def test_frozen_hash(self):\n @dataclass(frozen=True)\n class C:\n x: Any\n\n # If x is immutable, we can compute the hash. No exception is\n # raised.\n hash(C(3))\n\n # If x is mutable, computing the hash is an error.\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(C({}))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFrozen","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_25.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestSlots(unittest.TestCase):\n def test_simple(self):\n @dataclass\n class C:\n __slots__ = ('x',)\n x: Any\n\n # There was a bug where a variable in a slot was assumed to\n # also have a default value (of type\n # types.MemberDescriptorType).\n with self.assertRaisesRegex(TypeError,\n r\"__init__\\(\\) missing 1 required positional argument: 'x'\"):\n C()\n\n # We can create an instance, and assign to x.\n c = C(10)\n self.assertEqual(c.x, 10)\n c.x = 5\n self.assertEqual(c.x, 5)\n\n # We can't assign to anything else.\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'y'\"):\n c.y = 5\n\n def test_derived_added_field(self):\n # See bpo-33100.\n @dataclass\n class Base:\n __slots__ = ('x',)\n x: Any\n\n @dataclass\n class Derived(Base):\n x: int\n y: int\n\n d = Derived(1, 2)\n self.assertEqual((d.x, d.y), (1, 2))\n\n # We can add a new field to the derived instance.\n d.z = 10\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestSlots","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_26.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDescriptors(unittest.TestCase):\n def test_set_name(self):\n # See bpo-33141.\n\n # Create a descriptor.\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n def __get__(self, instance, owner):\n if instance is not None:\n return 1\n return self\n\n # This is the case of just normal descriptor behavior, no\n # dataclass code is involved in initializing the descriptor.\n @dataclass\n class C:\n c: int=D()\n self.assertEqual(C.c.name, 'cx')\n\n # Now test with a default value and init=False, which is the\n # only time this is really meaningful. If not using\n # init=False, then the descriptor will be overwritten, anyway.\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n self.assertEqual(C().c, 1)\n\n def test_non_descriptor(self):\n # PEP 487 says __set_name__ should work on non-descriptors.\n # Create a descriptor.\n\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n\n def test_lookup_on_instance(self):\n # See bpo-33175.\n class D:\n pass\n\n d = D()\n # Create an attribute on the instance, not type.\n d.__set_name__ = Mock()\n\n # Make sure d.__set_name__ is not called.\n @dataclass\n class C:\n i: int=field(default=d, init=False)\n\n self.assertEqual(d.__set_name__.call_count, 0)\n\n def test_lookup_on_class(self):\n # See bpo-33175.\n class D:\n pass\n D.__set_name__ = Mock()\n\n # Make sure D.__set_name__ is called.\n @dataclass\n class C:\n i: int=field(default=D(), init=False)\n\n self.assertEqual(D.__set_name__.call_count, 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDescriptors","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_27.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestMakeDataclass(unittest.TestCase):\n def test_simple(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace={'add_one': lambda self: self.x + 1})\n c = C(10)\n self.assertEqual((c.x, c.y), (10, 5))\n self.assertEqual(c.add_one(), 11)\n\n\n def test_no_mutate_namespace(self):\n # Make sure a provided namespace isn't mutated.\n ns = {}\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace=ns)\n self.assertEqual(ns, {})\n\n def test_base(self):\n class Base1:\n pass\n class Base2:\n pass\n C = make_dataclass('C',\n [('x', int)],\n bases=(Base1, Base2))\n c = C(2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n def test_base_dataclass(self):\n @dataclass\n class Base1:\n x: int\n class Base2:\n pass\n C = make_dataclass('C',\n [('y', int)],\n bases=(Base1, Base2))\n with self.assertRaisesRegex(TypeError, 'required positional'):\n c = C(2)\n c = C(1, 2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n self.assertEqual((c.x, c.y), (1, 2))\n\n def test_init_var(self):\n def post_init(self, y):\n self.x *= y\n\n C = make_dataclass('C',\n [('x', int),\n ('y', InitVar[int]),\n ],\n namespace={'__post_init__': post_init},\n )\n c = C(2, 3)\n self.assertEqual(vars(c), {'x': 6})\n self.assertEqual(len(fields(c)), 1)\n\n def test_class_var(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ])\n c = C(1)\n self.assertEqual(vars(c), {'x': 1})\n self.assertEqual(len(fields(c)), 1)\n self.assertEqual(C.y, 10)\n self.assertEqual(C.z, 20)\n\n def test_other_params(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ],\n init=False)\n # Make sure we have a repr, but no init.\n self.assertNotIn('__init__', vars(C))\n self.assertIn('__repr__', vars(C))\n\n # Make sure random other params don't work.\n with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):\n C = make_dataclass('C',\n [],\n xxinit=False)\n\n def test_no_types(self):\n C = make_dataclass('Point', ['x', 'y', 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': 'typing.Any',\n 'z': 'typing.Any'})\n\n C = make_dataclass('Point', ['x', ('y', int), 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': int,\n 'z': 'typing.Any'})\n\n def test_invalid_type_specification(self):\n for bad_field in [(),\n (1, 2, 3, 4),\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'Invalid field: '):\n make_dataclass('C', ['a', bad_field])\n\n # And test for things with no len().\n for bad_field in [float,\n lambda x:x,\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'has no len\\(\\)'):\n make_dataclass('C', ['a', bad_field])\n\n def test_duplicate_field_names(self):\n for field in ['a', 'ab']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'Field name duplicated'):\n make_dataclass('C', [field, 'a', field])\n\n def test_keyword_field_names(self):\n for field in ['for', 'async', 'await', 'as']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field, 'a'])\n\n def test_non_identifier_field_names(self):\n for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field, 'a'])\n\n def test_underscore_field_names(self):\n # Unlike namedtuple, it's okay if dataclass field names have\n # an underscore.\n make_dataclass('C', ['_', '_a', 'a_a', 'a_'])\n\n def test_funny_class_names_names(self):\n # No reason to prevent weird class names, since\n # types.new_class allows them.\n for classname in ['()', 'x,y', '*', '2@3', '']:\n with self.subTest(classname=classname):\n C = make_dataclass(classname, ['a', 'b'])\n self.assertEqual(C.__name__, classname)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestMakeDataclass","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_28.py","code":"from dataclasses import *\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestReplace(unittest.TestCase):\n def test(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n z: int = field(init=False, default=10)\n t: int = field(init=False, default=100)\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))\n self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))\n\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=3, z=20, t=50)\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, z=20)\n replace(c, x=3, z=20, t=50)\n\n # Make sure the result is still frozen.\n with self.assertRaisesRegex(FrozenInstanceError, \"cannot assign to field 'x'\"):\n c1.x = 3\n\n # Make sure we can't replace an attribute that doesn't exist,\n # if we're also replacing one that does exist. Test this\n # here, because setting attributes on frozen instances is\n # handled slightly differently from non-frozen ones.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'a'\"):\n c1 = replace(c, x=20, a=5)\n\n def test_invalid_field_name(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'z'\"):\n c1 = replace(c, z=3)\n\n def test_invalid_object(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(C, x=3)\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(0, x=3)\n\n def test_no_init(self):\n @dataclass\n class C:\n x: int\n y: int = field(init=False, default=10)\n\n c = C(1)\n c.y = 20\n\n # Make sure y gets the default value.\n c1 = replace(c, x=5)\n self.assertEqual((c1.x, c1.y), (5, 10))\n\n # Trying to replace y is an error.\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=2, y=30)\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, y=30)\n\n def test_classvar(self):\n @dataclass\n class C:\n x: int\n y: ClassVar[int] = 1000\n\n c = C(1)\n d = C(2)\n\n self.assertIs(c.y, d.y)\n self.assertEqual(c.y, 1000)\n\n # Trying to replace y is an error: can't replace ClassVars.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an \"\n \"unexpected keyword argument 'y'\"):\n replace(c, y=30)\n\n replace(c, x=5)\n\n def test_initvar_is_specified(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int]\n\n def __post_init__(self, y):\n self.x *= y\n\n c = C(1, 10)\n self.assertEqual(c.x, 10)\n with self.assertRaisesRegex(ValueError, r\"InitVar 'y' must be \"\n \"specified with replace()\"):\n replace(c, x=3)\n c = replace(c, x=3, y=5)\n self.assertEqual(c.x, 15)\n\n def test_recursive_repr(self):\n @dataclass\n class C:\n f: \"C\"\n\n c = C(None)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr..C(f=...)\")\n\n def test_recursive_repr_two_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: \"C\"\n\n c = C(None, None)\n c.f = c\n c.g = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_two_attrs\"\n \"..C(f=..., g=...)\")\n\n def test_recursive_repr_indirection(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n c.f = d\n d.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection\"\n \"..C(f=TestReplace.test_recursive_repr_indirection\"\n \"..D(f=...))\")\n\n def test_recursive_repr_indirection_two(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"E\"\n\n @dataclass\n class E:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n e = E(None)\n c.f = d\n d.f = e\n e.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection_two\"\n \"..C(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..D(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..E(f=...)))\")\n\n def test_recursive_repr_misc_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: int\n\n c = C(None, 1)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_misc_attrs\"\n \"..C(f=..., g=1)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestReplace","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"dict-union","pep":"584","introduced_in":"3.9","form":"modern","file":"dict-union/modern_01.py","code":"import collections\nimport collections.abc\nimport gc\nimport pickle\nimport random\nimport string\nimport sys\nimport unittest\nimport weakref\nfrom test import support\nfrom test import mapping_tests\n\n\ndef test_merge_operator(self):\n\n a = {0: 0, 1: 1, 2: 1}\n b = {1: 1, 2: 2, 3: 3}\n\n c = a.copy()\n c |= b\n\n self.assertEqual(a | b, {0: 0, 1: 1, 2: 2, 3: 3})\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n c = b.copy()\n c |= a\n\n self.assertEqual(b | a, {1: 1, 2: 1, 3: 3, 0: 0})\n self.assertEqual(c, {1: 1, 2: 1, 3: 3, 0: 0})\n\n c = a.copy()\n c |= [(1, 1), (2, 2), (3, 3)]\n\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n self.assertIs(a.__or__(None), NotImplemented)\n self.assertIs(a.__or__(()), NotImplemented)\n self.assertIs(a.__or__(\"BAD\"), NotImplemented)\n self.assertIs(a.__or__(\"\"), NotImplemented)\n\n self.assertRaises(TypeError, a.__ior__, None)\n self.assertEqual(a.__ior__(()), {0: 0, 1: 1, 2: 1})\n self.assertRaises(ValueError, a.__ior__, \"BAD\")\n self.assertEqual(a.__ior__(\"\"), {0: 0, 1: 1, 2: 1})\n","source":"cpython_tests","origin":"Lib/test/test_dict.py::DictTest.test_merge_operator","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_01.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport lzma\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom . import _support as test_support\nfrom ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\n\n\nclass ZoneInfoCacheTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n def setUp(self):\n self.klass.clear_cache()\n super().setUp()\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @property\n def tzpath(self):\n return [self.zoneinfo_data.tzpath]\n\n def test_ephemeral_zones(self):\n self.assertIs(\n self.klass(\"America/Los_Angeles\"), self.klass(\"America/Los_Angeles\")\n )\n\n def test_strong_refs(self):\n tz0 = self.klass(\"Australia/Sydney\")\n tz1 = self.klass(\"Australia/Sydney\")\n\n self.assertIs(tz0, tz1)\n\n def test_no_cache(self):\n\n tz0 = self.klass(\"Europe/Lisbon\")\n tz1 = self.klass.no_cache(\"Europe/Lisbon\")\n\n self.assertIsNot(tz0, tz1)\n\n def test_cache_reset_tzpath(self):\n \"\"\"Test that the cache persists when tzpath has been changed.\n\n The PEP specifies that as long as a reference exists to one zone\n with a given key, the primary constructor must continue to return\n the same object.\n \"\"\"\n zi0 = self.klass(\"America/Los_Angeles\")\n with self.tzpath_context([]):\n zi1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIs(zi0, zi1)\n\n def test_clear_cache_explicit_none(self):\n la0 = self.klass(\"America/Los_Angeles\")\n self.klass.clear_cache(only_keys=None)\n la1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIsNot(la0, la1)\n\n def test_clear_cache_one_key(self):\n \"\"\"Tests that you can clear a single key from the cache.\"\"\"\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n\n self.klass.clear_cache(only_keys=[\"America/Los_Angeles\"])\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n\n self.assertIsNot(la0, la1)\n self.assertIs(dub0, dub1)\n\n def test_clear_cache_two_keys(self):\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n tok0 = self.klass(\"Asia/Tokyo\")\n\n self.klass.clear_cache(\n only_keys=[\"America/Los_Angeles\", \"Europe/Dublin\"]\n )\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n tok1 = self.klass(\"Asia/Tokyo\")\n\n self.assertIsNot(la0, la1)\n self.assertIsNot(dub0, dub1)\n self.assertIs(tok0, tok1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ZoneInfoCacheTest","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_02.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport lzma\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom . import _support as test_support\nfrom ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\n\n\nclass TzPathTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n @staticmethod\n @contextlib.contextmanager\n def python_tzpath_context(value):\n path_var = \"PYTHONTZPATH\"\n try:\n with OS_ENV_LOCK:\n old_env = os.environ.get(path_var, None)\n os.environ[path_var] = value\n yield\n finally:\n if old_env is None:\n del os.environ[path_var]\n else:\n os.environ[path_var] = old_env # pragma: nocover\n\n def test_env_variable(self):\n \"\"\"Tests that the environment variable works with reset_tzpath.\"\"\"\n new_paths = [\n (\"\", []),\n (\"/etc/zoneinfo\", [\"/etc/zoneinfo\"]),\n (f\"/a/b/c{os.pathsep}/d/e/f\", [\"/a/b/c\", \"/d/e/f\"]),\n ]\n\n for new_path_var, expected_result in new_paths:\n with self.python_tzpath_context(new_path_var):\n with self.subTest(tzpath=new_path_var):\n self.module.reset_tzpath()\n tzpath = self.module.TZPATH\n self.assertSequenceEqual(tzpath, expected_result)\n\n def test_env_variable_relative_paths(self):\n test_cases = [\n [(\"path/to/somewhere\",), ()],\n [\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\",),\n ],\n [(\"../relative/path\",), ()],\n [\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\",),\n ],\n [(\"path/to/somewhere\", \"../relative/path\",), ()],\n [\n (\n \"/usr/share/zoneinfo\",\n \"path/to/somewhere\",\n \"../relative/path\",\n ),\n (\"/usr/share/zoneinfo\",),\n ],\n ]\n\n for input_paths, expected_paths in test_cases:\n path_var = os.pathsep.join(input_paths)\n with self.python_tzpath_context(path_var):\n with self.subTest(\"warning\", path_var=path_var):\n # Note: Per PEP 615 the warning is implementation-defined\n # behavior, other implementations need not warn.\n with self.assertWarns(self.module.InvalidTZPathWarning):\n self.module.reset_tzpath()\n\n tzpath = self.module.TZPATH\n with self.subTest(\"filtered\", path_var=path_var):\n self.assertSequenceEqual(tzpath, expected_paths)\n\n def test_reset_tzpath_kwarg(self):\n self.module.reset_tzpath(to=[\"/a/b/c\"])\n\n self.assertSequenceEqual(self.module.TZPATH, (\"/a/b/c\",))\n\n def test_reset_tzpath_relative_paths(self):\n bad_values = [\n (\"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"path/to/somewhere\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\", \"../relative/path\",),\n ]\n for input_paths in bad_values:\n with self.subTest(input_paths=input_paths):\n with self.assertRaises(ValueError):\n self.module.reset_tzpath(to=input_paths)\n\n def test_tzpath_type_error(self):\n bad_values = [\n \"/etc/zoneinfo:/usr/share/zoneinfo\",\n b\"/etc/zoneinfo:/usr/share/zoneinfo\",\n 0,\n ]\n\n for bad_value in bad_values:\n with self.subTest(value=bad_value):\n with self.assertRaises(TypeError):\n self.module.reset_tzpath(bad_value)\n\n def test_tzpath_attribute(self):\n tzpath_0 = [\"/one\", \"/two\"]\n tzpath_1 = [\"/three\"]\n\n with self.tzpath_context(tzpath_0):\n query_0 = self.module.TZPATH\n\n with self.tzpath_context(tzpath_1):\n query_1 = self.module.TZPATH\n\n self.assertSequenceEqual(tzpath_0, query_0)\n self.assertSequenceEqual(tzpath_1, query_1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TzPathTest","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_03.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport lzma\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom . import _support as test_support\nfrom ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\n\n\nclass TestModule(ZoneInfoTestBase):\n module = py_zoneinfo\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @cached_property\n def _UTC_bytes(self):\n zone_file = self.zoneinfo_data.path_from_key(\"UTC\")\n with open(zone_file, \"rb\") as f:\n return f.read()\n\n def touch_zone(self, key, tz_root):\n \"\"\"Creates a valid TZif file at key under the zoneinfo root tz_root.\n\n tz_root must exist, but all folders below that will be created.\n \"\"\"\n if not os.path.exists(tz_root):\n raise FileNotFoundError(f\"{tz_root} does not exist.\")\n\n root_dir, *tail = key.rsplit(\"/\", 1)\n if tail: # If there's no tail, then the first component isn't a dir\n os.makedirs(os.path.join(tz_root, root_dir), exist_ok=True)\n\n zonefile_path = os.path.join(tz_root, key)\n with open(zonefile_path, \"wb\") as f:\n f.write(self._UTC_bytes)\n\n def test_getattr_error(self):\n with self.assertRaises(AttributeError):\n self.module.NOATTRIBUTE\n\n def test_dir_contains_all(self):\n \"\"\"dir(self.module) should at least contain everything in __all__.\"\"\"\n module_all_set = set(self.module.__all__)\n module_dir_set = set(dir(self.module))\n\n difference = module_all_set - module_dir_set\n\n self.assertFalse(difference)\n\n def test_dir_unique(self):\n \"\"\"Test that there are no duplicates in dir(self.module)\"\"\"\n module_dir = dir(self.module)\n module_unique = set(module_dir)\n\n self.assertCountEqual(module_dir, module_unique)\n\n def test_available_timezones(self):\n with self.tzpath_context([self.zoneinfo_data.tzpath]):\n self.assertTrue(self.zoneinfo_data.keys) # Sanity check\n\n available_keys = self.module.available_timezones()\n zoneinfo_keys = set(self.zoneinfo_data.keys)\n\n # If tzdata is not present, zoneinfo_keys == available_keys,\n # otherwise it should be a subset.\n union = zoneinfo_keys & available_keys\n self.assertEqual(zoneinfo_keys, union)\n\n def test_available_timezones_weirdzone(self):\n with tempfile.TemporaryDirectory() as td:\n # Make a fictional zone at \"Mars/Olympus_Mons\"\n self.touch_zone(\"Mars/Olympus_Mons\", td)\n\n with self.tzpath_context([td]):\n available_keys = self.module.available_timezones()\n self.assertIn(\"Mars/Olympus_Mons\", available_keys)\n\n def test_folder_exclusions(self):\n expected = {\n \"America/Los_Angeles\",\n \"America/Santiago\",\n \"America/Indiana/Indianapolis\",\n \"UTC\",\n \"Europe/Paris\",\n \"Europe/London\",\n \"Asia/Tokyo\",\n \"Australia/Sydney\",\n }\n\n base_tree = list(expected)\n posix_tree = [f\"posix/{x}\" for x in base_tree]\n right_tree = [f\"right/{x}\" for x in base_tree]\n\n cases = [\n (\"base_tree\", base_tree),\n (\"base_and_posix\", base_tree + posix_tree),\n (\"base_and_right\", base_tree + right_tree),\n (\"all_trees\", base_tree + right_tree + posix_tree),\n ]\n\n with tempfile.TemporaryDirectory() as td:\n for case_name, tree in cases:\n tz_root = os.path.join(td, case_name)\n os.mkdir(tz_root)\n\n for key in tree:\n self.touch_zone(key, tz_root)\n\n with self.tzpath_context([tz_root]):\n with self.subTest(case_name):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n\n def test_exclude_posixrules(self):\n expected = {\n \"America/New_York\",\n \"Europe/London\",\n }\n\n tree = list(expected) + [\"posixrules\"]\n\n with tempfile.TemporaryDirectory() as td:\n for key in tree:\n self.touch_zone(key, td)\n\n with self.tzpath_context([td]):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TestModule","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.9","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_04.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport lzma\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom . import _support as test_support\nfrom ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\n\n\nclass ExtensionBuiltTest(unittest.TestCase):\n \"\"\"Smoke test to ensure that the C and Python extensions are both tested.\n\n Because the intention is for the Python and C versions of ZoneInfo to\n behave identically, these tests necessarily rely on implementation details,\n so the tests may need to be adjusted if the implementations change. Do not\n rely on these tests as an indication of stable properties of these classes.\n \"\"\"\n\n def test_cache_location(self):\n # The pure Python version stores caches on attributes, but the C\n # extension stores them in C globals (at least for now)\n self.assertFalse(hasattr(c_zoneinfo.ZoneInfo, \"_weak_cache\"))\n self.assertTrue(hasattr(py_zoneinfo.ZoneInfo, \"_weak_cache\"))\n\n def test_gc_tracked(self):\n # The pure Python version is tracked by the GC but (for now) the C\n # version is not.\n import gc\n\n self.assertTrue(gc.is_tracked(py_zoneinfo.ZoneInfo))\n self.assertFalse(gc.is_tracked(c_zoneinfo.ZoneInfo))\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ExtensionBuiltTest","origin_revision":"v3.9.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_01.py","code":"from typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_02.py","code":"import typing\nx: typing.List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_03.py","code":"from typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: List[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> List[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_01.py","code":"from typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_02.py","code":"import typing\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_03.py","code":"from typing import List\nSomeAlias = list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: list[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> list[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_01.py","code":"x = lambda foo: None","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[lambdas do not have type annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_02.py","code":"from __future__ import annotations\nfrom typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_03.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not a PEP 585 type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_01.py","code":"open(\"foo\", encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop_before_315","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_02.py","code":"open(\"foo\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_03.py","code":"open(\"foo\", encoding=\"latin1\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"latin1\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_04.py","code":"open(\"foo\", encoding=\"us-ascii\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"us-ascii\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_05.py","code":"open(\"foo\", \"r\", \"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", \"r\", \"utf-8\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_06.py","code":"open(\"foo\", encoding=\"utf-8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[simple case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_07.py","code":"open(\"foo\", encoding=\"UTF8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[alternative spelling]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_08.py","code":"open(*args, encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_18.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"async def c(): return f'{await 1+foo()}'","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_18.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_01.py","code":"if s.startswith(\"foo\"):\n s = s[len(\"foo\"):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_02.py","code":"if s.startswith(S):\n s = s[len(S):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_03.py","code":"if s.endswith(\"foo\"):\n s = s[:-1 * len(\"foo\")]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_04.py","code":"if s.endswith(S):\n s = s[:-1 * len(S)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_05.py","code":"if s.startswith(x):\n s = s[len(x):] # TODO: removeprefix\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_06.py","code":"if True:\n if s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_07.py","code":"if True:\n something_else()\n if s.startswith(x):\n s = s[len(x):]\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_08.py","code":"if (\n x.startswith(y)\n):\n x = x[len(y):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_01.py","code":"s = s.removeprefix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_02.py","code":"s = s.removeprefix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_03.py","code":"s = s.removesuffix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_04.py","code":"s = s.removesuffix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_05.py","code":"s = s.removeprefix(x)\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_06.py","code":"if True:\n s = s.removeprefix(x)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_07.py","code":"if True:\n something_else()\n s = s.removeprefix(x)\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_08.py","code":"x = x.removeprefix(y)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_01.py","code":"if x.startswith(S):\n x = x[len(S):]\nelif x.endswith(T):\n x = x[:-1 * len(T)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop_before_39","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_02.py","code":"if s.startswith(\"a\"):\n s = s.lstrip(\"a\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[unrelated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_03.py","code":"if s.startswith(x):\n s = s[2:]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[cannot prove x is 2]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_04.py","code":"if s.startswith(x):\n s = s[len(x):]\nelse:\n print(\"no!)\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has else]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_05.py","code":"if something:\n print(\"something!\")\nelif s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has elif]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_01.py","code":"from typing import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_02.py","code":"import typing\nD = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": typing.Literal[\"b\", b\"c\"]})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_05.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {\n # first comment\n \"a\": int, # inline comment\n # second comment\n \"b\": str,\n # third comment\n}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_07.py","code":"from typing_extensions import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_08.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_09.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int}, total=True)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nFoo = TypedDict(\"Foo\", {\"lsts\": List[List[int]]})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_11.py","code":"import typing\nif True:\n if False:\n pass\n D = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_12.py","code":"from typing import TypedDict\nFoo = TypedDict(\"Foo\", {\"union\": str | int | None})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_01.py","code":"from typing import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_02.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_03.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_04.py","code":"import typing\nclass D(typing.TypedDict):\n a: typing.Literal['b', b'c']\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_05.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_06.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n # first comment\n a: int # inline comment\n # second comment\n b: str\n # third comment\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_07.py","code":"from typing_extensions import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_08.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_09.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict, total=True):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nclass Foo(TypedDict):\n lsts: List[List[int]]","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_11.py","code":"import typing\nif True:\n if False:\n pass\n class D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_12.py","code":"from typing import TypedDict\nclass Foo(TypedDict):\n union: str | int | None","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_01.py","code":"from wat import TypedDict\nQ = TypedDict(\"Q\")\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[from imported from elsewhere]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_02.py","code":"import typing\nD = typing.TypedDict(\"D\")","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {}, a=int)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[both]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_05.py","code":"import typing\nD = typing.TypedDict(\"D\", 1)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[not a dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {1: str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not a string]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_07.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a-b\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not an identifier]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_08.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"class\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is a keyword]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_09.py","code":"import typing\nD = typing.TypedDict(\"D\", {**d, \"a\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[dictionary splat operator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_10.py","code":"import typing\nC = typing.TypedDict(\"C\", *types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_11.py","code":"import typing\nD = typing.TypedDict(\"D\", **types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starstarkwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_12.py","code":"import typing\nD = typing.TypedDict(\"D\", x=int, total=False)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[kw_typed_dict with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_01.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_02.py","code":"import typing\nx: typing.Union[int]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_03.py","code":"import typing\nx: typing.Union[Foo[str, int], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_04.py","code":"import typing\nx: typing.Union[typing.List[str], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_05.py","code":"import typing\nx: typing.Union[int, str,]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_06.py","code":"import typing\nx: typing.Union[(int, str)]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_07.py","code":"import typing\nx: typing.Union[\n int,\n str\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_08.py","code":"import typing\nx: typing.Union[\n int,\n str,\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_09.py","code":"from typing import Optional\nx: Optional[str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_10.py","code":"import typing\nx: typing.Optional[\n ComplicatedLongType[int]\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: Optional[\"str\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_12.py","code":"from typing import Union, Sequence\ndef f(x: Union[Union[A, B], Sequence[Union[C, D]]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_13.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_14.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_15.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_16.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> Union[int, str]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_01.py","code":"from typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_02.py","code":"x: int\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_03.py","code":"x: Foo[str, int] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_04.py","code":"x: list[str] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_05.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_06.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_07.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_08.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_09.py","code":"from typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_10.py","code":"x: None | (\n ComplicatedLongType[int]\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_12.py","code":"from typing import Union\nfrom collections.abc import Sequence\ndef f(x: A | B | Sequence[C | D]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_13.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x})\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_14.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x}(\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_15.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x}(\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_16.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x})\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: int | str) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> int | str: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_01.py","code":"from __future__ import annotations\nfrom typing import Union\nSomeAlias = Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[<3.9 not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_02.py","code":"from typing import Union\ndef f() -> Union[()]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ empty Union]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_03.py","code":"from typing import Optional\ndef f() -> Optional[\"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Optional of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_04.py","code":"from typing import Union\ndef f() -> Union[int, \"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Union of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_05.py","code":"from typing import Union\ndef f() -> Union[1:2]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[invalid Union slicing]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_01.py","code":"from contextvars import ContextVar\nfrom types import MappingProxyType\nimport re\nimport collections\nimport time\n\n# Okay\nContextVar(\"cv\")\nContextVar(\"cv\", default=())\nContextVar(\"cv\", default=(1, 2, 3))\nContextVar(\"cv\", default=\"foo\")\nContextVar(\"cv\", default=tuple())\nContextVar(\"cv\", default=frozenset())\nContextVar(\"cv\", default=MappingProxyType({}))\nContextVar(\"cv\", default=re.compile(\"foo\"))\nContextVar(\"cv\", default=float(1))\nContextVar(\"cv\", default=frozenset[str]())\nContextVar[frozenset[str]](\"cv\", default=frozenset[str]())\n\n# Bad\nContextVar(\"cv\", default=[])\nContextVar(\"cv\", default={})\nContextVar(\"cv\", default=list())\nContextVar(\"cv\", default=set())\nContextVar(\"cv\", default=dict())\nContextVar(\"cv\", default=[char for char in \"foo\"])\nContextVar(\"cv\", default={char for char in \"foo\"})\nContextVar(\"cv\", default={char: idx for idx, char in enumerate(\"foo\")})\nContextVar(\"cv\", default=collections.deque())\nContextVar(\"cv\", default=set[str]())\nContextVar[set[str]](\"cv\", default=set[str]())\n\ndef bar() -> list[int]:\n return [1, 2, 3]\n\nContextVar(\"cv\", default=bar())\nContextVar(\"cv\", default=time.time())\n\ndef baz(): ...\nContextVar(\"cv\", default=baz())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_02.py","code":"from contextvars import ContextVar\n\nfrom fastapi import Query\nContextVar(\"cv\", default=Query(None))\n\nfrom something_else import Depends\nContextVar(\"cv\", default=Depends())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039_extended.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_01.py","code":"import typing\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, Sequence\n\nKNOWINGLY_MUTABLE_DEFAULT = []\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = []\n immutable_annotation: typing.Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: typing.ClassVar[list[int]] = []\n\n\n@dataclass\nclass B:\n mutable_default: list[int] = []\n immutable_annotation: Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: ClassVar[list[int]] = []\n\n# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n@dataclass\nclass AWithQuotes:\n mutable_default: 'list[int]' = []\n immutable_annotation: 'typing.Sequence[int]' = []\n without_annotation = []\n correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: 'list[int]' = field(default_factory=list)\n class_variable: 'typing.ClassVar[list[int]]'= []\n\n\n# Mutable defaults wrapped in field() calls\n@dataclass\nclass C:\n mutable_default: list[int] = field(default=[]) # RUF008\n mutable_default2: dict[str, int] = field(default={}) # RUF008\n mutable_default3: set[int] = field(default=set()) # RUF008\n mutable_default4: dict[str, int] = field(default=dict()) # RUF008\n correct_factory: list[int] = field(default_factory=list) # okay\n immutable_default: tuple[int, ...] = field(default=()) # okay\n immutable_default2: str = field(default=\"hello\") # okay\n immutable_default3: int = field(default=1) # okay\n non_mutable_var: list[int] = field(default=KNOWINGLY_MUTABLE_DEFAULT) # okay\n class_variable: ClassVar[list[int]] = field(default=[]) # okay\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_02.py","code":"# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n\nfrom __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Example():\n \"\"\"Class that uses ClassVar.\"\"\"\n\n options: ClassVar[dict[str, str]] = {}\n\n\nif typing.TYPE_CHECKING:\n from typing import ClassVar\n\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_03.py","code":"import datetime\nimport re\nimport typing\nfrom dataclasses import dataclass, field\nfrom fractions import Fraction\nfrom pathlib import Path\nfrom typing import ClassVar, NamedTuple\n\n\ndef default_function() -> list[int]:\n return []\n\n\nclass ImmutableType(NamedTuple):\n something: int = 8\n\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\n fine_path: Path = Path()\n fine_date: datetime.date = datetime.date(2042, 1, 1)\n fine_timedelta: datetime.timedelta = datetime.timedelta(hours=7)\n fine_tuple: tuple[int] = tuple([1])\n fine_regex: re.Pattern = re.compile(r\".*\")\n fine_float: float = float(\"-inf\")\n fine_int: int = int(12)\n fine_complex: complex = complex(1, 2)\n fine_str: str = str(\"foo\")\n fine_bool: bool = bool(\"foo\")\n fine_fraction: Fraction = Fraction(1, 2)\n\n\nDEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES = ImmutableType(40)\nDEFAULT_A_FOR_ALL_DATACLASSES = A([1, 2, 3])\n\n\n@dataclass\nclass B:\n hidden_mutable_default: list[int] = default_function()\n another_dataclass: A = A()\n not_optimal: ImmutableType = ImmutableType(20)\n good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES\n okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES\n\n fine_dataclass_function: list[int] = field(default_factory=list)\n\n\nclass IntConversionDescriptor:\n def __init__(self, *, default):\n self._default = default\n\n def __set_name__(self, owner, name):\n self._name = \"_\" + name\n\n def __get__(self, obj, type):\n if obj is None:\n return self._default\n\n return getattr(obj, self._name, self._default)\n\n def __set__(self, obj, value):\n setattr(obj, self._name, int(value))\n\n\n@dataclass\nclass InventoryItem:\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\n\n\n# Regression tests for:\n# https://github.com/astral-sh/ruff/issues/6447\nfrom typing import NewType\n\nListOfStrings = NewType(\"ListOfStrs\", list[str])\nStringsToInts = NewType(\"IntsToStrings\", dict[str, int])\n\nSpecialString = NewType(name=\"SpecialString\", tp=str)\nNegativeInteger = NewType(\"NegInt\", tp=int)\n\nInvalid1 = NewType(*Foo)\nInvalid2 = NewType(\"Invalid2\", name=Foo)\nInvalid3 = NewType(\"Invalid3\", name=Foo, lorem=\"ipsum\")\n\n@dataclass\nclass DataclassWithNewTypeFields:\n # Errors\n a: ListOfStrings = ListOfStrings([])\n b: StringsToInts = StringsToInts()\n c: Invalid1 = Invalid1()\n d: Invalid2 = Invalid2()\n e: Invalid3 = Invalid3()\n\n # No errors\n e: SpecialString = SpecialString(\"Lorem ipsum\")\n f: NegativeInteger = NegativeInteger(-110)\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/15772\ndef f() -> int:\n return 0\n\n@dataclass\nclass ShouldMatchB008RuleOfImmutableTypeAnnotationIgnored:\n this_is_not_fine: list[int] = default_function()\n # ignored\n this_is_fine: int = f()\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/17424\n@dataclass(frozen=True)\nclass C:\n foo: int = 1\n\n\n@dataclass\nclass D:\n c: C = C()\n\n\n@dataclass\nclass E:\n c: C = C()\n\n# https://github.com/astral-sh/ruff/issues/20266\n@dataclass(frozen=True)\nclass C:\n @dataclass(frozen=True)\n class D:\n foo: int = 1\n\n d: D = D() # OK","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_04.py","code":"from dataclasses import dataclass \nfrom typing import TYPE_CHECKING\n\n\ndef default_function() ->list[int]:\n return []\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\nif TYPE_CHECKING:\n from typing import ClassVar\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_05.py","code":"from dataclasses import InitVar, KW_ONLY, MISSING, dataclass, field\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n # Errors\n no_annotation = r\"foo\"\n missing = MISSING\n field = field()\n\n # No errors\n __slots__ = (\"foo\", \"bar\")\n __radd__ = __add__\n _private_attr = 100\n\n with_annotation: str\n with_annotation_and_default: int = 42\n with_annotation_and_field_specifier: bytes = field()\n\n class_var_no_arguments: ClassVar = 42\n class_var_with_arguments: ClassVar[int] = 42\n\n init_var_no_arguments: InitVar = \"lorem\"\n init_var_with_arguments: InitVar[str] = \"ipsum\"\n\n kw_only: KW_ONLY\n tu, ple, [unp, ack, ing] = (0, 1, 2, [3, 4, 5])\n mul, [ti, ple] = (a, ssign), ment = {1: b\"3\", \"2\": 4}, [6j, 5]\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_06.py","code":"from dataclasses import dataclass\nfrom enum import Enum, Flag, IntEnum, IntFlag, StrEnum, ReprEnum\n\nimport attr\nimport attrs\n\n\n## Errors\n\n@dataclass\nclass E(Enum): ...\n\n\n@dataclass # Foobar\nclass E(Flag): ...\n\n\n@dataclass()\nclass E(IntEnum): ...\n\n\n@dataclass() # Foobar\nclass E(IntFlag): ...\n\n\n@dataclass(\n frozen=True\n)\nclass E(StrEnum): ...\n\n\n@dataclass( # Foobar\n frozen=True\n)\nclass E(ReprEnum): ...\n\n\n@dataclass(\n frozen=True\n) # Foobar\nclass E(Enum): ...\n\n\n## No errors\n\n@attrs.define\nclass E(Enum): ...\n\n\n@attrs.frozen\nclass E(Enum): ...\n\n\n@attrs.mutable\nclass E(Enum): ...\n\n\n@attr.s\nclass E(Enum): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_01.py","code":"import typing\nimport typing_extensions\nfrom typing import Literal\n\n# Shouldn't affect non-union field types.\nfield1: Literal[1] # OK\n\n# Should emit for duplicate field types.\nfield2: Literal[1] | Literal[2] # Error\n\n# Should emit for union types in arguments.\ndef func1(arg1: Literal[1] | Literal[2]): # Error\n print(arg1)\n\n\n# Should emit for unions in return types.\ndef func2() -> Literal[1] | Literal[2]: # Error\n return \"my Literal[1]ing\"\n\n\n# Should emit in longer unions, even if not directly adjacent.\nfield3: Literal[1] | Literal[2] | str # Error\nfield4: str | Literal[1] | Literal[2] # Error\nfield5: Literal[1] | str | Literal[2] # Error\nfield6: Literal[1] | bool | Literal[2] | str # Error\n\n# Should emit for non-type unions.\nfield7 = Literal[1] | Literal[2] # Error\n\n# Should emit for parenthesized unions.\nfield8: Literal[1] | (Literal[2] | str) # Error\n\n# Should handle user parentheses when fixing.\nfield9: Literal[1] | (Literal[2] | str) # Error\nfield10: (Literal[1] | str) | Literal[2] # Error\n\n# Should emit for union in generic parent type.\nfield11: dict[Literal[1] | Literal[2], str] # Error\n\n# Should emit for unions with more than two cases\nfield12: Literal[1] | Literal[2] | Literal[3] # Error\nfield13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error\n\n# Should emit for unions with more than two cases, even if not directly adjacent\nfield14: Literal[1] | Literal[2] | str | Literal[3] # Error\n\n# Should emit for unions with mixed literal internal types\nfield15: Literal[1] | Literal[\"foo\"] | Literal[True] # Error\n\n# Shouldn't emit for duplicate field types with same value; covered by Y016\nfield16: Literal[1] | Literal[1] # OK\n\n# Shouldn't emit if in new parent type\nfield17: Literal[1] | dict[Literal[2], str] # OK\n\n# Shouldn't emit if not in a union parent\nfield18: dict[Literal[1], Literal[2]] # OK\n\n# Should respect name of literal type used\nfield19: typing.Literal[1] | typing.Literal[2] # Error\n\n# Should emit in cases with newlines\nfield20: typing.Union[\n Literal[\n 1 # test\n ],\n Literal[2],\n] # Error, newline and comment will not be emitted in message\n\n# Should handle multiple unions with multiple members\nfield21: Literal[1, 2] | Literal[3, 4] # Error\n\n# Should emit in cases with `typing.Union` instead of `|`\nfield22: typing.Union[Literal[1], Literal[2]] # Error\n\n# Should emit in cases with `typing_extensions.Literal`\nfield23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error\n\n# Should emit in cases with nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error\n\n# Should emit in cases with mixed `typing.Union` and `|`\nfield25: typing.Union[Literal[1], Literal[2] | str] # Error\n\n# Should emit only once in cases with multiple nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error\n\n# Should use the first literal subscript attribute when fixing\nfield25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error\n\nfrom typing import IO, Literal\n\nInlineOption = Literal[\"a\"] | Literal[\"b\"] | IO[str]\n\n# Should use unsafe fix when comments are deleted\nfield26: (\n # First comment\n Literal[\"a\", \"b\"]\n # Second comment\n | Literal[\"c\", \"d\"]\n)\nfield27: (\n Literal[\"a\", \"b\"] # First comment\n | Literal[\"c\", \"d\"] # Second comment\n)\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI030.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_02.py","code":"import typing\nfrom typing import Literal, TypeAlias, Union\n\nA: str | Literal[\"foo\"]\nB: TypeAlias = typing.Union[Literal[b\"bar\", b\"foo\"], bytes, str]\nC: TypeAlias = typing.Union[Literal[5], int, typing.Union[Literal[\"foo\"], str]]\nD: TypeAlias = typing.Union[Literal[b\"str_bytes\", 42], bytes, int]\nE: TypeAlias = typing.Union[typing.Union[typing.Union[typing.Union[Literal[\"foo\"], str]]]]\nF: TypeAlias = typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\nG: typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\n\ndef func(x: complex | Literal[1J], y: Union[Literal[3.14], float]): ...\n\n# OK\nA: Literal[\"foo\"]\nB: TypeAlias = Literal[b\"bar\", b\"foo\"]\nC: TypeAlias = typing.Union[Literal[5], Literal[\"foo\"]]\nD: TypeAlias = Literal[b\"str_bytes\", 42]\n\ndef func(x: Literal[1J], y: Literal[3.14]): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI051.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_03.py","code":"from typing import Literal\nimport typing as t\nimport typing_extensions\n\nx: Literal[True, False, True, False] # PYI062 twice here\n\ny: Literal[1, print(\"hello\"), 3, Literal[4, 1]] # PYI062 on the last 1\n\nz: Literal[{1, 3, 5}, \"foobar\", {1,3,5}] # PYI062 on the set literal\n\nLiteral[1, Literal[1]] # once\nLiteral[1, 2, Literal[1, 2]] # twice\nLiteral[1, Literal[1], Literal[1]] # twice\nLiteral[1, Literal[2], Literal[2]] # once\nt.Literal[1, t.Literal[2, t.Literal[1]]] # once\ntyping_extensions.Literal[1, 1, 1] # twice\nLiteral[\n 1, # comment\n Literal[ # another comment\n 1\n ]\n] # once\n\n# Ensure issue is only raised once, even on nested literals\nMyType = Literal[\"foo\", Literal[True, False, True], \"bar\"] # PYI062\n\nn: Literal[\"No\", \"duplicates\", \"here\", 1, \"1\"]\n\n\n# nested literals, all equivalent to `Literal[1]`\nLiteral[Literal[1]] # no duplicate\nLiteral[Literal[Literal[1], Literal[1]]] # once\nLiteral[Literal[1], Literal[Literal[Literal[1]]]] # once\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI062.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_01.py","code":"# parse_options: { \"target-version\": \"3.9\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/match_before_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_02.py","code":"match 2:\n case Class(x=x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_keyword_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_03.py","code":"match x:\n case [a] | [a]: ...\n case (x, y) | (x, y): ...\n case (x, (y | y)): ...\n case [a, _] | [a, _]: ...\n case [a] | [C(a)]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/different_match_pattern_bindings.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_04.py","code":"match x:\n case {x.a: 1, x.a: 2}: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/duplicate_match_key_attr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_05.py","code":"match x:\n case 2: ...\n case var: ...\nmatch x:\n case 2: ...\n case _: ...\nmatch x:\n case var if True: ... # don't try to refute a guarded pattern\n case 2: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/irrefutable_case_pattern_at_end.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_06.py","code":"# parse_options: { \"target-version\": \"3.10\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_after_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_07.py","code":"match foo:\n case foo_bar: ...\nmatch foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_08.py","code":"match foo:\n case case: ...\nmatch foo:\n case match: ...\nmatch foo:\n case type: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_09.py","code":"match foo:\n case match.bar: ...\n case case.bar: ...\n case type.bar: ...\n case match.case.type.bar.type.case.match: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_attr_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_10.py","code":"match foo:\n case _: ...\nmatch 1:\n case _: ...\nmatch 1.0:\n case _: ...\nmatch 1j:\n case _: ...\nmatch \"foo\":\n case _: ...\nmatch f\"foo {x}\":\n case _: ...\nmatch {1, 2}:\n case _: ...\nmatch ~foo:\n case _: ...\nmatch ...:\n case _: ...\nmatch not foo:\n case _: ...\nmatch await foo():\n case _: ...\nmatch lambda foo: foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_11.py","code":"match match:\n case _: ...\nmatch case:\n case _: ...\nmatch type:\n case _: ...\nmatch None:\n case _: ...\nmatch True:\n case _: ...\nmatch False:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_12.py","code":"match (1, 2) # Identifier\nmatch (1, 2): # Keyword\n case _: ...\nmatch [1:] # Identifier\nmatch [1, 2]: # Keyword\n case _: ...\nmatch * foo # Identifier\nmatch - foo # Identifier\nmatch -foo: # Keyword\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_or_identifier.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_13.py","code":"match subject:\n case [a, b]: ...\n case (a, b): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_parentheses_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_14.py","code":"match subject:\n case a if x: ...\n case a, b: ...\n case a, b if x: ...\n case a: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_15.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_16.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_17.py","code":"match 2:\n case Class(x) | [x] | x: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/multiple_assignment_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_18.py","code":"match ruff:\n case {\"lint\": {\"select\": x} | {\"extend-select\": x}} | {\"select\": x}:\n ...\nmatch 42:\n case [[x] | [x]] | x: ...\nmatch 42:\n case [[x | x] | [x]] | x: ...\nmatch 42:\n case ast.Subscript(n, ast.Constant() | ast.Slice()) | ast.Attribute(n): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/nested_alternative_patterns.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_19.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_01.py","code":"match[0]: int\nmatch [x, y, z]: dict\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_annotated_assignment.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_02.py","code":"match not in case\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_03.py","code":"match\nmatch != foo\n(foo, match)\n[foo, match]\n{foo, match}\nmatch;\nmatch: int\nmatch,\nmatch.foo\nmatch / foo\nmatch << foo\nmatch and foo\nmatch is not foo\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_04.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_01.py","code":"# parse_options: {\"target-version\": \"3.8\"}\ndef foo(a, /): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pos_only_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_02.py","code":"lambda: a\nlambda: 1\nlambda x: 1\nlambda x, y: ...\nlambda a, b, c: 1\nlambda a, b=20, c=30: 1\nlambda x, y: x * y\nlambda y, z=1: z * y\nlambda *a: a\nlambda *a, z, x=0: ...\nlambda *, a, b, c: 1\nlambda *, a, b=20, c=30: 1\nlambda a, b, c, *, d, e: 0\nlambda **kwargs: f()\nlambda *args, **kwargs: f() + 1\nlambda *args, a, b=1, **kwargs: f() + 1\nlambda a, /: ...\nlambda a, /, b: ...\nlambda a=1, /,: ...\nlambda a, b, /, *, c: ...\nlambda kw=1, *, a: ...\nlambda a, b=20, /, c=30: 1\nlambda a, b, /, c, *, d, e: 0\nlambda a, b, /, c, *d, e, **f: 0","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/lambda.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_01.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/decorator_named_expression_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_03.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_function_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_04.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_05.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_comp_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_06.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{x := 1, 2, 3}\n{1, x := 2, 3}\n{1, 2, x := 3}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_literal_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_07.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/walrus_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_08.py","code":"# parse_options: { \"target-version\": \"3.9\" }\n@buttons[0].clicked.connect\ndef spam(): ...\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/decorator_expression_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_09.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_10.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_11.py","code":"[a := 0 for x in range(0)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_rebound_comprehension_variable.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_12.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[(x:=1)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_13.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{(x := 1), 2, 3}\n{(last := x) for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_14.py","code":"# parse_options: {\"target-version\": \"3.9\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_index_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_15.py","code":"# parse_options: {\"target-version\": \"3.9\"}\n{x := 1, 2, 3}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_16.py","code":"class F(y := list): ...\ndef f():\n class G((yield 1)): ...\n class H((yield from 1)): ...\nasync def f():\n class G((await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_17.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_function_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_18.py","code":"# parse_options: {\"target-version\": \"3.13\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_19.py","code":"# parse_options: { \"target-version\": \"3.8\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/walrus_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_20.py","code":"# This only tests the call arguments and not the expression before the opening parenthesis.\n\n# Simple\ncall()\ncall(x, y)\ncall(x, y,) # Trailing comma\ncall(x=1, y=2)\ncall(*x)\ncall(**x)\n\n# Order\ncall(x, y=1)\ncall(x, *y)\ncall(x, **y)\ncall(x=1, *y)\ncall(x=1, **y)\ncall(*x, **y)\ncall(*x, y, z)\ncall(**x, y=1, z=2)\ncall(*x1, *x2, **y1, **y2)\ncall(x=1, **y, z=1)\n\n# Keyword expression\ncall(x=1 if True else 2)\ncall(x=await y)\ncall(x=lambda y: y)\ncall(x=(y := 1))\n\n# Yield expression\ncall((yield x))\ncall((yield from x))\n\n# Named expression\ncall(x := 1)\ncall(x := 1 for i in iter)\n\n# Starred expressions\ncall(*x and y)\ncall(*x | y)\ncall(*await x)\ncall(*lambda x: x)\ncall(*x if True else y)\n\n# Double starred\ncall(**x)\ncall(**x and y)\ncall(**await x)\ncall(**x if True else y)\ncall(**(yield x))\ncall(**lambda x: x)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/arguments.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_21.py","code":"# Simple\n{}\n{1: 2}\n{1: 2, a: 1, b: 'hello'}\n\n# Mixed indentations\n{\n}\n{\n 1:\n 2,\n 3\n :4\n}\n\n# Nested\n{{1: 2}: {3: {4: 5}}}\n\n# Lambda expressions\n{lambda x: x: 1}\n{'A': lambda p: None, 'B': C,}\n\n# Named expressions\n{(x := 1): y}\n{(x := 1): (y := 2)}\n\n# Double star unpacking\n{**d}\n{a: b, **d}\n{**a, **b}\n{\"a\": \"b\", **c, \"d\": \"e\"}\n{1: 2, **{'nested': 'dict'}}\n{x * 1: y ** 2, **call()}\n# Here, `not` isn't allowed but parentheses resets the precedence\n{**(not x)}\n\n# Random expressions\n{1: x if True else y}\n{x if True else y: y for x in range(10) for y in range(10)}\n{{1, 2}: 3, x: {1: 2,},}\n{(x): (y), (z): (a)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/dictionary.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_22.py","code":"(x for target in iter)\n(x async for target in iter)\n(x for target in iter if x in y if a and b if c)\n(x for target1 in iter1 if x and y for target2 in iter2 if a > b)\n(x for target1 in iter1 if x and y async for target2 in iter2 if a > b)\n\n# Named expression\n(x := y + 1 for y in z)\n\n# If expression\n(x if y else y for y in z)\n\n# Arguments\n\" \".join(\n sql\n for sql in (\n \"LIMIT %d\" % limit if limit else None,\n (\"OFFSET %d\" % offset) if offset else None,\n )\n)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/generator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_23.py","code":"# Simple lists\n[]\n[1]\n[1,]\n[1, 2, 3]\n[1, 2, 3,]\n\n# Mixed with indentations\n[\n]\n[\n 1\n]\n[\n 1,\n 2,\n]\n\n# Nested\n[[[1]]]\n[[1, 2], [3, 4]]\n\n# Named expression\n[x := 2]\n[x := 2,]\n[1, x := 2, 3]\n\n# Star expression\n[1, *x, 3]\n[1, *x | y, 3]\n\n# Random expressions\n[1 + 2, [1, 2, 3, 4], (a, b + c, d), {a, b, c}, {a: 1}, x := 2]\n[call1(call2(value.attr()) for element in iter)]\n[item in xs]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/list.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_24.py","code":"(name := 0)\n(name := (x * y))\n(name := 1 + 1)\n(name := (*x, y))\n(name := x if True else y)\n(name := lambda x: x)\n(name := (yield x))\n(name := (yield from x))","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/named.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_25.py","code":"(expr)\n(expr)()\n(expr)()()()\n\n(a and b or c)\n(lambda x: x)\n(x := 2)\n(yield x)\n(yield from x)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/parenthesized.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_26.py","code":"# Simple sets\n{}\n{1}\n{1,}\n{1, 2, 3}\n{1, 2, 3,}\n\n# Mixed with indentations\n{\n}\n{\n 1\n}\n{\n 1,\n 2,\n}\n\n# Nested\n{{1}}\n{{1, 2}, {3, 4}}\n\n# Named expression\n{x := 2}\n{1, x := 2, 3}\n{1, (x := 2),}\n\n# Star expression\n{1, *x, 3}\n{1, *x | y, 3}\n\n# Random expressions\n{1 + 2, (a, b), {1, 2, 3}, {a: b, **d}}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/set.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_27.py","code":"# Various combinations\nx[:]\nx[1:]\nx[:2]\nx[1:2]\nx[::]\nx[1::]\nx[:2:]\nx[1:2:]\nx[::3]\nx[1::3]\nx[:2:3]\nx[1:2:3]\n\n# Named expression\nx[y := 2]\nx[(y := 2):]\nx[y := 2,]\n\n# These are two separate slice elements\nx[1,:2,]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/slice.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_28.py","code":"# With parentheses\n()\n(())\n((()), ())\n(a,)\n(a, b)\n(a, b,)\n((a, b))\n\n# Without parentheses\na,\na, b\na, b,\n\n# Starred expression\n*a,\na, *b\n*a | b, *await x, (), *()\n(*a,)\n(a, *b)\n(*a | b, *await x, (), *())\n\n# Named expression\n(x := 1,)\n(x, y := 2)\n(x, y := 2, z)\nx, (y := 2), z\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_29.py","code":"# Simple\n-1\n+1\n~1\nnot x\n\n# Multiple\n---1\n-+~1\nnot-+~1\nnot not x\n\n# Precedence check\n- await 1\n+ await 1 ** -2\n~(1, 2)\n-1 + 2\n\n# Precedence check for `not` operator because it is higher than other unary operators\nnot a and b or not c | d and not e\nnot (x := 1)\nnot a | (not b)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/unary_op.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_30.py","code":"yield\nyield x\nyield x + 1\nyield x and y\nyield call()\nyield [1, 2]\nyield {3, 4}\nyield {x: 5}\nyield x, y\nyield (x, y)\nyield x == y\nyield (x := 1)\nyield x, *y\nyield *x,\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_31.py","code":"yield from x\nyield from x + 1\nyield from x and y\nyield from call()\nyield from [1, 2]\nyield from {3, 4}\nyield from {x: 5}\nyield from (x, y)\nyield from x == y\nyield from (x := 1)\nyield from (x, *x | y)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield_from.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_32.py","code":"@function_decorator\ndef test():\n pass\n\n\n@class_decorator\nclass Test:\n pass\n\n\n@decorator\ndef f(): ...\n\n\n@a.b.c\ndef f(): ...\n\n\n@a\n@a.b.c\ndef f(): ...\n\n\n@a\n@1 | 2\n@a.b.c\nclass T: ...\n\n\n@x := 1\n@x if True else y\n@lambda x: x\n@x and y\n@(yield x)\n@(*x, *y)\ndef f(): ...\n\n\n# This is not multiple decorators on the same line but rather a binary (`@`) expression\n@x @y\ndef foo(): ...\n\n\n@x\n\n\n@y\n\n\ndef foo(): ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/other/decorator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_33.py","code":"# These test cases specifically tests out parsing a list of with items that start with a\n# left parenthesis. This makes parsing ambiguous as to whether the left parenthesis is to\n# parenthesize the with items or part of a parenthesized expression. It's not to test the\n# with statement itself.\n\n# The following sections basically separates between which node does the\n# start parenthesis belongs to.\n\n# Parenthesized with items\n# ------------------------\n#\n# - The opening parenthesis belongs to the with statement.\n# - The range of the first with item shouldn't include the parenthesis.\nwith (item): ...\nwith (item,): ... # with a trailing comma\nwith (((item))): ...\nwith (item1, item2): ...\nwith (item1, item2,): ... # with a trailing comma\nwith ((item1), (item2), item3 as f, (item4)): ...\nwith ((item1, item2), item3): ...\nwith ((x, y) as f): ...\nwith (item1 as f1, item2 as f2): ...\nwith (item1 as f1, item2 as f2,): ... # with a trailing comma\nwith (item == 10,): ...\nwith ((item := 10)): ...\nwith ((item := 10,)): ...\nwith ((*item,)): ...\nwith ((item1 := 10), item2): ...\nwith (item1 as f, (item2 := 10)): ...\nwith (foo()): ...\nwith (foo(),): ...\nwith (foo() as f): ...\nwith (f\"{item := 42}\"): ...\nwith (f\"{(item := 42)}\"): ...\nwith ((x for x in range(10)), item): ...\nwith (item, (x for x in range(10))): ...\nwith (item, (x for x in range(10)), item): ...\nwith (data[1:2]): ...\nwith (data[1:2] as f): ...\nwith ((x for x in iter) as y): ...\n\n# Parenthesized expression\n# ------------------------\n#\n# - The opening parenthesis belongs to the context expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (item) as f: ...\nwith (item := 10): ...\nwith (item := 10) as f: ...\nwith ( item := 1 ): ...\nwith (item1 := 42), item2: ...\nwith (root + filename).read(): ... # Postfix expression\nwith (root + filename).read() as f: ... # Postfix expression\nwith (foo)(): ... # Postfix expression\nwith (foo)() as f: ... # Postfix expression\nwith (foo()) as f: ...\nwith (data[1:2]) as f: ...\nwith (1, 2, 3)[0]: ... # Postfix expression\nwith (1, 2, 3)[0] as f: ... # Postfix expression\nwith (item1), (item2): ...\nwith (open('a.py')), (open('b.py')): ...\nwith (yield x): ...\nwith ((yield x)): ...\nwith (yield from x): ...\nwith ((yield from x)): ...\nwith (yield x) as f: ...\nwith (yield x,) as f: ...\n\n\n# Tuple expression\n# ----------------\n#\n# - This is a sub-case of the parenthesized expression and requires transforming the list of\n# with items from the speculative parsing to a single with item containing a tuple expression.\n# - The opening parenthesis belongs to the tuple expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (): ...\nwith () as f: ...\nwith (item := 42,): ...\nwith (1, item := 2): ...\nwith (item1 := 10, item2): ...\nwith (item1, item2 := 2, item3) as f: ...\nwith (item,) as f: ...\nwith (*item,): ...\nwith (*item,) as f: ...\nwith (item1, item2) as f: ...\nwith (item1, item2,) as f: ...\nwith (item1, item2), item3: ...\nwith ((item1, item2), item3) as f: ...\nwith (item1,), item2, (item3, item4) as f: ...\nwith (item1, item2) as f1, item3 as f2: ...\nwith (item1, *item2): ...\nwith (item1, *item2) as f: ...\nwith (item1 := 10, *item2): ...\nwith ((item1 := 10), *item2): ...\n\n\n# Parenthesized generator expression\n# ----------------------------------\n#\n# - The opening parenthesis belongs to the generator expression\n# - The range of the with item should include the parenthesis\nwith (x for x in range(10)): ...\nwith (x async for x in range(10)): ...\nwith (x for x in range(10)), item: ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/ambiguous_lpar_with_items.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_34.py","code":"if 1: 10\nelif 2: 20\nelse: 30\n\nif True:\n 1\n ...\nif x < 1:\n ...\nelse:\n pass\n\nif a:\n pass\nelif b:\n ...\n\nif a and b:\n ...\nelif True:\n ...\nelif c:\n ...\nelif d:\n ...\nelse:\n f()\n\n# Valid test expression\nif a := b: ...\nelif a := b: ...\nif lambda x: x: ...\nelif lambda x: x: ...\nif await x: ...\nelif await x: ...\nif (yield x): ...\nelif (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/if.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_35.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_36.py","code":"return\nreturn x\nreturn *x, *y\nreturn (x := 1)\nreturn None\nreturn x and y\nreturn 1 < 2\nreturn 1, 2,\nreturn call()\nreturn attr.value()\nreturn await x\nreturn lambda x: y\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/return.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_37.py","code":"while x:\n ...\n\nwhile (x > 1) and y:\n pass\nelse:\n ...\n\nwhile x and y:\n ...\n print('Hello World!')\n\nelse:\n print('Olá, Mundo!')\n ...\n\nwhile a := b: ...\nwhile (a := b) and c: ...\nwhile lambda x: x: ...\nwhile await x: ...\n\nif True:\n while x:\n pass\n else:\n pass\nelse:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/while.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.10","idiom_id":"annotated","pep":"593","introduced_in":"3.9","form":"modern","file":"annotated/modern_01.py","code":"\"\"\"\nTests the typing.Annotated special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#annotated\n\n# > The first argument to Annotated must be a valid type\n\nfrom dataclasses import InitVar, dataclass\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Literal,\n NotRequired,\n Required,\n TypeAlias,\n TypeVar,\n TypedDict,\n Union,\n)\n\nT = TypeVar(\"T\")\n\n\nGood1: Annotated[Union[int, str], \"\"]\nGood2: Annotated[int | None, \"\"]\nGood3: Annotated[list[int], \"\"]\nGood4: Annotated[Any, \"\"]\nGood5: Annotated[tuple[int, ...] | list[int], \"\"]\nGood6: Annotated[Callable[..., int], \"\"]\nGood7: Annotated[\"int | str\", \"\"]\nGood8: Annotated[list[\"int | str\"], \"\"]\n\n\nBad1: Annotated[[int, str], \"\"] # E: invalid type expression\nBad2: Annotated[((int, str),), \"\"] # E: invalid type expression\nBad3: Annotated[[int for i in range(1)], \"\"] # E: invalid type expression\nBad4: Annotated[{\"a\": \"b\"}, \"\"] # E: invalid type expression\nBad5: Annotated[(lambda: int)(), \"\"] # E: invalid type expression\nBad6: Annotated[[int][0], \"\"] # E: invalid type expression\nBad7: Annotated[int if 1 < 3 else str, \"\"] # E: invalid type expression\nBad8: Annotated[var1, \"\"] # E: invalid type expression\nBad9: Annotated[True, \"\"] # E: invalid type expression\nBad10: Annotated[1, \"\"] # E: invalid type expression\nBad11: Annotated[list or set, \"\"] # E: invalid type expression\nBad12: Annotated[f\"{'int'}\", \"\"] # E: invalid type expression\n\n\n# > Multiple type annotations are supported (Annotated supports variadic arguments):\n\nMulti1: Annotated[int | str, 3, \"\"]\nMulti2: Annotated[int | str, 3, \"\", lambda x: x, max(1, 2)]\n\n# > Annotated must be called with at least two arguments ( Annotated[int] is not valid)\n\nBad13: Annotated[int] # E: requires at least two arguments\n\n\n# > Annotated types can be nested\n\nNested1: list[Annotated[dict[str, Annotated[str, \"\"]], \"\"]]\nNested2: Annotated[list[Annotated[dict[str, Annotated[Literal[1, 2, 3], \"\"]], \"\"]], \"\"]\n\n\n# > Annotated is not type compatible with type or type[T]\nSmallInt: TypeAlias = Annotated[int, \"\"]\n\nnot_type1: type[Any] = Annotated[int, \"\"] # E\nnot_type2: type[Any] = SmallInt # E\n\n\ndef func4(x: type[T]) -> T:\n return x()\n\n\nfunc4(Annotated[str, \"\"]) # E\nfunc4(SmallInt) # E\n\n\n# > An attempt to call Annotated (whether parameterized or not) should be\n# > treated as a type error by type checkers.\n\nAnnotated() # E\nAnnotated[int, \"\"]() # E\nSmallInt(1) # E\n\n\nclass ClassA:\n a: ClassVar[Annotated[int, \"\"]] = 1\n b: Annotated[ClassVar[int], \"\"] = 1\n c: Final[Annotated[int, \"\"]] = 1\n d: Annotated[Final[int], \"\"] = 1\n\n\n@dataclass\nclass ClassB:\n a: InitVar[Annotated[int, \"\"]]\n b: Annotated[InitVar[int], \"\"]\n\n\nclass ClassC(TypedDict):\n a: Annotated[Required[int], \"\"]\n b: Required[Annotated[int, \"\"]]\n c: Annotated[NotRequired[int], \"\"]\n d: NotRequired[Annotated[int, \"\"]]\n\n\nTA1: TypeAlias = Annotated[int | str, \"\"]\nTA2 = Annotated[Literal[1, 2], \"\"]\nTA3 = Annotated[T, \"\"]\n","source":"typing_tests","origin":"conformance/tests/qualifiers_annotated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_07.py","code":"\"\"\"\nTests the handling of builtins.type[T].\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#type\n\n\nfrom typing import Any, Callable, Generic, Type, TypeAlias, TypeVar, assert_type\n\n\nclass User:\n ...\n\n\nclass BasicUser(User):\n ...\n\n\nclass ProUser(User):\n ...\n\n\nclass TeamUser(User):\n ...\n\n\ndef func1(user_class: type) -> User:\n return user_class()\n\n\ndef func2(user_class: type[User]) -> User:\n return user_class()\n\n\nU = TypeVar(\"U\", bound=User)\n\n\ndef func3(user_class: type[U]) -> U:\n return user_class()\n\n\nassert_type(func1(TeamUser), User)\nassert_type(func2(TeamUser), User)\nassert_type(func3(TeamUser), TeamUser)\n\n\n# > Note that it is legal to use a union of classes as the parameter for type[].\n\n\ndef func4(user_class: type[BasicUser | ProUser]) -> User:\n return user_class()\n\n\nassert_type(func4(BasicUser), User)\nassert_type(func4(ProUser), User)\nfunc4(TeamUser) # E\n\n\n# > Any other special constructs like Callable are not allowed as an argument to type.\n\nT = TypeVar(\"T\")\n\n\ndef func5(x: type[T]) -> None:\n pass\n\n\nfunc5(User) # OK\nfunc5(tuple) # OK\nfunc5(Callable) # E\n\n\n# > When type is parameterized it requires exactly one parameter. Plain type\n# > without brackets, the root of Python’s metaclass hierarchy, is equivalent to type[Any].\n\nbad_type1: type[int, str] # E\n\n\nclass MyMetaA(type):\n ...\n\n\ndef func6(a: type, b: type[Any]):\n assert_type(a, type[Any])\n a = b # OK\n b = a # OK\n a = type # OK\n b = type # OK\n\n\n# > Regarding the behavior of type[Any] (or type), accessing attributes of a\n# > variable with this type only provides attributes and methods defined by\n# > type (for example, __repr__() and __mro__). Such a variable can be called\n# > with arbitrary arguments, and the return type is Any.\n\n\ndef func7(a: type, b: type[Any], c: Type, d: Type[Any]):\n assert_type(a.__mro__, tuple[type, ...])\n assert_type(a.unknown, Any)\n assert_type(a.unknown(), Any)\n\n assert_type(b.__mro__, tuple[type, ...])\n assert_type(b.unknown, Any)\n assert_type(b.unknown(), Any)\n\n assert_type(c.__mro__, tuple[type, ...])\n assert_type(c.unknown, Any)\n assert_type(c.unknown(), Any)\n\n assert_type(d.__mro__, tuple[type, ...])\n assert_type(d.unknown, Any)\n assert_type(d.unknown(), Any)\n\n\ndef func8(a: type[object], b: Type[object]):\n assert_type(a.__name__, str)\n a.unknown # E\n\n assert_type(b.__name__, str)\n b.unknown # E\n\n\n# > type is covariant in its parameter, because type[Derived] is a subtype of type[Base]:\n\n\ndef func9(pro_user_class: type[ProUser]):\n assert_type(func3(pro_user_class), ProUser)\n\n\nTA1: TypeAlias = Type\nTA2: TypeAlias = Type[Any]\nTA3: TypeAlias = type\nTA4: TypeAlias = type[Any]\n\n\ndef func10(a: TA1, b: TA2, c: TA3, d: TA4):\n assert_type(a, type[Any])\n assert_type(b, type[Any])\n assert_type(c, type[Any])\n assert_type(d, type[Any])\n\n\nTA1.unknown # E\nTA2.unknown # E\nTA3.unknown # E\nTA4.unknown # E\n\nTA7: TypeAlias = type[T]\nTA8: TypeAlias = Type[T]\n\n\ndef func11(t1: TA7[T]) -> T:\n return t1()\n\n\ndef func12(t1: TA8[T]) -> T:\n return t1()\n\n\nassert_type(func11(int), int)\nassert_type(func12(int), int)\n\n\ndef func13(v: type):\n x1: Callable[..., Any] = v # OK\n x2: Callable[[int, int], int] = v # OK\n x3: object = v # OK\n x4: type = v # OK\n x5: type[int] = v # OK\n x6: type[Any] = v # OK\n\n\nclass ClassA(Generic[T]):\n def method1(self, v: type) -> type[T]:\n return v # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_type.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_07.py","code":"\"\"\"\nTests the handling of descriptors within a dataclass.\n\"\"\"\n\n# This portion of the dataclass spec is under-specified in the documentation,\n# but its behavior can be determined from the runtime implementation.\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, TypeVar, assert_type, overload\n\nT = TypeVar(\"T\")\n\n\nclass Desc1:\n @overload\n def __get__(self, __obj: None, __owner: Any) -> \"Desc1\":\n ...\n\n @overload\n def __get__(self, __obj: object, __owner: Any) -> int:\n ...\n\n def __get__(self, __obj: object | None, __owner: Any) -> \"int | Desc1\":\n raise NotImplementedError\n\n def __set__(self, __obj: object, __value: int) -> None:\n ...\n\n\n@dataclass\nclass DC1:\n y: Desc1 = Desc1()\n\n\ndc1 = DC1(3)\n\nassert_type(dc1.y, int)\nassert_type(DC1.y, Desc1)\n\n\nclass Desc2(Generic[T]):\n @overload\n def __get__(self, instance: None, owner: Any) -> list[T]:\n ...\n\n @overload\n def __get__(self, instance: object, owner: Any) -> T:\n ...\n\n def __get__(self, instance: object | None, owner: Any) -> list[T] | T:\n raise NotImplementedError\n\n\n@dataclass\nclass DC2:\n x: Desc2[int]\n y: Desc2[str]\n z: Desc2[str] = Desc2()\n\n\nassert_type(DC2.x, list[int])\nassert_type(DC2.y, list[str])\nassert_type(DC2.z, list[str])\n\ndc2 = DC2(Desc2(), Desc2(), Desc2())\nassert_type(dc2.x, int)\nassert_type(dc2.y, str)\nassert_type(dc2.z, str)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_descriptors.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_08.py","code":"\"\"\"\nTests validation of frozen dataclass instances.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#frozen-instances\n\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass DC1:\n a: float\n b: str\n\ndc1 = DC1(1, \"\")\n\ndc1.a = 1 # E: dataclass is frozen\ndc1.b = \"\" # E: dataclass is frozen\n\n\n# This should generate an error because a non-frozen dataclass\n# cannot inherit from a frozen dataclass.\n@dataclass # E[DC2]\nclass DC2(DC1): # E[DC2]\n pass\n\n@dataclass\nclass DC3:\n a: int\n\n# This should generate an error because a frozen dataclass\n# cannot inherit from a non-frozen dataclass.\n@dataclass(frozen=True) # E[DC4]\nclass DC4(DC3): # E[DC4]\n pass\n\n\n@dataclass(frozen=True)\nclass DC1Child(DC1):\n # This should be allowed because attributes within a frozen\n # dataclass are covariant rather than invariant.\n a: int\n","source":"typing_tests","origin":"conformance/tests/dataclasses_frozen.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_09.py","code":"\"\"\"\nTests the synthesis of the __hash__ method in a dataclass.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Callable, Hashable, assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n\n\nassert_type(DC1.__hash__, None)\n\n# These should generate errors because DC1 isn't hashable.\nDC1(0).__hash__() # E\nv1: Hashable = DC1(0) # E\n\n\n@dataclass(eq=True, frozen=True)\nclass DC2:\n a: int\n\n\ndc2_hash: Callable[..., int] = DC2.__hash__ # OK\nDC2(0).__hash__() # OK\nv2: Hashable = DC2(0) # OK\n\n\n@dataclass(eq=True)\nclass DC3:\n a: int\n\n\nassert_type(DC3.__hash__, None)\n\n# These should generate errors because DC3 isn't hashable.\nDC3(0).__hash__() # E\nv3: Hashable = DC3(0) # E\n\n\n@dataclass(frozen=True)\nclass DC4:\n a: int\n\n\ndc4_hash: Callable[..., int] = DC4.__hash__ # OK\nDC4(0).__hash__() # OK\nv4: Hashable = DC4(0) # OK\n\n\n@dataclass(eq=True, unsafe_hash=True)\nclass DC5:\n a: int\n\n\ndc5_hash: Callable[..., int] = DC5.__hash__ # OK\nDC5(0).__hash__() # OK\nv5: Hashable = DC5(0) # OK\n\n\n@dataclass(eq=True)\nclass DC6:\n a: int\n\n def __hash__(self) -> int:\n return 0\n\n\ndc6_hash: Callable[..., int] = DC6.__hash__ # OK\nDC6(0).__hash__() # OK\nv6: Hashable = DC6(0) # OK\n\n\n@dataclass(frozen=True)\nclass DC7:\n a: int\n\n def __eq__(self, other) -> bool:\n return self.a == other.a\n\n\ndc7_hash: Callable[..., int] = DC7.__hash__ # OK\nDC7(0).__hash__() # OK\nv7: Hashable = DC7(0) # OK\n","source":"typing_tests","origin":"conformance/tests/dataclasses_hash.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_10.py","code":"\"\"\"\nTests inheritance rules for dataclasses.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#inheritance\n\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar\n\n\n@dataclass\nclass DC1:\n a: int\n b: str = \"\"\n\n\n@dataclass\nclass DC2(DC1):\n b: str = \"\"\n a: int = 1\n\n\ndc2_1 = DC2(1, \"\")\n\ndc2_2 = DC2()\n\n\n@dataclass\nclass DC3:\n x: float = 15.0\n y: str = \"\"\n\n\n@dataclass\nclass DC4(DC3):\n z: tuple[int] = (10,)\n x: float = 15\n\n\ndc4_1 = DC4(0.0, \"\", (1,))\n\n\n@dataclass\nclass DC5:\n # While this generates an error at runtime for the stdlib dataclass,\n # other libraries that use dataclass_transform don't have similar\n # restrictions. It is therefore not required that a type checker\n # report an error here.\n x: list[int] = [] # E?\n\n\n@dataclass\nclass DC6:\n x: int\n y: ClassVar[int] = 1\n\n\n@dataclass\nclass DC7(DC6):\n # This should generate an error because a ClassVar cannot override\n # an instance variable of the same name.\n x: ClassVar[int] # E\n\n # This should generate an error because an instance variable cannot\n # override a class variable of the same name.\n y: int # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_11.py","code":"\"\"\"\nTests the keyword-only feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY, field\n\n\n@dataclass\nclass DC1:\n a: str\n _: KW_ONLY\n b: int = 0\n\n\nDC1(\"hi\")\nDC1(a=\"hi\")\nDC1(a=\"hi\", b=1)\nDC1(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC1(\"hi\", 1) # E\n\n\n@dataclass\nclass DC2:\n b: int = field(kw_only=True, default=3)\n a: str\n\n\nDC2(\"hi\")\nDC2(a=\"hi\")\nDC2(a=\"hi\", b=1)\nDC2(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC2(\"hi\", 1) # E\n\n\n@dataclass(kw_only=True)\nclass DC3:\n a: str = field(kw_only=False)\n b: int = 0\n\n\nDC3(\"hi\")\nDC3(a=\"hi\")\nDC3(a=\"hi\", b=1)\nDC3(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC3(\"hi\", 1) # E\n\n\n@dataclass\nclass DC4(DC3):\n c: float\n\n\nDC4(\"\", 0.2, b=3)\nDC4(a=\"\", b=3, c=0.2)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_kwonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_12.py","code":"\"\"\"\nTests the match_args feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY\nfrom typing import assert_type, Literal\n\n# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method\n\n@dataclass(match_args=True)\nclass DC1:\n x: int\n _: KW_ONLY\n y: str\n\nassert_type(DC1.__match_args__, tuple[Literal['x']])\n\n# The match_args default is True\n\n@dataclass\nclass DC2:\n x: int\n\nassert_type(DC2.__match_args__, tuple[Literal['x']])\n\n# __match_args__ is created even if __init__() is not generated\n\n@dataclass(match_args=True, init=False)\nclass DC3:\n x: int = 0\n\nassert_type(DC3.__match_args__, tuple[Literal['x']])\n\n# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.\n\n@dataclass(match_args=False)\nclass DC4:\n x: int\n\nDC4.__match_args__ # E\n\n@dataclass(match_args=True)\nclass DC5:\n __match_args__ = ()\n x: int\n\nassert_type(DC5.__match_args__, tuple[()])\n","source":"typing_tests","origin":"conformance/tests/dataclasses_match_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_13.py","code":"\"\"\"\nTests the synthesized comparison methods for dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass DC1:\n a: str\n b: int\n\n\n@dataclass(order=True)\nclass DC2:\n a: str\n b: int\n\n\ndc1_1 = DC1(\"\", 0)\ndc1_2 = DC1(\"\", 0)\n\nif dc1_1 < dc1_2:\n pass\n\nif dc1_1 <= dc1_2:\n pass\n\nif dc1_1 > dc1_2:\n pass\n\nif dc1_1 >= dc1_2:\n pass\n\nif dc1_1 == dc1_2:\n pass\n\nif dc1_1 != dc1_2:\n pass\n\nif dc1_1 == None:\n pass\n\nif dc1_1 != None:\n pass\n\ndc2_1 = DC2(\"hi\", 2)\n\n# This should generate an error because the types are\n# incompatible.\nif dc1_1 < dc2_1: # E:\n pass\n\nif dc1_1 != dc2_1:\n pass\n","source":"typing_tests","origin":"conformance/tests/dataclasses_order.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_14.py","code":"\"\"\"\nTests type checking of the __post_init__ method in a dataclass.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#post-init-processing\n\nfrom dataclasses import InitVar, dataclass, field, replace\nfrom typing import assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n b: int\n x: InitVar[int]\n c: int\n y: InitVar[str]\n\n def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y\n pass\n\n\ndc1 = DC1(1, 2, 3, 4, \"\")\n\nassert_type(dc1.a, int)\nassert_type(dc1.b, int)\nassert_type(dc1.c, int)\nprint(dc1.x) # E: cannot access InitVar\nprint(dc1.y) # E: cannot access InitVar\n\n@dataclass\nclass DC2:\n x: InitVar[int]\n y: InitVar[str]\n\n def __post_init__(self, x: int) -> None: # E: missing y\n pass\n\n\n@dataclass\nclass DC3:\n _name: InitVar[str] = field()\n name: str = field(init=False)\n\n def __post_init__(self, _name: str):\n ...\n\n\n@dataclass\nclass DC4(DC3):\n _age: InitVar[int] = field()\n age: int = field(init=False)\n\n def __post_init__(self, _name: str, _age: int):\n ...\n","source":"typing_tests","origin":"conformance/tests/dataclasses_postinit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_15.py","code":"\"\"\"\nTests the slots functionality of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass\n\n# This should generate an error because __slots__ is already defined.\n@dataclass(slots=True) # E[DC1]\nclass DC1: # E[DC1]\n x: int\n\n __slots__ = ()\n\n\n@dataclass(slots=True)\nclass DC2:\n x: int\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass(slots=False)\nclass DC3:\n x: int\n\n __slots__ = (\"x\",)\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass\nclass DC4:\n __slots__ = (\"y\", \"x\")\n x: int\n y: str\n\n\nDC4(1, \"bar\")\n\n\n@dataclass(slots=True)\nclass DC5:\n a: int\n\n\nDC5.__slots__\nDC5(1).__slots__\n\n\n@dataclass\nclass DC6:\n a: int\n\n\n# This should generate an error because __slots__ is not defined.\nDC6.__slots__ # E\n\n# This should generate an error because __slots__ is not defined.\nDC6(1).__slots__ # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_slots.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_16.py","code":"\"\"\"\nTests basic handling of the dataclass factory.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html\n# Also, see https://peps.python.org/pep-0557/\n\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar, assert_type\nimport sys\n\nT = TypeVar(\"T\")\n\n\n@dataclass(order=True)\nclass InventoryItem:\n x = 0\n name: str\n unit_price: float\n quantity_on_hand: int = 0\n\n def total_cost(self) -> float:\n return self.unit_price * self.quantity_on_hand\n\n\nv1 = InventoryItem(\"soap\", 2.3)\n\n\nclass InventoryItemInitProto(Protocol):\n def __call__(\n self, name: str, unit_price: float, quantity_on_hand: int = ...\n ) -> None: ...\n\n\n# Validate the type of the synthesized __init__ method.\nx1: InventoryItemInitProto = v1.__init__\n\n# Make sure the following additional methods were synthesized.\nprint(v1.__repr__)\nprint(v1.__eq__)\nprint(v1.__ne__)\nprint(v1.__lt__)\nprint(v1.__le__)\nprint(v1.__gt__)\nprint(v1.__ge__)\n\nassert_type(v1.name, str)\nassert_type(v1.unit_price, float)\nassert_type(v1.quantity_on_hand, int)\n\nv2 = InventoryItem(\"name\") # E: missing unit_price\nv3 = InventoryItem(\"name\", \"price\") # E: incorrect type for unit_price\nv4 = InventoryItem(\"name\", 3.1, 3, 4) # E: too many arguments\n\n\n# > TypeError will be raised if a field without a default value follows a\n# > field with a default value. This is true either when this occurs in a\n# > single class, or as a result of class inheritance.\n@dataclass # E[DC1]\nclass DC1:\n a: int = 0 # E[DC1]: field with default should follow a field with no default.\n b: int # E[DC1]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC2]\nclass DC2:\n a: int = field(default=1) # E[DC2]: field with default should follow a field with no default.\n b: int # E[DC2]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC3]\nclass DC3:\n a: InitVar[int] = 0 # E[DC3]: field with default should follow a field with no default.\n b: int # E[DC3]: field with no default cannot follow field with default.\n\n\n@dataclass\nclass DC4:\n a: int = field(init=False)\n b: int\n\n\nv5 = DC4(0)\nv6 = DC4(0, 1) # E: too many parameters\n\n\n@dataclass\nclass DC5:\n a: int = field(default_factory=str) # E: type mismatch\n\n\ndef f(s: str) -> int:\n return int(s)\n\n\n@dataclass\nclass DC6:\n a: ClassVar[int] = 0\n b: str\n c: Callable[[str], int] = f\n\n\ndc6 = DC6(\"\")\nassert_type(dc6.a, int)\nassert_type(DC6.a, int)\nassert_type(dc6.b, str)\nassert_type(dc6.c, Callable[[str], int])\n\n\n@dataclass\nclass DC7:\n x: int\n\n\n@dataclass(init=False)\nclass DC8(DC7):\n y: int\n\n def __init__(self, a: DC7, y: int):\n self.__dict__ = a.__dict__\n self.y = y\n\n\na = DC7(3)\nb = DC8(a, 5)\n\n# This should generate an error because there is an extra parameter\nDC7(3, 4) # E\n\n# This should generate an error because there is one too few parameters\nDC8(a) # E\n\n\n@dataclass\nclass DC9:\n a: str = field(init=False, default=\"s\")\n b: bool = field()\n\n\n@dataclass\nclass DC10(DC9):\n a: str = field()\n b: bool = field()\n\n\n@dataclass(init=False)\nclass DC11:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC11(3)\n\n\n@dataclass(init=True)\nclass DC12:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC12(3)\n\n\n@dataclass(init=False)\nclass DC13:\n x: int\n x_squared: int\n\n\n# This should generate an error because there is no matching\n# override __init__ method and no synthesized __init__.\nDC13(3) # E\n\n\n@dataclass\nclass DC14:\n prop_1: str = field(init=False)\n prop_2: str = field(default=\"hello\")\n prop_3: str = field(default_factory=lambda: \"hello\")\n\n\n@dataclass\nclass DC15(DC14):\n prop_2: str = \"\"\n\n\ndc15 = DC15(prop_2=\"test\")\n\nassert_type(dc15.prop_1, str)\nassert_type(dc15.prop_2, str)\nassert_type(dc15.prop_3, str)\n\n\nclass DataclassProto(Protocol):\n __dataclass_fields__: ClassVar[dict[str, Any]]\n\n\nv7: DataclassProto = dc15\n\n\n@dataclass\nclass DC16(Generic[T]):\n value: T\n\n\nassert_type(DC16(1), DC16[int])\n\n\nclass DC17(DC16[str]):\n pass\n\n\nassert_type(DC17(\"\"), DC17)\n\n\n@dataclass\nclass DC18:\n x: int = field()\n # This may generate a type checker error because an unannotated field\n # will result in a runtime exception.\n y = field() # E?\n\n\n# > Dataclass fields may be conditional, via checks of the same\n# > statically-known conditions that a type-checker understands elsewhere,\n# > such as Python version:\n\n@dataclass\nclass DC19:\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nDC19(1, 2)\nDC19(1, 2, 3) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_01.py","code":"\"\"\"\nTests the handling of ClassVar and Final in dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import assert_type, ClassVar, Final\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#dataclass-semantics\n\n# > A final class variable on a dataclass must be explicitly annotated as\n# e.g. x: ClassVar[Final[int]] = 3.\n\n\n@dataclass\nclass D:\n final_no_default: Final[int]\n final_with_default: Final[str] = \"foo\"\n final_classvar: ClassVar[Final[int]] = 4\n # we don't require support for Final[ClassVar[...]] because the dataclasses\n # runtime implementation won't recognize it as a ClassVar either\n\n\n# An explicitly marked ClassVar can be accessed on the class:\nassert_type(D.final_classvar, int)\n\n# ...but not assigned to, because it's Final:\nD.final_classvar = 10 # E: can't assign to final attribute\n\n# A non-ClassVar attribute (with or without default) is a dataclass field:\nd = D(final_no_default=1, final_with_default=\"bar\")\nassert_type(d.final_no_default, int)\nassert_type(d.final_with_default, str)\n\n# ... but can't be assigned to (on the class or on an instance):\nd.final_no_default = 10 # E: can't assign to final attribute\nd.final_with_default = \"baz\" # E: can't assign to final attribute\nD.final_no_default = 10 # E: can't assign to final attribute\nD.final_with_default = \"baz\" # E: can't assign to final attribute\n","source":"typing_tests","origin":"conformance/tests/dataclasses_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_02.py","code":"\"\"\"\nTests the typing.Final special form.\n\"\"\"\n\nfrom typing import ClassVar, Final, Literal, NamedTuple, TypedDict, assert_type\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#id1\n\nID1: Final[int] = 1\n\nID2: Final = 1\nassert_type(ID2, Literal[1])\n\n# > If the right hand side is omitted, there must be an explicit type argument to Final.\n\nBAD1: Final # E: missing assignment\n\nBAD2: Final[str, int] = \"\" # E: only one type argument allowed\n\n# > There can be at most one final declaration per module or class for a given\n# > attribute.\n\n# > As self.id: Final = 1 (also optionally with a type in square brackets).\n# > This is allowed only in __init__ methods, so that the final instance\n# > attribute is assigned only once when an instance is created.\n\n\nclass ClassA:\n ID1: Final = 1\n\n # > In class bodies and stub files you can omit the right hand side and just\n # > write ID: Final[float]. If the right hand side is omitted, there must be\n # > an explicit type argument to Final.\n ID2: Final # E: missing initialization\n\n # > A final attribute declared in a class body without an initializer must\n # > be initialized in the __init__ method (except in stub files):\n ID3: Final[int] # E: missing initialization\n\n ID4: Final[int] # OK because initialized in __init__\n\n ID5: Final[int] = 0\n\n ID6: Final[int]\n\n ID7: Final[int] = 0\n\n def __init__(self, cond: bool) -> None:\n self.id1: Final = 1\n self.id2: Final[int] = 1\n\n self.ID4 = 1\n\n self.ID5 = 0 # E: Already initialized\n\n if cond:\n self.ID6 = 1\n else:\n self.ID6 = 2\n\n def method1(self) -> None:\n self.id3: Final = 1 # E: not allowed outside of __init__ method.\n self.id4: Final[int] = 1 # E: not allowed outside of __init__ method.\n\n self.ID7 = 0 # E: cannot modify Final value\n\n self.ID7 += 1 # E: cannot modify Final value\n\n\nRATE: Final = 3000\nRATE = 300 # E: Cannot redefine Final value\n\n# > There can’t be separate class-level and instance-level constants\n# > with the same name.\n\n\nclass ClassB:\n DEFAULT_ID: Final = 0\n\n\nClassB.DEFAULT_ID = 0 # E: Cannot redefined value\n\n\n# > A type checker should prevent final attributes from being overridden in a subclass:\n\n\nclass ClassC:\n BORDER_WIDTH: Final = 2.5\n\n __private: Final = 0\n\n\nclass ClassCChild(ClassC):\n BORDER_WIDTH = 2.5 # E: Cannot override Final value\n\n __private = 0 # OK\n\n\n# > Type checkers should infer a final attribute that is initialized in a class\n# > body as being a class variable. Variables should not be annotated with both\n# > ClassVar and Final. (Except in a dataclass; see dataclasses_final.py.)\n\n\nclass ClassD:\n VALUE1: Final = 1\n\n VALUE2: ClassVar[Final] = 1 # E: Final cannot be used with ClassVar\n VALUE3: Final[ClassVar] = 1 # E: Final cannot be used with ClassVar\n\n\nClassD.VALUE1 # OK\n\n\n# > Final may only be used as the outermost type in assignments or variable\n# > annotations. Using it in any other position is an error. In particular,\n# > Final can’t be used in annotations for function arguments.\n\nx: list[Final[int]] = [] # E\n\n\ndef func1(x: Final[list[int]]) -> None: # E\n ...\n\n\n# > ``Final`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithFinal(TypedDict):\n a: int\n b: Final[int] # E: Final not allowed in a TypedDict\n\n\nclass NTWithFinal(NamedTuple):\n a: int\n b: Final[int] # E: Final not allowed in a NamedTuple\n\n\n# > Type checkers should treat uses of a final name that was initialized with\n# > a literal as if it was replaced by the literal. For example, the following\n# > should be allowed:\n\nX: Final = \"x\"\nY: Final = \"y\"\nN = NamedTuple(\"N\", [(X, int), (Y, int)])\n\nN(x=3, y=4) # OK\nN(a=1) # E\nN(x=\"\", y=\"\") # E\n\n\ndef func2() -> None:\n global ID1\n\n ID1 = 2 # E: cannot modify Final value\n\n x: Final = 3\n\n x += 1 # E: cannot modify Final value\n\n a = (x := 4) # E: cannot modify Final value\n\n for x in [1, 2, 3]: # E: cannot modify Final value\n pass\n\n with open(\"FileName\") as x: # E: cannot modify Final value\n pass\n\n (a, x) = (1, 2) # E: cannot modify Final value\n\n\n# > If a module declares a ``Final`` variable and another module imports that\n# > variable in an import statement by name or wildcard, the imported symbol\n# > inherits the ``Final`` type qualifier. Any attempt to assign a different value\n# > to this symbol should be flagged as an error by a type checker.\n\n\nfrom _qualifiers_final_annotation_1 import TEN\n\nTEN = 9 # E: Cannot redefine Final value\n\nfrom _qualifiers_final_annotation_2 import *\n\nPI = 3.14159 # E: Cannot redefine Final value\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_03.py","code":"\"\"\"\nTests the @final decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#final\n\nfrom typing import final, overload\nfrom _qualifiers_final_decorator import Base3, Base4\n\n# > A type checker should prohibit any class decorated with @final from being\n# > subclassed and any method decorated with @final from being overridden in a\n# > subclass. The method decorator version may be used with all of instance\n# > methods, class methods, static methods, and properties.\n\n\n@final\nclass Base1:\n ...\n\n\nclass Derived1(Base1): # E: Cannot inherit from final class \"Base\"\n ...\n\n\nclass Base2:\n @final\n def method1(self) -> None:\n pass\n\n @final\n @classmethod\n def method2(cls) -> None:\n pass\n\n @final\n @staticmethod\n def method3() -> None:\n pass\n\n # > For overloaded methods, @final should be placed on the implementation.\n\n @overload\n def method4(self, x: int) -> int:\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @final\n def method4(self, x: int | str) -> int | str:\n return 0\n\n\nclass Derived2(Base2):\n def method1(self) -> None: # E\n pass\n\n @classmethod # E[method2]\n def method2(cls) -> None: # E[method2]\n pass\n\n @staticmethod # E[method3]\n def method3() -> None: # E[method3]\n pass\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n def method4(self, x: int | str) -> int | str: # E[method4]\n return 0\n\n\nclass Derived3(Base3):\n @overload # E[Derived3]\n def method(self, x: int) -> int: # E[Derived3]\n ...\n\n @overload # E[Derived3-2]\n @final # E[Derived3-2]: should be applied only to implementation\n def method(self, x: str) -> str: # E[Derived3-2]\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived3]\n return 0\n\n\nclass Derived4(Base4):\n @overload # E[Derived4]\n def method(self, x: int) -> int: # E[Derived4]\n ...\n\n @overload\n def method(self, x: str) -> str:\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived4]\n return 0\n\n\nclass Base5_1:\n ...\n\n\nclass Base5_2:\n @final\n def method(self, v: int) -> None:\n ...\n\n\n# Test multiple inheritance case.\nclass Derived5(Base5_1, Base5_2):\n def method(self) -> None: # E\n ...\n\n\n# > It is an error to use @final on a non-method function.\n\n\n@final # E[func]: not allowed on non-method function.\ndef func1() -> int: # E[func]\n return 0\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_decorator.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_04.py","code":"\"\"\"\nTests the use of Final values when used with TypedDicts.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#use-of-final-values-and-literal-types\n\nfrom typing import Final, Literal, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\n# > Type checkers should allow final names (PEP 591) with string values to be\n# > used instead of string literals in operations on TypedDict objects.\nYEAR: Final = \"year\"\n\nm: Movie = {\"name\": \"Alien\", \"year\": 1979}\nyears_since_epoch = m[YEAR] - 1970\n\n\n# > An expression with a suitable literal type (PEP 586) can be used instead of\n# > a literal value.\ndef get_value(movie: Movie, key: Literal[\"year\", \"name\"]) -> int | str:\n return movie[key]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_04.py","code":"\"\"\"\nTests interactions between Literal types and other typing features.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#interactions-with-other-types-and-features\nfrom enum import Enum\nfrom typing import IO, Any, Final, Generic, Literal, TypeVar, LiteralString, assert_type, overload\n\n\ndef func1(v: tuple[int, str, list[bool]], a: Literal[0], b: Literal[5], c: Literal[-5]):\n assert_type(v[a], int)\n assert_type(v[2], list[bool])\n\n v[b] # E: index out of range\n v[c] # E: index out of range\n v[4] # E: index out of range\n v[-4] # E: index out of range\n\n\n_PathType = str | bytes | int\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"r\", \"w\", \"a\", \"x\", \"r+\", \"w+\", \"a+\", \"x+\"],\n) -> IO[str]:\n ...\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"rb\", \"wb\", \"ab\", \"xb\", \"r+b\", \"w+b\", \"a+b\", \"x+b\"],\n) -> IO[bytes]:\n ...\n\n\n@overload\ndef open(path: _PathType, mode: str) -> IO[Any]:\n ...\n\n\ndef open(path: _PathType, mode: Any) -> Any:\n raise NotImplementedError\n\n\nassert_type(open(\"path\", \"r\"), IO[str])\nassert_type(open(\"path\", \"wb\"), IO[bytes])\nassert_type(open(\"path\", \"other\"), IO[Any])\n\n\nA = TypeVar(\"A\", bound=int)\nB = TypeVar(\"B\", bound=int)\nC = TypeVar(\"C\", bound=int)\n\n\nclass Matrix(Generic[A, B]):\n def __add__(self, other: \"Matrix[A, B]\") -> \"Matrix[A, B]\":\n raise NotImplementedError\n\n def __matmul__(self, other: \"Matrix[B, C]\") -> \"Matrix[A, C]\":\n raise NotImplementedError\n\n def transpose(self) -> \"Matrix[B, A]\":\n raise NotImplementedError\n\n\ndef func2(a: Matrix[Literal[2], Literal[3]], b: Matrix[Literal[3], Literal[7]]):\n c = a @ b\n assert_type(c, Matrix[Literal[2], Literal[7]])\n\n\nT = TypeVar(\"T\", Literal[\"a\"], Literal[\"b\"], Literal[\"c\"])\nS = TypeVar(\"S\", bound=Literal[\"foo\"])\n\n\nclass Status(Enum):\n SUCCESS = 0\n INVALID_DATA = 1\n FATAL_ERROR = 2\n\n\ndef parse_status1(s: str | Status) -> None:\n if s is Status.SUCCESS:\n assert_type(s, Literal[Status.SUCCESS])\n elif s is Status.INVALID_DATA:\n assert_type(s, Literal[Status.INVALID_DATA])\n elif s is Status.FATAL_ERROR:\n assert_type(s, Literal[Status.FATAL_ERROR])\n else:\n assert_type(s, str)\n\n\n# > Type checkers may optionally perform additional analysis for both\n# > enum and non-enum Literal types beyond what is described in the section above.\n#\n# > For example, it may be useful to perform narrowing based on things\n# > like containment or equality checks:\n\ndef expects_bad_status(status: Literal[\"MALFORMED\", \"ABORTED\"]):\n ...\n\n\ndef expects_pending_status(status: Literal[\"PENDING\"]):\n ...\n\n\ndef parse_status2(status: LiteralString) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n\n# Narrowing `str` to `Literal` strings is unsound given the possiblity of\n# user-defined `str` subclasses that could have custom equality semantics,\n# but is explicitly listed by the spec as optional analysis that type checkers\n# may perform.\ndef parse_status3(status: str) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n\nfinal_val1: Final = 3\nassert_type(final_val1, Literal[3])\n\nfinal_val2: Final = True\nassert_type(final_val2, Literal[True])\n","source":"typing_tests","origin":"conformance/tests/literals_interactions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_05.py","code":"\"\"\"\nTests legal and illegal parameterizations of Literal.\n\"\"\"\n\n# > Literal must be parameterized with at least one type.\n\nfrom typing import Any, Literal, TypeVar\nfrom enum import Enum\n\n\nclass Color(Enum):\n RED = 0\n GREEN = 1\n BLUE = 2\n\n\ngood1: Literal[26]\ngood2: Literal[0x1A]\ngood3: Literal[-4]\ngood4: Literal[+5]\ngood5: Literal[\"hello world\"]\ngood6: Literal[b\"hello world\"]\ngood7: Literal[\"hello world\"]\ngood8: Literal[True]\ngood9: Literal[Color.RED]\ngood10: Literal[None]\n\nReadOnlyMode = Literal[\"r\", \"r+\"]\nWriteAndTruncateMode = Literal[\"w\", \"w+\", \"wt\", \"w+t\"]\nWriteNoTruncateMode = Literal[\"r+\", \"r+t\"]\nAppendMode = Literal[\"a\", \"a+\", \"at\", \"a+t\"]\n\nAllModes = Literal[ReadOnlyMode, WriteAndTruncateMode, WriteNoTruncateMode, AppendMode]\n\ngood11: Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n\nvariable = 3\nT = TypeVar(\"T\")\n\n# > Arbitrary expressions [are illegal]\nbad1: Literal[3 + 4] # E\nbad2: Literal[\"foo\".replace(\"o\", \"b\")] # E\nbad3: Literal[4 + 3j] # E\nbad4: Literal[~5] # E\nbad5: Literal[not False] # E\nbad6: Literal[(1, \"foo\", \"bar\")] # E\nbad7: Literal[{\"a\": \"b\", \"c\": \"d\"}] # E\nbad8: Literal[int] # E\nbad9: Literal[variable] # E\nbad10: Literal[T] # E\nbad11: Literal[3.14] # E\nbad12: Literal[Any] # E\nbad13: Literal[...] # E\n\n\ndef my_function(x: Literal[1 + 2]) -> int: # E\n return x * 3\n\n\nx: Literal # E\ny: Literal[my_function] = my_function # E\n\n\ndef func2(a: Literal[Color.RED]):\n x1: Literal[\"Color.RED\"] = a # E\n\n x2: \"Literal[Color.RED]\" = a # OK\n","source":"typing_tests","origin":"conformance/tests/literals_parameterizations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_06.py","code":"\"\"\"\nTests the semantics of the Literal special form.\n\"\"\"\n\nfrom typing import Literal\nfrom typing import Literal as L\n\n\nv1: Literal[3] = 3\nv2: Literal[3] = 4 # E\n\nv3: L[-3] = -3\n\n\n# > Literal[20] and Literal[0x14] are equivalent\ndef func1(a: Literal[20], b: Literal[0x14], c: Literal[0b10100]):\n x1: Literal[0x14] = a\n x2: Literal[0x14] = b\n x3: Literal[0x14] = c\n\n\n# > Literal[0] and Literal[False] are not equivalent\ndef func2(a: Literal[0], b: Literal[False]):\n x1: Literal[False] = a # E\n x2: Literal[0] = b # E\n\n\n# > Given some value v that is a member of type T, the type Literal[v] shall\n# > be treated as a subtype of T. For example, Literal[3] is a subtype of int.\ndef func3(a: L[3, 4, 5]):\n b = a.__add__(3)\n c = a + 3\n a += 3 # E\n\n\n# > When a Literal is parameterized with more than one value, it’s treated\n# > as exactly equivalent to the union of those types.\ndef func4(a: L[None, 3] | L[3, \"foo\", b\"bar\", True]):\n x1: Literal[3, b\"bar\", True, \"foo\", None] = a\n a = x1\n","source":"typing_tests","origin":"conformance/tests/literals_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_01.py","code":"\"\"\"\nTests basic usage of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#paramspec-variables\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeAlias\n\nP = ParamSpec(\"P\") # OK\nWrongName = ParamSpec(\"NotIt\") # E: name inconsistency\n\n\n# > Valid use locations\n\nTA1: TypeAlias = P # E\n\nTA2: TypeAlias = Callable[P, None] # OK\nTA3: TypeAlias = Callable[Concatenate[int, P], None] # OK\nTA4: TypeAlias = Callable[..., None] # OK\nTA5: TypeAlias = Callable[..., None] # OK\n\n\ndef func1(x: P) -> P: # E\n raise NotImplementedError\n\n\ndef func2(x: Concatenate[int, P]) -> int: # E\n raise NotImplementedError\n\n\ndef func3(x: list[P]) -> None: # E\n ...\n\n\ndef func4(x: Callable[[int, str], P]) -> None: # E\n ...\n\n\ndef func5(*args: P, **kwargs: P) -> None: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_02.py","code":"\"\"\"\nTests the usage of a ParamSpec and its components (P.args, P.kwargs).\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#the-components-of-a-paramspec\n\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef puts_p_into_scope1(f: Callable[P, int]) -> None:\n def inner(*args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def mixed_up(*args: P.kwargs, **kwargs: P.args) -> None: # E\n pass\n\n def misplaced1(x: P.args) -> None: # E\n pass\n\n def bad_kwargs1(*args: P.args, **kwargs: P.args) -> None: # E\n pass\n\n def bad_kwargs2(*args: P.args, **kwargs: Any) -> None: # E\n pass\n\n\ndef out_of_scope(*args: P.args, **kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef puts_p_into_scope2(f: Callable[P, int]) -> None:\n stored_args: P.args # E\n stored_kwargs: P.kwargs # E\n\n def just_args(*args: P.args) -> None: # E\n pass\n\n def just_kwargs(**kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef decorator(f: Callable[P, int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n assert_type(f(*args, **kwargs), int) # OK\n\n f(*kwargs, **args) # E\n\n f(1, *args, **kwargs) # E\n\n return foo # OK\n\n\ndef add(f: Callable[P, int]) -> Callable[Concatenate[str, P], None]:\n def foo(s: str, *args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def bar(*args: P.args, s: str, **kwargs: P.kwargs) -> None: # E\n pass\n\n return foo # OK\n\n\ndef remove(f: Callable[Concatenate[int, P], int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n f(1, *args, **kwargs) # OK\n\n f(*args, 1, **kwargs) # E\n\n f(*args, **kwargs) # E\n\n return foo # OK\n\n\ndef outer(f: Callable[P, None]) -> Callable[P, None]:\n def foo(x: int, *args: P.args, **kwargs: P.kwargs) -> None:\n f(*args, **kwargs)\n\n def bar(*args: P.args, **kwargs: P.kwargs) -> None:\n foo(1, *args, **kwargs) # OK\n foo(x=1, *args, **kwargs) # E\n\n return bar\n\n\ndef twice(f: Callable[P, int], *args: P.args, **kwargs: P.kwargs) -> int:\n return f(*args, **kwargs) + f(*args, **kwargs)\n\n\ndef a_int_b_str(a: int, b: str) -> int:\n return 0\n\n\ntwice(a_int_b_str, 1, \"A\") # OK\ntwice(a_int_b_str, b=\"A\", a=1) # OK\ntwice(a_int_b_str, \"A\", 1) # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_components.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_03.py","code":"\"\"\"\nTests semantics of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#semantics\n\n\nfrom typing import Callable, Concatenate, Generic, ParamSpec, TypeVar, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef changes_return_type_to_str(x: Callable[P, int]) -> Callable[P, str]:\n raise NotImplementedError\n\n\ndef returns_int(a: str, b: bool, /) -> int:\n raise NotImplementedError\n\n\nf1 = changes_return_type_to_str(returns_int)\nassert_type(f1, Callable[[str, bool], str])\n\nv1 = f1(\"A\", True) # OK\nassert_type(v1, str)\nf1(a=\"A\", b=True) # E: positional-only\nf1(\"A\", \"A\") # E: wrong type\n\n\ndef func1(x: Callable[P, int], y: Callable[P, int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\ndef x_y(x: int, y: str) -> int:\n raise NotImplementedError\n\n\ndef y_x(y: int, x: str) -> int:\n raise NotImplementedError\n\n\nf2 = func1(x_y, x_y)\nassert_type(f2(1, \"\"), bool)\nassert_type(f2(y=\"\", x=1), bool)\n\nf3 = func1(x_y, y_x) # E?: Could return (a: int, b: str, /) -> bool\n# (a callable with two positional-only parameters)\n# This works because both callables have types that are\n# behavioral subtypes of Callable[[int, str], int]\n# Also OK for type checkers to reject this.\n\n\ndef keyword_only_x(*, x: int) -> int:\n raise NotImplementedError\n\n\ndef keyword_only_y(*, y: int) -> int:\n raise NotImplementedError\n\n\nfunc1(keyword_only_x, keyword_only_y) # E\n\n\nU = TypeVar(\"U\")\n\n\nclass Y(Generic[U, P]):\n f: Callable[P, str]\n prop: U\n\n def __init__(self, f: Callable[P, str], prop: U) -> None:\n self.f = f\n self.prop = prop\n\n\ndef callback_a(q: int, /) -> str:\n raise NotImplementedError\n\n\ndef func(x: int) -> None:\n y1 = Y(callback_a, x)\n assert_type(y1, Y[int, [int]])\n y2 = y1.f\n assert_type(y2, Callable[[int], str])\n\n\ndef bar(x: int, *args: bool) -> int:\n raise NotImplementedError\n\n\ndef add(x: Callable[P, int]) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\na1 = add(bar) # Should return (a: str, /, x: int, *args: bool) -> bool\nassert_type(a1(\"\", 1, False, True), bool)\nassert_type(a1(\"\", x=1), bool)\na1(1, x=1) # E\n\n\ndef remove(x: Callable[Concatenate[int, P], int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\nr1 = remove(bar) # Should return (*args: bool) -> bool\nassert_type(r1(False, True, True), bool)\nassert_type(r1(), bool)\nr1(1) # E\n\n\ndef transform(\n x: Callable[Concatenate[int, P], int]\n) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\nt1 = transform(bar) # Should return (a: str, /, *args: bool) -> bool\nassert_type(t1(\"\", True, False, True), bool)\nassert_type(t1(\"\"), bool)\nt1(1) # E\n\n\ndef expects_int_first(x: Callable[Concatenate[int, P], int]) -> None:\n ...\n\n\n@expects_int_first # E\ndef one(x: str) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef two(*, x: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef three(**kwargs: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # OK\ndef four(*args: int) -> int:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_04.py","code":"\"\"\"\nTests the handling of a ParamSpec specialization.\n\"\"\"\n\nfrom typing import Any, Callable, Concatenate, Generic, ParamSpec, TypeVar, cast\n\n\nT = TypeVar(\"T\")\nP1 = ParamSpec(\"P1\")\nP2 = ParamSpec(\"P2\")\n\n\nclass ClassA(Generic[T, P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\nclass ClassB(ClassA[T, P1], Generic[T, P1, P2]):\n f1: Callable[P1, int] = cast(Any, \"\")\n f2: Callable[P2, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\ndef func20(x: ClassA[int, P2]) -> str: # OK\n return \"\"\n\n\ndef func21(x: ClassA[int, Concatenate[int, P2]]) -> str: # OK\n return \"\"\n\n\ndef func22(x: ClassB[int, [int, bool], ...]) -> str: # OK\n return \"\"\n\n\ndef func23(x: ClassA[int, ...]) -> str: # OK\n return \"\"\n\n\ndef func24(x: ClassB[int, [], []]) -> str: # OK\n return \"\"\n\n\ndef func25(x: ClassA[int, int]) -> str: # E\n return \"\"\n\n\nclass ClassC(Generic[P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n\n\ndef func30(x: ClassC[[int, str, bool]]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n\n\ndef func31(x: ClassC[int, str, bool]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_01.py","code":"\"\"\"\nTests the handling of class objects as implementations of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#type-and-class-objects-vs-protocols\n\n# > Variables and parameters annotated with Type[Proto] accept only concrete\n# (non-protocol) subtypes of Proto.\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Protocol\n\n\nclass Proto(Protocol):\n @abstractmethod\n def meth(self) -> int:\n ...\n\n\nclass Concrete:\n def meth(self) -> int:\n return 42\n\n\ndef fun(cls: type[Proto]) -> int:\n return cls().meth() # OK\n\n\nfun(Proto) # E\nfun(Concrete) # OK\n\n\nvar: type[Proto]\nvar = Proto # E\nvar = Concrete # OK\nvar().meth() # OK\n\n\n# > A class object is considered an implementation of a protocol if accessing\n# > all members on it results in types compatible with the protocol members.\n\n\nclass ProtoA1(Protocol):\n def method1(self, x: int) -> int:\n ...\n\n\nclass ProtoA2(Protocol):\n def method1(_self, self: Any, x: int) -> int:\n ...\n\n\nclass ConcreteA:\n def method1(self, x: int) -> int:\n return 0\n\n\npa1: ProtoA1 = ConcreteA # E: signatures don't match\npa2: ProtoA2 = ConcreteA # OK\n\n\nclass ProtoB1(Protocol):\n @property\n def prop1(self) -> int:\n ...\n\n\nclass ConcreteB:\n @property\n def prop1(self) -> int:\n return 0\n\n\npb1: ProtoB1 = ConcreteB # E\n\n\nclass ProtoC1(Protocol):\n attr1: ClassVar[int]\n\n\nclass ProtoC2(Protocol):\n attr1: int\n\n\nclass ConcreteC1:\n attr1: ClassVar[int] = 1\n\n\nclass ConcreteC2:\n attr1: int = 1\n\n\nclass CMeta(type):\n attr1: int\n\n def __init__(self, *args, **kwargs) -> None:\n self.attr1: int = 1\n\n\nclass ConcreteC3(metaclass=CMeta):\n pass\n\n\npc1: ProtoC1 = ConcreteC1 # E\npc2: ProtoC2 = ConcreteC1 # OK\npc3: ProtoC1 = ConcreteC2 # E\npc4: ProtoC2 = ConcreteC2 # E\npc5: ProtoC1 = ConcreteC3 # E?: Explicit ClassVar matching is unspecified\npc6: ProtoC2 = ConcreteC3 # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_class_objects.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_02.py","code":"\"\"\"\nTests the basic definition rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#defining-a-protocol\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Iterable, NamedTuple, Protocol, Sequence\nfrom dataclasses import dataclass\n\n\nclass SupportsClose(Protocol):\n def close(self) -> None:\n ...\n\n\nclass Resource:\n def close(self) -> None:\n pass\n\n\ndef close_all(things: Iterable[SupportsClose]) -> None:\n for t in things:\n t.close()\n\n\nf = open(\"foo.txt\")\nr = Resource()\nclose_all([f, r]) # OK\nclose_all([1]) # E: 'int' has no 'close' method\n\n\nclass Example(Protocol):\n def first(self) -> int: # This is a protocol member\n return 42\n\n @abstractmethod\n def second(self) -> int: # Method without a default implementation\n raise NotImplementedError\n\n # > Static methods, class methods, and properties are equally allowed in protocols.\n\n @staticmethod\n def third() -> int:\n ...\n\n @classmethod\n def fourth(cls) -> int:\n ...\n\n @property\n def fifth(self) -> int:\n ...\n\n\n# > To define a protocol variable, one can use PEP 526 variable annotations\n# > in the class body. Additional attributes only defined in the body of a\n# > method by assignment via self are not allowed.\n\n\nclass Template(Protocol):\n name: str # This is a protocol member\n value: int = 0 # This one too (with default)\n\n def method(self) -> None:\n self.name = \"name\" # OK\n self.temp: list[int] = [] # E: use of self variables not allowed\n\n\nclass Concrete:\n def __init__(self, name: str, value: int) -> None:\n self.name = name\n self.value = value\n\n def method(self) -> None:\n return\n\n\nvar: Template = Concrete(\"value\", 42) # OK\n\n\n# > To distinguish between protocol class variables and protocol instance\n# > variables, the special ClassVar annotation should be used as specified\n# > by PEP 526. By default, protocol variables as defined above are considered\n# > readable and writable. To define a read-only protocol variable, one can\n# > use an (abstract) property.\n\n\nclass Template2(Protocol):\n val1: ClassVar[Sequence[int]]\n\n\nclass Concrete2_Good1:\n val1: ClassVar[Sequence[int]] = [2]\n\n\nclass Concrete2_Bad1:\n ...\n\n\nclass Concrete2_Bad2:\n val1: Sequence[float] = [2]\n\n\nclass Concrete2_Bad3:\n val1: list[int] = [2]\n\n\nclass Concrete2_Bad4:\n val1: Sequence[int] = [2]\n\n\nv2_good1: Template2 = Concrete2_Good1() # OK\nv2_bad1: Template2 = Concrete2_Bad1() # E\nv2_bad2: Template2 = Concrete2_Bad2() # E\nv2_bad3: Template2 = Concrete2_Bad3() # E\nv2_bad4: Template2 = Concrete2_Bad4() # E?: Explicit ClassVar matching is unspecified\n\n\nclass Template3(Protocol):\n val1: Sequence[int]\n\n\nclass Concrete3_Good1:\n val1: Sequence[int] = [0]\n\n\nclass Concrete3_Good2:\n def __init__(self) -> None:\n self.val1: Sequence[int] = [0]\n\n\nclass Concrete3_Bad1:\n ...\n\n\nclass Concrete3_Bad2:\n val1: ClassVar[Sequence[int]] = [0]\n\n\nclass Concrete3_Bad3:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete3_Bad4:\n val1: Sequence[float] = [0]\n\n\nclass Concrete3_Bad5:\n val1: list[int] = [0]\n\n\nv3_good1: Template3 = Concrete3_Good1() # OK\nv3_bad1: Template3 = Concrete3_Bad1() # E\nv3_bad2: Template3 = Concrete3_Bad2() # E\nv3_bad3: Template3 = Concrete3_Bad3() # E\nv3_bad4: Template3 = Concrete3_Bad4() # E\nv3_bad5: Template3 = Concrete3_Bad5() # E\n\n\nclass Template4(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n\nclass Concrete4_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete4_Good2:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete4_Good3:\n val1: Sequence[float] = [0]\n\n\nclass Concrete4_Good4:\n val1: Sequence[int] = [0]\n\n\nclass Concrete4_Good5:\n val1: list[float] = [0]\n\n\nclass Concrete4_Good6(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete4_Good7:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete4_Bad1:\n def val1(self) -> Sequence[int]: # Not a property\n return [0]\n\n\nclass Concrete4_Bad2:\n ...\n\n\nv4_good1: Template4 = Concrete4_Good1() # OK\nv4_good2: Template4 = Concrete4_Good2() # OK\nv4_good3: Template4 = Concrete4_Good3() # OK\nv4_good4: Template4 = Concrete4_Good4() # OK\nv4_good5: Template4 = Concrete4_Good5() # OK\nv4_good6: Template4 = Concrete4_Good6() # OK\nv4_good7: Template4 = Concrete4_Good7() # OK\nv4_bad1: Template4 = Concrete4_Bad1() # E\nv4_bad2: Template4 = Concrete4_Bad2() # E\n\n\nclass Template5(Protocol):\n def method1(self, a: int, b: int) -> float:\n ...\n\n\nclass Concrete5_Good1:\n def method1(self, a: float, b: float) -> int:\n return 0\n\n\nclass Concrete5_Good2:\n def method1(self, *args: float, **kwargs: float) -> Any:\n return 0.0\n\n\nclass Concrete5_Good3:\n def method1(self, a, b) -> Any:\n return 0.0\n\n\nclass Concrete5_Good4:\n @classmethod\n def method1(cls, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Good5:\n @staticmethod\n def method1(a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad1:\n def method1(self, a, c) -> int:\n return 0\n\n\nclass Concrete5_Bad2:\n def method1(self, a: int, c: int) -> int:\n return 0\n\n\nclass Concrete5_Bad3:\n def method1(self, *, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad4:\n def method1(self, a: int, b: int, /) -> float:\n return 0\n\n\nclass Concrete5_Bad5:\n @staticmethod\n def method1(self, a: int, b: int) -> float:\n return 0\n\n\nv5_good1: Template5 = Concrete5_Good1() # OK\nv5_good2: Template5 = Concrete5_Good2() # OK\nv5_good3: Template5 = Concrete5_Good3() # OK\nv5_good4: Template5 = Concrete5_Good4() # OK\nv5_good5: Template5 = Concrete5_Good5() # OK\nv5_bad1: Template5 = Concrete5_Bad1() # E\nv5_bad2: Template5 = Concrete5_Bad2() # E\nv5_bad3: Template5 = Concrete5_Bad3() # E\nv5_bad4: Template5 = Concrete5_Bad4() # E\nv5_bad5: Template5 = Concrete5_Bad5() # E\n\n\nclass Template6(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n ...\n\n\nclass Concrete6_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n pass\n\n\nclass Concrete6_Good2:\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete6_Good3:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete6_Bad1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete6_Bad2(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=True)\nclass Concrete6_Bad3:\n val1: Sequence[float] = (0,)\n\n\nv6_good1: Template6 = Concrete6_Good1() # OK\nv6_good2: Template6 = Concrete6_Good2() # OK\nv6_good3: Template6 = Concrete6_Good3() # OK\nv6_bad1: Template6 = Concrete6_Bad1() # E\nv6_bad2: Template6 = Concrete6_Bad2() # E: named tuple is immutable\nv6_bad3: Template6 = Concrete6_Bad3() # E: dataclass is frozen\n\n\n# The specification leaves two possible interpretations of a ClassVar protocol\n# member. One interpretation requires the implementing attribute to be explicitly\n# declared with ClassVar. The other interpretation imposes only structural\n# requirements: the attribute must be readable and writable on the class object\n# and readable on instances of the class. Both interpretations therefore require\n# the following assignments to be rejected.\n\n\nclass Template7(Protocol):\n val1: ClassVar[int]\n\n\nclass Concrete7_Bad1:\n def __init__(self) -> None:\n self.val1: int = 42\n\n\nclass Concrete7Meta(type):\n val1: int = 42\n\n\nclass Concrete7_Bad2(metaclass=Concrete7Meta):\n pass\n\n\nv7_bad1: Template7 = Concrete7_Bad1() # E: val1 is not readable on the class object\nv7_bad2: Template7 = Concrete7_Bad2() # E: val1 is not readable on instances\n","source":"typing_tests","origin":"conformance/tests/protocols_definition.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_03.py","code":"\"\"\"\nTests the handling of explicit protocol classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#explicitly-declaring-implementation\n\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar, Protocol\n\n\nclass PColor(Protocol):\n @abstractmethod\n def draw(self) -> str:\n ...\n\n def complex_method(self) -> int:\n return 1\n\n\nclass NiceColor(PColor):\n def draw(self) -> str:\n return \"deep blue\"\n\n\nclass BadColor(PColor):\n def draw(self) -> str:\n return super().draw() # E: no default implementation\n\n\nclass ImplicitColor: # Note no 'PColor' base here\n def draw(self) -> str:\n return \"probably gray\"\n\n def complex_method(self) -> int:\n return 0\n\n\nv1: PColor = NiceColor() # OK\nv2: PColor = ImplicitColor() # OK\n\n\nclass RGB(Protocol):\n rgb: tuple[int, int, int]\n other: int\n\n @abstractmethod\n def intensity(self) -> int:\n return 1\n\n def transparency(self) -> int:\n ...\n\n\nclass Point(RGB):\n def __init__(self, red: int, green: int, blue: str) -> None:\n self.rgb = red, green, blue # E: 'blue' must be 'int'\n self.other = 0\n\n\np = Point(0, 0, \"\") # E: Cannot instantiate abstract class\n\n\nclass Proto1(Protocol):\n cm1: ClassVar[int]\n cm2: ClassVar[int] = 0\n\n im1: int\n im2: int = 2\n im3: int\n\n def __init__(self):\n self.im3 = 3\n\n\nclass Proto2(Protocol):\n cm10: int\n\n\nclass Proto3(Proto2, Protocol):\n cm11: int\n\n\nclass Concrete1(Proto1):\n def __init__(self):\n self.im1 = 1\n self.im3 = 3\n\n\nc1 = Concrete1() # E: cannot instantiate abstract class\n\n\nclass Concrete2(Proto1):\n cm1 = 3\n im1 = 0\n\n\nc2 = Concrete2()\n\n\nclass Concrete3(Proto1, Proto3):\n cm1 = 3\n\n def __init__(self):\n self.im1 = 0\n self.cm10 = 10\n self.cm11 = 11\n\n\nc3 = Concrete3()\n\n\nclass Concrete4(Proto1, Proto3):\n cm1 = 3\n cm10 = 3\n\n def __init__(self):\n self.im1 = 3\n self.im10 = 10\n self.cm11 = 3\n\n\nc4 = Concrete4()\n\n\nclass Proto5(Protocol):\n def method1(self) -> int:\n ...\n\n\nclass Concrete5(Proto5):\n pass\n\n\nc5 = Concrete5() # E: cannot instantiate abstract class\n\n\nclass Proto6(Protocol):\n x: int\n\n\nclass Mixin:\n x = 3\n\n\nclass Concrete6(Mixin, Proto6):\n pass\n\n\nclass Proto7(Protocol):\n @abstractmethod\n def method1(self):\n ...\n\n\nclass Mixin7(Proto7, ABC):\n def method1(self) -> None:\n pass\n\n\nclass Concrete7A(Proto7):\n pass\n\n\nc7a = Concrete7A() # E: cannot instantiate abstract class\n\n\nclass Concrete7B(Mixin7, Proto7):\n pass\n\n\nc7b = Concrete7B()\n","source":"typing_tests","origin":"conformance/tests/protocols_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_04.py","code":"\"\"\"\nTests the handling of generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\n\nfrom typing import Callable, Generic, Iterator, Protocol, Self, TypeVar, assert_type\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Iterable(Protocol[T_co]):\n def __iter__(self) -> Iterator[T_co]:\n ...\n\n\n# > Protocol[T, S, ...] is allowed as a shorthand for Protocol, Generic[T, S, ...].\n# In particular, the implicit order of type parameters is dictated by\n# the order in which they appear in the `Protocol` subscript.\n\n\nclass Proto1(Iterable[T_co], Protocol[S, T_co]):\n def method1(self, x: S) -> S:\n ...\n\n\nclass Concrete1:\n def __iter__(self) -> Iterator[int]:\n return (x for x in [1, 2, 3])\n\n def method1(self, x: str) -> str:\n return \"\"\n\n\np1: Proto1[str, int] = Concrete1() # OK\np2: Proto1[int, str] = Concrete1() # E: incompatible type\n\n\n# > It is an error to combine the shorthand with Generic[T, S, ...]\nclass Proto2(Protocol[T_co], Generic[T_co]): # E\n ...\n\n\n# > User-defined generic protocols support explicitly declared variance.\nclass Box(Protocol[T_co]):\n def content(self) -> T_co:\n ...\n\n\ndef func1(box_int: Box[int], box_float: Box[float]):\n v1: Box[float] = box_int # OK\n v2: Box[int] = box_float # E\n\n\nclass Sender(Protocol[T_contra]):\n def send(self, data: T_contra) -> int:\n return 0\n\n\ndef func2(sender_int: Sender[int], sender_float: Sender[float]):\n v1: Sender[int] = sender_float # OK\n v2: Sender[float] = sender_int # E\n\n\nclass AttrProto(Protocol[T]):\n attr: T\n\n\ndef func3(attr_int: AttrProto[int], attr_float: AttrProto[float]):\n v1: AttrProto[float] = attr_int # E\n v2: AttrProto[int] = attr_float # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n# > The self-types in protocols follow the rules for other methods.\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n# > In addition, the first argument in an instance method can be annotated\n# > with a type variable. In this case the return type may use the same\n# > type variable, thus making that method a generic function.\n\n\nT_bounded = TypeVar(\"T_bounded\", bound=\"HasParent\")\n\n\nclass HasParent(Protocol):\n def get_parent(self: T_bounded) -> T_bounded:\n ...\n\n\nGenericHasParent = TypeVar(\"GenericHasParent\", bound=HasParent)\n\n\ndef generic_get_parent(n: GenericHasParent) -> GenericHasParent:\n return n.get_parent()\n\n\nclass ConcreteHasParent:\n def get_parent(self) -> Self:\n return self\n\n\nparent = generic_get_parent(ConcreteHasParent()) # OK\nassert_type(parent, ConcreteHasParent)\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > `Self` is valid within Protocols, similar to its use in classes:\n\n\nclass HasParentProperty(Protocol):\n @property\n def parent(self) -> Self:\n ...\n\n\nclass ConcreteParentProperty:\n @property\n def parent(self) -> Self:\n return self\n\n\nclass InvalidParentProperty:\n @property\n def parent(self) -> HasParentProperty:\n return ConcreteParentProperty()\n\n\nhp1: HasParentProperty = ConcreteParentProperty() # OK\nhp2: HasParentProperty = InvalidParentProperty() # E\n\n\n\nclass HasMethod(Protocol):\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n ...\n\n\nclass ConcreteHasMethod:\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n return \"\"\n\n\nclass InvalidHasMethod:\n def m(self, item: int, callback: Callable[[int], str]) -> str:\n return \"\"\n\n\nhm1: HasMethod = ConcreteHasMethod() # OK\nhm2: HasMethod = InvalidHasMethod() # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > Checking a class for assignability to a protocol: If a protocol uses `Self`\n# > in methods or attribute annotations, then a class `Foo` is assignable\n# > to the protocol if its corresponding methods and attribute annotations use\n# > either `Self` or `Foo` or any of `Foo`'s subclasses.\n\n\nclass HasGreaterThan(Protocol):\n def __gt__(self, other: Self) -> bool:\n ...\n\n\nclass ConcreteGreaterThan1:\n def __gt__(self, other: Self) -> bool:\n return False\n\n\nclass ConcreteGreaterThan2:\n def __gt__(self, other: \"ConcreteGreaterThan2\") -> bool:\n return False\n\n\nclass InvalidGreaterThan:\n def __gt__(self, other: int) -> bool:\n return False\n\n\nhg1: HasGreaterThan = ConcreteGreaterThan1() # OK\nhg2: HasGreaterThan = ConcreteGreaterThan2() # OK\nhg3: HasGreaterThan = InvalidGreaterThan() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_generic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_05.py","code":"\"\"\"\nTests merging and extending of protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#merging-and-extending-protocols\n\nfrom abc import abstractmethod\nfrom typing import Protocol\nfrom collections.abc import Sized\n\n\nclass SizedAndClosable1(Sized, Protocol):\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable2(Protocol):\n def __len__(self) -> int:\n ...\n\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable3(SizedAndClosable1): # Note: not a protocol\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete1:\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete2:\n def close(self) -> None:\n pass\n\n\ns1: SizedAndClosable1 = SCConcrete1() # OK\ns2: SizedAndClosable2 = SCConcrete1() # OK\ns3: SizedAndClosable1 = SizedAndClosable3() # OK\ns4: SizedAndClosable2 = SizedAndClosable3() # OK\ns5: Sized = SCConcrete1() # OK\n\ns6: SizedAndClosable1 = SCConcrete2() # E: doesn't implement `__len__`\ns7: SizedAndClosable2 = SCConcrete2() # E: doesn't implement `__len__`\ns8: SizedAndClosable3 = SCConcrete2() # E: SizedAndClosable3 is not a protocol\n\n\ndef func1(s1: SizedAndClosable1, s2: SizedAndClosable2):\n # > The two definitions of SizedAndClosable are equivalent.\n v1: SizedAndClosable2 = s1\n v2: SizedAndClosable1 = s2\n\n\n# > If Protocol is included in the base class list, all the other base classes\n# > must be protocols.\n\n\nclass BadProto(SizedAndClosable3, Protocol): # E: SizedAndClosable3 is not a protocol\n ...\n\n\n# > Without this base, the class is “downgraded” to a regular ABC that\n# > cannot be used with structural subtyping.\nclass SizedAndClosable4(SizedAndClosable1):\n def __len__(self) -> int:\n return 0\n\n @abstractmethod\n def close(self) -> None:\n raise NotImplementedError\n\n\nx = SizedAndClosable4() # E: cannot instantiate abstract class\ny: SizedAndClosable4 = SCConcrete1() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_merging.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_06.py","code":"\"\"\"\nTests the handling of modules as the implementation of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#modules-as-implementations-of-protocols\n\n# > A module object is accepted where a protocol is expected if the public\n# > interface of the given module is compatible with the expected protocol.\n\nimport _protocols_modules1\nimport _protocols_modules2\nfrom typing import Protocol\n\n\nclass Options1(Protocol):\n timeout: int\n one_flag: bool\n other_flag: bool\n\n\nclass Options2(Protocol):\n timeout: str\n\n\nop1: Options1 = _protocols_modules1 # OK\nop2: Options2 = _protocols_modules1 # E\n\n\nclass Reporter1(Protocol):\n def on_error(self, x: int) -> None:\n ...\n\n def on_success(self) -> None:\n ...\n\n\nclass Reporter2(Protocol):\n def on_error(self, x: int) -> int:\n ...\n\n\nclass Reporter3(Protocol):\n def not_implemented(self, x: int) -> int:\n ...\n\n\nrp1: Reporter1 = _protocols_modules2 # OK\nrp2: Reporter2 = _protocols_modules2 # E\nrp3: Reporter3 = _protocols_modules2 # E\n","source":"typing_tests","origin":"conformance/tests/protocols_modules.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_07.py","code":"\"\"\"\nTests the handling of recursive protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#recursive-protocols\n\n\nfrom typing import Generic, Iterable, Never, Protocol, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Traversable(Protocol):\n def leaves(self) -> Iterable[\"Traversable\"]:\n ...\n\n\nclass SimpleTree:\n def leaves(self) -> list[\"SimpleTree\"]:\n return []\n\n\nroot: Traversable = SimpleTree() # OK\n\n\nclass Tree(Generic[T]):\n def leaves(self) -> list[\"Tree[T]\"]:\n return []\n\n\ndef walk(graph: Traversable) -> None:\n pass\n\n\ntree: Tree[float] = Tree()\nwalk(tree) # OK\n\n\nclass ProtoA(Protocol[T_co, T_contra]):\n def method1(self) -> \"ProtoA[T_co, T_contra]\":\n ...\n\n @classmethod\n def method2(cls, value: T_contra) -> None:\n ...\n\n\nclass ProtoB(Protocol[T_co, T_contra]):\n def method3(self) -> ProtoA[T_co, T_contra]:\n ...\n\n\nclass ImplA:\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls, value: int) -> None:\n pass\n\n\nclass ImplB:\n def method3(self) -> ImplA:\n return ImplA()\n\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls: type[ProtoB[object, T]], value: list[T]) -> None:\n pass\n\n\ndef func1(x: ProtoA[Never, T]) -> T:\n raise NotImplementedError\n\n\nv1 = func1(ImplB())\nassert_type(v1, list[int])\n","source":"typing_tests","origin":"conformance/tests/protocols_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_08.py","code":"\"\"\"\nTests the handling of the @runtime_checkable decorator for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#runtime-checkable-decorator-and-narrowing-types-by-isinstance\n\n# > A protocol can be used as a second argument in isinstance() and\n# > issubclass() only if it is explicitly opt-in by @runtime_checkable decorator.\n\nfrom typing import Any, Protocol, runtime_checkable\n\n\nclass Proto1(Protocol):\n name: str\n\n\n@runtime_checkable\nclass Proto2(Protocol):\n name: str\n\n\ndef func1(a: Any):\n if isinstance(a, Proto1): # E: not runtime_checkable\n return\n\n if isinstance(a, Proto2): # OK\n return\n\n\n# > isinstance() can be used with both data and non-data protocols, while\n# > issubclass() can be used only with non-data protocols.\n\n\n@runtime_checkable\nclass DataProtocol(Protocol):\n name: str\n\n def method1(self) -> int:\n ...\n\n\n@runtime_checkable\nclass NonDataProtocol(Protocol):\n def method1(self) -> int:\n ...\n\n\ndef func2(a: Any):\n if isinstance(a, DataProtocol): # OK\n return\n\n if isinstance(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, DataProtocol): # E\n return\n\n if issubclass(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, (NonDataProtocol, DataProtocol)): # E\n return\n\n\n# > Type checkers should reject an isinstance() or issubclass() call if there\n# > is an unsafe overlap between the type of the first argument and the protocol.\n\n\n@runtime_checkable\nclass Proto3(Protocol):\n def method1(self, a: int) -> int:\n ...\n\n\nclass Concrete3A:\n def method1(self, a: str) -> None:\n pass\n\n\nclass Concrete3B:\n method1: int = 1\n\n\ndef func3():\n if isinstance(Concrete3A(), Proto2): # OK\n pass\n\n if isinstance(Concrete3A(), Proto3): # E: unsafe overlap\n pass\n\n if isinstance(Concrete3B(), (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n\n if issubclass(Concrete3A, (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n","source":"typing_tests","origin":"conformance/tests/protocols_runtime_checkable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_09.py","code":"\"\"\"\nTests the handling of annotated \"self\" parameters in a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n\nfrom typing import Generic, Protocol, Self, TypeVar\n\n\nC = TypeVar(\"C\", bound=\"Copyable\")\n\n\nclass Copyable(Protocol):\n def copy(self: C) -> C:\n return self\n\n\nclass One:\n def copy(self) -> \"One\":\n return One()\n\n\nT = TypeVar(\"T\", bound=\"Other\")\n\n\nclass Other:\n def copy(self: T) -> T:\n return self\n\n\nc: Copyable\nc = One() # OK\nc = Other() # OK\n\n\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT2_co = TypeVar(\"T2_co\", covariant=True)\n\n\nclass P1Parent(Protocol[T2_co]):\n def f0(self, /) -> Self:\n ...\n\n\nclass P1Child(P1Parent[T2_co], Protocol[T2_co]):\n ...\n\n\nclass C1(Generic[T1_co]):\n def f0(self, /) -> Self:\n return self\n\n\na1: P1Parent[str] = C1[str]()\nb1: P1Child[str] = C1[str]()\n\n\nclass P2Parent(Protocol[T1_co]):\n def f0(self, right: Self, /) -> \"P2Parent[T1_co]\":\n return right\n\n\nclass P2Child(P2Parent[T1_co], Protocol[T1_co]):\n ...\n\n\nclass C2(Generic[T2_co]):\n def f0(self, other: Self) -> \"C2[T2_co]\":\n return other\n\n\na2: P2Parent[str] = C2[str]() # OK\nb2: P2Child[str] = C2[str]() # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_self.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_10.py","code":"\"\"\"\nTests subtyping rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#subtyping-relationships-with-other-types\n\n# > Protocols cannot be instantiated.\n\nfrom typing import Hashable, Iterable, Protocol, Sequence, TypeVar\n\n\nclass Proto1(Protocol):\n pass\n\n\np1 = Proto1() # E: protocol cannot be instantiated\n\n\n# > A protocol is never a subtype of a concrete type.\n\n# > A concrete type X is a subtype of protocol P if and only if X implements\n# > all protocol members of P with compatible types. In other words, subtyping\n# > with respect to a protocol is always structural.\n\n\nclass Proto2(Protocol):\n def method1(self) -> None:\n ...\n\n\nclass Concrete2:\n def method1(self) -> None:\n pass\n\n\ndef func1(p2: Proto2, c2: Concrete2):\n v1: Proto2 = c2 # OK\n v2: Concrete2 = p2 # E\n\n\n# > A protocol P1 is a subtype of another protocol P2 if P1 defines all\n# > protocol members of P2 with compatible types.\n\n\nclass Proto3(Protocol):\n def method1(self) -> None:\n ...\n\n def method2(self) -> None:\n ...\n\n\ndef func2(p2: Proto2, p3: Proto3):\n v1: Proto2 = p3 # OK\n v2: Proto3 = p2 # E\n\n\n# > Generic protocols follow the rules for generic abstract classes, except\n# > for using structural compatibility instead of compatibility defined by\n# > inheritance relationships.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n\nclass Proto4(Protocol[S, T]):\n def method1(self, a: S, b: T) -> tuple[S, T]:\n ...\n\n\nclass Proto5(Protocol[T]):\n def method1(self, a: T, b: T) -> tuple[T, T]:\n ...\n\n\ndef func3(p4_int: Proto4[int, int], p5_int: Proto5[int]):\n v1: Proto4[int, int] = p5_int # OK\n v2: Proto5[int] = p4_int # OK\n v3: Proto4[int, float] = p5_int # E\n v4: Proto5[float] = p4_int # E\n\n\nS_co = TypeVar(\"S_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Proto6(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\nclass Proto7(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\ndef func4(p6: Proto6[float, float]):\n v1: Proto7[object, int] = p6 # OK\n v2: Proto7[float, float] = p6 # OK\n v3: Proto7[complex, int] = p6 # OK\n\n v4: Proto7[int, float] = p6 # E\n v5: Proto7[float, object] = p6 # E\n\n\n# > Unions of protocol classes behaves the same way as for non-protocol classes.\n\n\nclass SupportsExit(Protocol):\n def exit(self) -> int:\n ...\n\n\nclass SupportsQuit(Protocol):\n def quit(self) -> int | None:\n ...\n\n\ndef finish(task: SupportsExit | SupportsQuit) -> int:\n return 0\n\n\nclass DefaultJob:\n def quit(self) -> int:\n return 0\n\n\nfinish(DefaultJob()) # OK\n\n\n# > One can use multiple inheritance to define an intersection of protocols.\n\n\nclass HashableFloats(Iterable[float], Hashable, Protocol):\n pass\n\n\ndef cached_func(args: HashableFloats) -> float:\n return 0.0\n\n\ncached_func((1, 2, 3)) # OK, tuple is both hashable and iterable\n","source":"typing_tests","origin":"conformance/tests/protocols_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_11.py","code":"\"\"\"\nTests type variable variance inference for generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\nfrom typing import Protocol, TypeVar\nfrom typing_extensions import ParamSpec\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", bound=int)\nT3 = TypeVar(\"T3\", bytes, str)\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT1_contra = TypeVar(\"T1_contra\", contravariant=True)\nP = ParamSpec(\"P\", contravariant=True)\nR = TypeVar(\"R\", covariant=True)\n\n# > Type checkers will warn if the inferred variance is different from the\n# > declared variance.\n\n\nclass AnotherBox(Protocol[T1]): # E: T should be covariant\n def content(self) -> T1:\n ...\n\n\nclass Protocol1(Protocol[T1, T2, T3]): # OK\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1 | T2:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n def m4(self) -> T3:\n ...\n\n\nclass Protocol2(Protocol[T1, T2, T3]): # E: T3 should be contravariant\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n\nclass Protocol3(Protocol[T1_co]):\n def m1(self) -> None:\n pass\n\n\nclass Protocol4(Protocol[T1]): # E: T1 should be contravariant\n def m1(self, p0: T1) -> None:\n ...\n\n\nclass Protocol5(Protocol[T1_co]): # E[covariant_in_input+]\n def m1(self, p0: T1_co) -> None: # E[covariant_in_input+]\n ...\n\n\nclass Protocol6(Protocol[T1]): # E: T1 should be covariant\n def m1(self) -> T1:\n ...\n\n\nclass Protocol7(Protocol[T1_contra]): # E[contravariant_in_output+]\n def m1(self) -> T1_contra: # E[contravariant_in_output+]\n ...\n\n\nclass Protocol8(Protocol[T1]): # OK\n def m1(self) -> T1:\n ...\n\n def m2(self, p1: T1) -> None:\n pass\n\n\nclass Callback(Protocol[P, R]): # OK\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\nclass Protocol9(Protocol[T1_co]): # OK\n @property\n def prop1(self) -> T1_co:\n ...\n\n\nclass Protocol10(Protocol[T1_co]): # OK\n def m1(self) -> type[T1_co]:\n ...\n\n\nclass Protocol11(Protocol[T1]): # OK\n x: T1 | None\n\n\nclass Protocol12(Protocol[T1]): # E: T1 should be covariant\n # __init__ method is exempt from variance calculations.\n def __init__(self, x: T1) -> None:\n ...\n\n\nclass Protocol13(Protocol[T1_contra]): # OK\n def m1(self: \"Protocol13[T1_contra]\", x: T1_contra) -> None:\n ...\n\n @classmethod\n def m2(cls: \"type[Protocol13[T1_contra]]\") -> None:\n ...\n\n\nclass Protocol14(Protocol[T1]): # OK\n def m1(self) -> list[T1]:\n ...\n","source":"typing_tests","origin":"conformance/tests/protocols_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_01.py","code":"\"\"\"\nTests explicit type aliases defined with `TypeAlias`.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#typealias\n\nfrom typing import Any, Callable, Concatenate, Literal, ParamSpec, TypeVar, Union, assert_type\nfrom typing import TypeAlias as TA\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1: TA = Union[int, str]\nGoodTypeAlias2: TA = int | None\nGoodTypeAlias3: TA = list[GoodTypeAlias2]\nGoodTypeAlias4: TA = list[T]\nGoodTypeAlias5: TA = tuple[T, ...] | list[T]\nGoodTypeAlias6: TA = tuple[int, int, S, T]\nGoodTypeAlias7: TA = Callable[..., int]\nGoodTypeAlias8: TA = Callable[[int, T], T]\nGoodTypeAlias9: TA = Callable[Concatenate[int, P], R]\nGoodTypeAlias10: TA = Any\nGoodTypeAlias11: TA = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12: TA = Callable[P, None]\nGoodTypeAlias13: TA = \"int | str\"\nGoodTypeAlias14: TA = list[\"int | str\"]\nGoodTypeAlias15: TA = Literal[3, 4, 5, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12,\n p13: GoodTypeAlias13,\n p14: GoodTypeAlias14,\n p15: GoodTypeAlias15,\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, Callable[..., None])\n assert_type(p13, int | str)\n assert_type(p14, list[int | str])\n assert_type(p15, Literal[3, 4, 5, None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be allowed as type aliases.\nBadTypeAlias1: TA = eval(\"\".join(map(chr, [105, 110, 116]))) # E\nBadTypeAlias2: TA = [int, str] # E\nBadTypeAlias3: TA = ((int, str),) # E\nBadTypeAlias4: TA = [int for i in range(1)] # E\nBadTypeAlias5: TA = {\"a\": \"b\"} # E\nBadTypeAlias6: TA = (lambda: int)() # E\nBadTypeAlias7: TA = [int][0] # E\nBadTypeAlias8: TA = int if 1 < 3 else str # E\nBadTypeAlias9: TA = var1 # E\nBadTypeAlias10: TA = True # E\nBadTypeAlias11: TA = 1 # E\nBadTypeAlias12: TA = list or set # E\nBadTypeAlias13: TA = f\"{'int'}\" # E\n\n\nListAlias: TA = list\nListOrSetAlias: TA = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2: ListAlias[int] # E: already specialized\nx3 = ListOrSetAlias() # E: cannot instantiate union\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_02.py","code":"\"\"\"\nTests recursive (self-referential) type aliases.\n\"\"\"\n\n# The typing specification doesn't mandate support for recursive\n# (self-referential) type aliases prior to PEP 695, but it also\n# doesn't indicates that they shouldn't work.\n# Most type checkers now support them, and many libraries and code\n# bases have started to rely on them.\n# PEP 695 formally mandates that recursive type aliases work.\n\nfrom typing import Mapping, TypeAlias, TypeVar, Union\n\nJson = Union[None, int, str, float, list[\"Json\"], dict[str, \"Json\"]]\n\nj1: Json = [1, {\"a\": 1}] # OK\nj2: Json = 3.4 # OK\nj3: Json = [1.2, None, [1.2, [\"\"]]] # OK\nj4: Json = {\"a\": 1, \"b\": 3j} # E: incompatible type\nj5: Json = [2, 3j] # E: incompatible type\n\n\n# This type alias should be equivalent to Json.\nJson2 = Union[None, int, str, float, list[\"Json2\"], dict[str, \"Json2\"]]\n\ndef func1(j1: Json) -> Json2:\n return j1\n\n\nRecursiveTuple = str | int | tuple[\"RecursiveTuple\", ...]\n\n\nt1: RecursiveTuple = (1, 1) # OK\nt2: RecursiveTuple = (1, \"1\") # OK\nt3: RecursiveTuple = (1, \"1\", 1, \"2\") # OK\nt4: RecursiveTuple = (1, (\"1\", 1), \"2\") # OK\nt5: RecursiveTuple = (1, (\"1\", 1), (1, (1, 2))) # OK\nt6: RecursiveTuple = (1, (\"1\", 1), (1, (1, [2]))) # E\nt7: RecursiveTuple = (1, [1]) # E\n\n\nRecursiveMapping = str | int | Mapping[str, \"RecursiveMapping\"]\n\nm1: RecursiveMapping = 1 # OK\nm2: RecursiveMapping = \"1\" # OK\nm3: RecursiveMapping = {\"1\": \"1\"} # OK\nm4: RecursiveMapping = {\"1\": \"1\", \"2\": 1} # OK\nm5: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {}} # OK\nm6: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": \"2\", \"2\": {}}} # OK\nm7: RecursiveMapping = {\"1\": [1]} # E\nm8: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": [1, 2]} # E\nm9: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": 1, \"2\": [1, 2, 3]}} # E\n\n\nT1 = TypeVar(\"T1\", str, int)\nT2 = TypeVar(\"T2\")\n\nGenericTypeAlias1 = list[\"GenericTypeAlias1[T1]\" | T1]\nSpecializedTypeAlias1 = GenericTypeAlias1[str]\n\ng1: SpecializedTypeAlias1 = [\"hi\", [\"hi\", \"hi\"]] # OK\ng2: GenericTypeAlias1[str] = [\"hi\", \"bye\", [\"\"], [[\"hi\"]]] # OK\ng3: GenericTypeAlias1[str] = [\"hi\", [2.4]] # E\n\nGenericTypeAlias2 = list[\"GenericTypeAlias2[T1, T2]\" | T1 | T2]\n\ng4: GenericTypeAlias2[str, int] = [[3, [\"hi\"]], \"hi\"] # OK\ng5: GenericTypeAlias2[str, float] = [[3, [\"hi\", 3.4, [3.4]]], \"hi\"] # OK\ng6: GenericTypeAlias2[str, int] = [[3, [\"hi\", 3, [3.4]]], \"hi\"] # E\n\n\nRecursiveUnion: TypeAlias = Union[\"RecursiveUnion\", int] # E: cyclical reference\n\n# On one line because different type checkers report the error on different lines\nMutualReference1: TypeAlias = Union[\"MutualReference2\", int]; MutualReference2: TypeAlias = Union[\"MutualReference1\", str] # E: cyclical reference\n","source":"typing_tests","origin":"conformance/tests/aliases_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-guard","pep":"647","introduced_in":"3.10","form":"modern","file":"type-guard/modern_01.py","code":"\"\"\"\nTests TypeGuard functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeguard\n\nfrom typing import Any, Callable, Protocol, Self, TypeGuard, TypeVar, assert_type\n\n\nT = TypeVar(\"T\")\n\ndef is_two_element_tuple(val: tuple[T, ...]) -> TypeGuard[tuple[T, T]]:\n return len(val) == 2\n\ndef func1(names: tuple[str, ...]):\n if is_two_element_tuple(names):\n assert_type(names, tuple[str, str])\n else:\n assert_type(names, tuple[str, ...])\n\n\ndef is_str_list(val: list[object], allow_empty: bool) -> TypeGuard[list[str]]:\n if len(val) == 0:\n return allow_empty\n return all(isinstance(x, str) for x in val)\n\ndef is_set_of(val: set[Any], type: type[T]) -> TypeGuard[set[T]]:\n return all(isinstance(x, type) for x in val)\n\ndef func2(val: set[object]):\n if is_set_of(val, int):\n assert_type(val, set[int])\n else:\n assert_type(val, set[object])\n\n\nT_A = TypeVar(\"T_A\", bound=\"A\")\n\nclass A:\n def tg_1(self, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @classmethod\n def tg_2(cls, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @staticmethod\n def tg_3(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n def tg4(self, val: object) -> TypeGuard[Self]:\n return isinstance(val, type(self))\n\n def tg5(self: T_A, val: object) -> TypeGuard[T_A]:\n return isinstance(val, type(self))\n\nclass B(A):\n pass\n\n# > Type checkers should assume that type narrowing should be applied to\n# > the expression that is passed as the first positional argument to a\n# > user-defined type guard. If the type guard function accepts more than\n# > one argument, no type narrowing is applied to those additional argument\n# > expressions.\n\ndef func3() -> None:\n val1 = object()\n if A().tg_1(val1):\n assert_type(val1, int)\n\n val2 = object()\n if A().tg_2(val2):\n assert_type(val2, int)\n\n val3 = object()\n if A.tg_2(val3):\n assert_type(val3, int)\n\n val4 = object()\n if A().tg_3(val4):\n assert_type(val4, int)\n\n val5 = object()\n if A.tg_3(val5):\n assert_type(val5, int)\n\n val6 = object()\n if B().tg4(val6):\n assert_type(val6, B)\n\n val7 = object()\n if B().tg4(val7):\n assert_type(val7, B)\n\n\n# > If a type guard function is implemented as an instance method or class\n# > method, the first positional argument maps to the second parameter\n# > (after “self” or “cls”).\n\nclass C:\n # Type checker should emit error here.\n def tg_1(self) -> TypeGuard[int]: # E\n return False\n\n @classmethod\n # Type checker should emit error here.\n def tg_2(cls) -> TypeGuard[int]: # E\n return False\n\n# > ``TypeGuard`` is also valid as the return type of a ``Callable`` type. In that\n# > context, it is treated as a subtype of bool. For example, ``Callable[..., TypeGuard[int]]``\n# > is assignable to ``Callable[..., bool]``.\n\n\ndef takes_callable_bool(f: Callable[[object], bool]) -> None:\n pass\n\n\ndef takes_callable_str(f: Callable[[object], str]) -> None:\n pass\n\n\ndef simple_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ntakes_callable_bool(simple_typeguard) # OK\ntakes_callable_str(simple_typeguard) # E\n\n\nclass CallableBoolProto(Protocol):\n def __call__(self, val: object) -> bool: ...\n\n\nclass CallableStrProto(Protocol):\n def __call__(self, val: object) -> str: ...\n\n\ndef takes_callable_bool_proto(f: CallableBoolProto) -> None:\n pass\n\n\ndef takes_callable_str_proto(f: CallableStrProto) -> None:\n pass\n\n\ntakes_callable_bool_proto(simple_typeguard) # OK\ntakes_callable_str_proto(simple_typeguard) # E\n\n# > Unlike ``TypeGuard``, ``TypeIs`` is invariant in its argument type:\n# > ``TypeIs[B]`` is not a subtype of ``TypeIs[A]``,\n# > even if ``B`` is a subtype of ``A``.\n\ndef takes_int_typeguard(f: Callable[[object], TypeGuard[int]]) -> None:\n pass\n\n\ndef int_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ndef bool_typeguard(val: object) -> TypeGuard[bool]:\n return isinstance(val, bool)\n\n\ntakes_int_typeguard(int_typeguard) # OK\ntakes_int_typeguard(bool_typeguard) # OK\n","source":"typing_tests","origin":"conformance/tests/narrowing_typeguard.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_13.py","code":"\"\"\"\nTests the \"alternative\" (non-class) syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#alternative-syntax\n\nfrom typing import TypedDict\n\n\nMovie = TypedDict(\"Movie\", {\"name\": str, \"year\": int, \"illegal key name\": bool})\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982, \"illegal key name\": True}\n\nMovieOptional = TypedDict(\"MovieOptional\", {\"name\": str, \"year\": int}, total=False)\n\nmovie_opt1: MovieOptional = {}\nmovie_opt2: MovieOptional = {\"year\": 1982}\n\n# > A type checker is only expected to accept a dictionary display expression as\n# > the second argument to TypedDict. In particular, a variable that refers to a\n# > dictionary object does not need to be supported, to simplify implementation.\nmy_dict = {\"name\": str}\nBadTypedDict1 = TypedDict(\"BadTypedDict1\", my_dict) # E\n\n\n# This should generate an error because it uses a non-str key.\nBadTypedDict2 = TypedDict(\"BadTypedDict2\", {1: str}) # E\n\n\n# This should generate an error because it uses a non-matching name.\nBadTypedDict3 = TypedDict(\"WrongName\", {\"name\": str}) # E\n\n\n# This should generate an error because of the additional parameter.\nBadTypedDict4 = TypedDict(\"BadTypedDict4\", {\"name\": str}, total=False, other=False) # E\n\n\n# > The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13.\n# > It may also be unsupported by static type checkers.\n\nMovie2 = TypedDict(\"Movie2\", name=str, year=int) # E?\n\nmovie2: Movie2\nmovie2 = {\"name\": \"Blade Runner\", \"year\": 1982} # E?: May generate errors if keyword-argument syntax is unsupported\nmovie2 = {\"name\": \"Blade Runner\", \"year\": \"\"} # E?: Incorrect type for year\n","source":"typing_tests","origin":"conformance/tests/typeddicts_alt_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_14.py","code":"\"\"\"\nTests the class syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import Generic, TypeVar, TypedDict\nimport sys\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n # > String literal forward references are valid in the value types.\n director: \"Person\"\n\n\nclass Person(TypedDict):\n name: str\n age: int\n\n\n# > Methods are not allowed, since the runtime type of a TypedDict object\n# > will always be just dict (it is never a subclass of dict).\nclass BadTypedDict1(TypedDict):\n name: str\n\n # Methods are not allowed, so this should generate an error.\n def method1(self): # E\n pass\n\n # Methods are not allowed, so this should generate an error.\n @classmethod # E[method2]\n def method2(cls): # E[method2]\n pass\n\n # Methods are not allowed, so this should generate an error.\n @staticmethod # E[method3]\n def method3(): # E[method3]\n pass\n\n\nclass CustomMeta(type):\n pass\n\n\n# > Specifying a custom metaclass is not allowed.\nclass BadTypedDict2(TypedDict, metaclass=CustomMeta): # E\n name: str\n\n\n# This should generate an error because \"other\" is not an allowed keyword argument.\nclass BadTypedDict3(TypedDict, other=True): # E\n name: str\n\n# > `if` conditions that the type checker is able to\n# > statically evaluate are also permitted (e.g. `if sys.version_info > (3, 14)`),\n# > in order to specify items that exist only under the given conditions.\nclass ConditionalField(TypedDict):\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nConditionalField(x=1, y=2)\nConditionalField(x=1, y=2, z=3) # E\n\n\n# > TypedDicts may be made generic by adding Generic[T] among the bases.\nT = TypeVar(\"T\")\n\n\nclass GenericTypedDict(TypedDict, Generic[T]):\n name: str\n value: T\n\n\n# > An empty TypedDict can be created by only including pass in the\n# > body (if there is a docstring, pass can be omitted):\nclass EmptyDict1(TypedDict):\n pass\n\n\nclass EmptyDict2(TypedDict):\n \"\"\"Docstring\"\"\"\n\n\nclass MovieTotal(TypedDict, total=True):\n name: str\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n","source":"typing_tests","origin":"conformance/tests/typeddicts_class_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_15.py","code":"\"\"\"\nTests inheritance rules for TypedDict classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclass BookBasedMovie(Movie):\n based_on: str\n\nclass BookBasedMovieAlso(TypedDict):\n name: str\n year: int\n based_on: str\n\nb1: BookBasedMovie = {\"name\": \"Little Women\", \"year\": 2019, \"based_on\": \"Little Women\"}\n\nb2: BookBasedMovieAlso = b1\n\n\nclass X(TypedDict):\n x: int\n\nclass Y(TypedDict):\n y: str\n\nclass XYZ(X, Y):\n z: bool\n\nx1 = XYZ(x=1, y=\"\", z=True)\n\n# > A TypedDict cannot inherit from both a TypedDict type and a\n# > non-TypedDict base class other than Generic.\n\nclass NonTypedDict:\n pass\n\nclass BadTypedDict(TypedDict, NonTypedDict): # E\n pass\n\n\n# > Changing a field type of a parent TypedDict class in a subclass is\n# > not allowed.\n\nclass X1(TypedDict):\n x: str\n\nclass Y1(X1): # E[Y1]\n x: int # E[Y1]: cannot overwrite TypedDict field \"x\"\n\n\n# > Multiple inheritance does not allow conflict types for the same name field:\nclass X2(TypedDict):\n x: int\n\nclass Y2(TypedDict):\n x: str\n\nclass XYZ2(X2, Y2): # E: cannot overwrite TypedDict field \"x\" while merging\n xyz: bool\n","source":"typing_tests","origin":"conformance/tests/typeddicts_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_16.py","code":"\"\"\"\nTests operations provided by a TypedDict object.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#supported-and-unsupported-operations\n\n\nfrom typing import TypedDict, assert_type\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie\n\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982}\nmovie[\"name\"] = \"Other\"\nmovie[\"year\"] = 1981\n\nmovie[\"name\"] = 1982 # E: wrong type\nmovie[\"year\"] = \"\" # E: wrong type\nmovie[\"other\"] = \"\" # E: unknown key added\n\nprint(movie[\"other\"]) # E: unknown key referenced\n\nmovie = {\"name\": \"Blade Runner\"} # E: year is missing\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982.1} # E: year is wrong type\n\n# > The use of a key that is not known to exist should be reported as an error.\nmovie = {\"name\": \"\", \"year\": 1900, \"other\": 2} # E: extra key\n\n\ndef func1(variable_key: str):\n # > A key that is not a literal should generally be rejected.\n movie: Movie = {variable_key: \"\", \"year\": 1900} # E: variable key\n\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"name\")\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"other\") # E?\n\n\nmovie.clear() # E: clear not allowed\n\ndel movie[\"name\"] # E: del not allowed for required key\n\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n year: int\n\n\nmovie_optional: MovieOptional = {}\n\nassert_type(movie_optional.get(\"name\"), str | None)\n\nmovie_optional.clear() # E: clear not allowed\n\ndel movie_optional[\"name\"]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_operations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_17.py","code":"\"\"\"\nTests the type consistency rules for TypedDict objects.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#type-consistency\n\nfrom typing import Any, Literal, Mapping, TypedDict\n\n\nclass A1(TypedDict):\n x: int | None\n\n\nclass B1(TypedDict):\n x: int\n\n\nb1: B1 = {\"x\": 0}\n\n# > Value types behave invariantly.\na1: A1 = b1 # E: 'B1' not compatible with 'A1'\n\n# > any TypedDict type is consistent with Mapping[str, object]\nv1: Mapping[str, object] = b1\n\n# > A TypedDict type with a required key is not consistent with a TypedDict\n# > type where the same key is a non-required key.\n\nclass A2(TypedDict, total=False):\n x: int\n\n\nclass B2(TypedDict):\n x: int\n\n\nb2: B2 = {\"x\": 0}\na2: A2 = b2 # E: 'B2' not compatible with 'A2'\n\n\n# > A TypedDict type A is consistent with TypedDict B if A is structurally\n# > compatible with B. This is true if and only if both of these conditions\n# > are satisfied:\n# > 1. For each key in B, A has the corresponding key and the corresponding\n# > value type in A is consistent with the value type in B. For each key in B,\n# > the value type in B is also consistent with the corresponding value type\n# > in A.\n# > 2. For each required key in B, the corresponding key is required in A. For\n# > each non-required key in B, the corresponding key is not required in A.\n\n\nclass A3(TypedDict):\n x: int\n\n\nclass B3(TypedDict):\n x: int\n y: int\n\n\nb3: B3 = {\"x\": 0, \"y\": 0}\na3: A3 = b3\n\na3 = {\"x\": 0}\nb3 = a3 # E\n\n\n# This should generate an error because it's a literal assignment.\na3_1: A3 = {\"x\": 0, \"y\": 0} # E\n\n# This should not generate an error.\na3_2 = b3\n\n# > A TypedDict isn’t consistent with any Dict[...] type.\n\nd1: dict[str, int] = b3 # E\nd2: dict[str, object] = b3 # E\nd3: dict[Any, Any] = b3 # E\n\n# > A TypedDict with all int values is not consistent with Mapping[str, int].\n\nm1: Mapping[str, int] = b3 # E\nm2: Mapping[str, object] = b3 # OK\nm3: Mapping[str, Any] = b3 # OK\n\n\n# Test \"get\" method.\nUserType1 = TypedDict(\"UserType1\", {\"name\": str, \"age\": int}, total=False)\nuser1: UserType1 = {\"name\": \"Bob\", \"age\": 40}\n\nname1: str = user1.get(\"name\", \"n/a\")\nage1: int = user1.get(\"age\", 42)\n\nUserType2 = TypedDict(\"UserType2\", {\"name\": str, \"age\": int})\nuser2: UserType2 = {\"name\": \"Bob\", \"age\": 40}\n\nname2: str | None = user2.get(\"name\")\n\n# The spec does not say whether type checkers should adjust the return type of `.get()`\n# to exclude `None` if it is known that the key exists. Either option is acceptable.\nname3: str = user2.get(\"name\") # E?\n\nage2: int = user2.get(\"age\", 42)\n\nage3: int | str = user2.get(\"age\", \"42\")\n\nage4: int = user2.get(\"age\", \"42\") # E?\n\n# Test nested TypedDicts.\nclass Inner1(TypedDict):\n inner_key: str\n\n\nclass Inner2(TypedDict):\n inner_key: Inner1\n\n\nclass Outer1(TypedDict):\n outer_key: Inner2\n\n\no1: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": \"hi\"}}}\n\n# This should generate an error because the inner-most value\n# should be a string.\no2: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": 1}}} # E\n\n\nclass Inner3(TypedDict):\n x: int\n\n\nclass Inner4(TypedDict):\n x: int\n\n\nclass Outer2(TypedDict):\n y: str\n z: Literal[\"\"] | Inner3\n\n\nclass Outer3(TypedDict):\n y: str\n z: Literal[\"\"] | Inner4\n\n\ndef func1(td: Outer3):\n ...\n\n\no3: Outer2 = {\"y\": \"\", \"z\": {\"x\": 0}}\no4: Outer3 = o3\n","source":"typing_tests","origin":"conformance/tests/typeddicts_type_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_18.py","code":"\"\"\"\nTests for basic usage of TypedDict.\n\"\"\"\n\nfrom typing import TypeVar, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982}\n\n\ndef record_movie(movie: Movie) -> None:\n ...\n\n\nrecord_movie({\"name\": \"Blade Runner\", \"year\": 1982})\n\n\nmovie[\"director\"] = \"Ridley Scott\" # E: invalid key 'director'\nmovie[\"year\"] = \"1982\" # E: invalid value type (\"int\" expected)\n\n# The code below should be rejected, since 'title' is not a valid key,\n# and the 'name' key is missing:\nmovie2: Movie = {\"title\": \"Blade Runner\", \"year\": 1982} # E\n\nm = Movie(name='Blade Runner', year=1982)\n\n\n# > TypedDict type objects cannot be used in isinstance() tests such as\n# > isinstance(d, Movie).\nif isinstance(movie, Movie): # E\n pass\n\n\n# TypedDict should not be allowed as a bound for a TypeVar.\nT = TypeVar(\"T\", bound=TypedDict) # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n an = g.__anext__()\n try:\n while True:\n try:\n an.__next__()\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n break\n else:\n res.append('EMPTY StopIteration')\n break\n except StopAsyncIteration:\n raise\n except Exception as ex:\n res.append(str(type(ex)))\n break\n except StopAsyncIteration:\n res.append('STOP')\n break\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_exception_11(self):\n def sync_gen():\n yield 10\n yield 20\n\n def sync_gen_wrapper():\n yield 1\n sg = sync_gen()\n sg.send(None)\n try:\n sg.throw(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n async def async_gen():\n yield 10\n yield 20\n\n async def async_gen_wrapper():\n yield 1\n asg = async_gen()\n await asg.asend(None)\n try:\n await asg.athrow(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n\n self.assertTrue(inspect.isawaitable(g.aclose()))\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n asyncio.set_event_loop_policy(None)\n\n def check_async_iterator_anext(self, ait_class):\n with self.subTest(anext=\"pure-Python\"):\n self._check_async_iterator_anext(ait_class, py_anext)\n with self.subTest(anext=\"builtin\"):\n self._check_async_iterator_anext(ait_class, anext)\n\n def _check_async_iterator_anext(self, ait_class, anext):\n g = ait_class()\n async def consume():\n results = []\n results.append(await anext(g))\n results.append(await anext(g))\n results.append(await anext(g, 'buckle my shoe'))\n return results\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2, 'buckle my shoe'])\n with self.assertRaises(StopAsyncIteration):\n self.loop.run_until_complete(consume())\n\n async def test_2():\n g1 = ait_class()\n self.assertEqual(await anext(g1), 1)\n self.assertEqual(await anext(g1), 2)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n\n g2 = ait_class()\n self.assertEqual(await anext(g2, \"default\"), 1)\n self.assertEqual(await anext(g2, \"default\"), 2)\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n\n return \"completed\"\n\n result = self.loop.run_until_complete(test_2())\n self.assertEqual(result, \"completed\")\n\n def test_send():\n p = ait_class()\n obj = anext(p, \"completed\")\n with self.assertRaises(StopIteration):\n with contextlib.closing(obj.__await__()) as g:\n g.send(None)\n\n test_send()\n\n async def test_throw():\n p = ait_class()\n obj = anext(p, \"completed\")\n self.assertRaises(SyntaxError, obj.throw, SyntaxError)\n return \"completed\"\n\n result = self.loop.run_until_complete(test_throw())\n self.assertEqual(result, \"completed\")\n\n def test_async_generator_anext(self):\n async def agen():\n yield 1\n yield 2\n self.check_async_iterator_anext(agen)\n\n def test_python_async_iterator_anext(self):\n class MyAsyncIter:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n async def __anext__(self):\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIter)\n\n def test_python_async_iterator_types_coroutine_anext(self):\n import types\n class MyAsyncIterWithTypesCoro:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n @types.coroutine\n def __anext__(self):\n if False:\n yield \"this is a generator-based coroutine\"\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIterWithTypesCoro)\n\n def test_async_gen_aiter(self):\n async def gen():\n yield 1\n yield 2\n g = gen()\n async def consume():\n return [i async for i in aiter(g)]\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_aiter_class(self):\n results = []\n class Gen:\n async def __aiter__(self):\n yield 1\n yield 2\n g = Gen()\n async def consume():\n ait = aiter(g)\n while True:\n try:\n results.append(await anext(ait))\n except StopAsyncIteration:\n break\n self.loop.run_until_complete(consume())\n self.assertEqual(results, [1, 2])\n\n def test_aiter_idempotent(self):\n async def gen():\n yield 1\n applied_once = aiter(gen())\n applied_twice = aiter(applied_once)\n self.assertIs(applied_once, applied_twice)\n\n def test_anext_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await anext()\n async def call_with_too_many_args():\n await anext(gen(), 1, 3)\n async def call_with_wrong_type_args():\n await anext(1, gen())\n async def call_with_kwarg():\n await anext(aiterator=gen())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_kwarg())\n\n def test_anext_bad_await(self):\n async def bad_awaitable():\n class BadAwaitable:\n def __await__(self):\n return 42\n class MyAsyncIter:\n def __aiter__(self):\n return self\n def __anext__(self):\n return BadAwaitable()\n regex = r\"__await__.*iterator\"\n awaitable = anext(MyAsyncIter(), \"default\")\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n awaitable = anext(MyAsyncIter())\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(bad_awaitable())\n self.assertEqual(result, \"completed\")\n\n async def check_anext_returning_iterator(self, aiter_class):\n awaitable = anext(aiter_class(), \"default\")\n with self.assertRaises(TypeError):\n await awaitable\n awaitable = anext(aiter_class())\n with self.assertRaises(TypeError):\n await awaitable\n return \"completed\"\n\n def test_anext_return_iterator(self):\n class WithIterAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return iter(\"abc\")\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithIterAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_return_generator(self):\n class WithGenAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n yield\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithGenAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_await_raises(self):\n class RaisingAwaitable:\n def __await__(self):\n raise ZeroDivisionError()\n yield\n class WithRaisingAwaitableAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return RaisingAwaitable()\n async def do_test():\n awaitable = anext(WithRaisingAwaitableAnext())\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n awaitable = anext(WithRaisingAwaitableAnext(), \"default\")\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(do_test())\n self.assertEqual(result, \"completed\")\n\n def test_anext_iter(self):\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyError(Exception):\n pass\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n def test1(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError, MyError(), None), 2)\n try:\n g.send(None)\n except StopIteration as e:\n err = e\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(err.value, \"default\")\n\n def test2(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError, MyError(), None), 2)\n with self.assertRaises(MyError):\n g.throw(MyError, MyError(), None)\n\n def test3(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n g.close()\n with self.assertRaisesRegex(RuntimeError, 'cannot reuse'):\n self.assertEqual(g.send(None), 1)\n\n def test4(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n self.assertEqual(g.throw(MyError, MyError(), None), 20)\n with self.assertRaisesRegex(MyError, 'val'):\n g.throw(MyError, MyError('val'), None)\n\n def test5(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n return\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n with self.assertRaisesRegex(StopIteration, 'default'):\n g.throw(MyError, MyError(), None)\n\n def test6(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n await _async_yield(1)\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n with self.assertRaises(MyError):\n g.throw(MyError, MyError(), None)\n\n def run_test(test):\n with self.subTest('pure-Python anext()'):\n test(py_anext)\n with self.subTest('builtin anext()'):\n test(anext)\n\n run_test(test1)\n run_test(test2)\n run_test(test3)\n run_test(test4)\n run_test(test5)\n run_test(test6)\n\n def test_aiter_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await aiter()\n async def call_with_too_many_args():\n await aiter(gen(), 1)\n async def call_with_wrong_type_arg():\n await aiter(1)\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_arg())\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n await asyncio.sleep(0.01)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n\n await asyncio.sleep(0.1)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_aclose_12(self):\n DONE = 0\n\n async def target():\n await asyncio.sleep(0.01)\n 1 / 0\n\n async def foo():\n nonlocal DONE\n task = asyncio.create_task(target())\n try:\n yield 1\n finally:\n try:\n await task\n except ZeroDivisionError:\n DONE = 1\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout)\n yield 1\n finally:\n await asyncio.sleep(0)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1))\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t1)\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t2)\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(finalized, 2)\n\n def test_async_gen_asyncio_shutdown_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n self.assertEqual(messages, [])\n\n def test_async_gen_asyncio_shutdown_exception_01(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n message, = messages\n self.assertEqual(message['asyncgen'], it)\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('an error occurred during closing of asynchronous generator',\n message['message'])\n\n def test_async_gen_asyncio_shutdown_exception_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n gc_collect()\n\n asyncio.run(main())\n\n message, = messages\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('unhandled exception during asyncio.run() shutdown',\n message['message'])\n\n def test_async_gen_expression_01(self):\n async def arange(n):\n for i in range(n):\n await asyncio.sleep(0.01)\n yield i\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 async for i in arange(n))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(10)])\n\n def test_async_gen_expression_02(self):\n async def wrap(n):\n await asyncio.sleep(0.01)\n return n\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 for i in range(n) if await wrap(i))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(1, 10)])\n\n def test_asyncgen_nonstarted_hooks_are_cancellable(self):\n # See https://bugs.python.org/issue38013\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n\n asyncio.run(main())\n\n self.assertEqual([], messages)\n\n def test_async_gen_await_same_anext_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.__anext__()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"\n ):\n await nxt\n\n await it.aclose() # prevent unfinished iterator warning\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_await_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.aclose()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n await nxt\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_twice_with_different_coros(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n await it.aclose()\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_after_exhaustion(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n async for _ in it:\n pass\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_compatible_with_get_stack(self):\n async def async_generator():\n yield object()\n\n async def run():\n ag = async_generator()\n asyncio.create_task(ag.aclose())\n tasks = asyncio.all_tasks()\n for task in tasks:\n # No AttributeError raised\n task.get_stack()\n\n self.loop.run_until_complete(run())\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"breakpoint","pep":"553","introduced_in":"3.7","form":"modern","file":"breakpoint/modern_01.py","code":"import ast\nimport asyncio\nimport builtins\nimport collections\nimport decimal\nimport fractions\nimport gc\nimport io\nimport locale\nimport os\nimport pickle\nimport platform\nimport random\nimport re\nimport sys\nimport traceback\nimport types\nimport unittest\nimport warnings\nfrom contextlib import ExitStack\nfrom functools import partial\nfrom inspect import CO_COROUTINE\nfrom itertools import product\nfrom textwrap import dedent\nfrom types import AsyncGeneratorType, FunctionType\nfrom operator import neg\nfrom test import support\nfrom test.support import (swap_attr, maybe_get_event_loop_policy)\nfrom test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink)\nfrom test.support.script_helper import assert_python_ok\nfrom test.support.warnings_helper import check_warnings\nfrom unittest.mock import MagicMock, patch\n\n\nclass TestBreakpoint(unittest.TestCase):\n def setUp(self):\n # These tests require a clean slate environment. For example, if the\n # test suite is run with $PYTHONBREAKPOINT set to something else, it\n # will mess up these tests. Similarly for sys.breakpointhook.\n # Cleaning the slate here means you can't use breakpoint() to debug\n # these tests, but I think that's okay. Just use pdb.set_trace() if\n # you must.\n self.resources = ExitStack()\n self.addCleanup(self.resources.close)\n self.env = self.resources.enter_context(EnvironmentVarGuard())\n del self.env['PYTHONBREAKPOINT']\n self.resources.enter_context(\n swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))\n\n def test_breakpoint(self):\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once()\n\n def test_breakpoint_with_breakpointhook_set(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_breakpointhook_reset(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n # Reset the hook and it will not be called again.\n sys.breakpointhook = sys.__breakpointhook__\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_args_and_keywords(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint(1, 2, 3, four=4, five=5)\n my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)\n\n def test_breakpoint_with_passthru_error(self):\n def my_breakpointhook():\n pass\n sys.breakpointhook = my_breakpointhook\n self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_builtin(self):\n self.env['PYTHONBREAKPOINT'] = 'int'\n with patch('builtins.int') as mock:\n breakpoint('7')\n mock.assert_called_once_with('7')\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_other(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_noop_0(self):\n self.env['PYTHONBREAKPOINT'] = '0'\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_not_called()\n\n def test_envar_good_path_empty_string(self):\n # PYTHONBREAKPOINT='' is the same as it not being set.\n self.env['PYTHONBREAKPOINT'] = ''\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_unimportable(self):\n for envar in (\n '.', '..', '.foo', 'foo.', '.int', 'int.',\n '.foo.bar', '..foo.bar', '/./',\n 'nosuchbuiltin',\n 'nosuchmodule.nosuchcallable',\n ):\n with self.subTest(envar=envar):\n self.env['PYTHONBREAKPOINT'] = envar\n mock = self.resources.enter_context(patch('pdb.set_trace'))\n w = self.resources.enter_context(check_warnings(quiet=True))\n breakpoint()\n self.assertEqual(\n str(w.message),\n f'Ignoring unimportable $PYTHONBREAKPOINT: \"{envar}\"')\n self.assertEqual(w.category, RuntimeWarning)\n mock.assert_not_called()\n\n def test_envar_ignored_when_hook_is_set(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n sys.breakpointhook = int\n breakpoint()\n mock.assert_not_called()\n","source":"cpython_tests","origin":"Lib/test/test_builtin.py::TestBreakpoint","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, ZeroDivisionError)\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, TypeError)\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_03.py","code":"import concurrent.futures\nimport contextvars\nimport functools\nimport gc\nimport random\nimport time\nimport unittest\nimport weakref\n\n\nclass ContextTest(unittest.TestCase):\n def test_context_var_new_1(self):\n with self.assertRaisesRegex(TypeError, 'takes exactly 1'):\n contextvars.ContextVar()\n\n with self.assertRaisesRegex(TypeError, 'must be a str'):\n contextvars.ContextVar(1)\n\n c = contextvars.ContextVar('aaa')\n self.assertEqual(c.name, 'aaa')\n\n with self.assertRaises(AttributeError):\n c.name = 'bbb'\n\n self.assertNotEqual(hash(c), hash('aaa'))\n\n @isolated_context\n def test_context_var_repr_1(self):\n c = contextvars.ContextVar('a')\n self.assertIn('a', repr(c))\n\n c = contextvars.ContextVar('a', default=123)\n self.assertIn('123', repr(c))\n\n lst = []\n c = contextvars.ContextVar('a', default=lst)\n lst.append(c)\n self.assertIn('...', repr(c))\n self.assertIn('...', repr(lst))\n\n t = c.set(1)\n self.assertIn(repr(c), repr(t))\n self.assertNotIn(' used ', repr(t))\n c.reset(t)\n self.assertIn(' used ', repr(t))\n\n def test_context_subclassing_1(self):\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContextVar(contextvars.ContextVar):\n # Potentially we might want ContextVars to be subclassable.\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContext(contextvars.Context):\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyToken(contextvars.Token):\n pass\n\n def test_context_new_1(self):\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1, a=1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(a=1)\n contextvars.Context(**{})\n\n def test_context_typerrors_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx[1]\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n 1 in ctx\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx.get(1)\n\n def test_context_get_context_1(self):\n ctx = contextvars.copy_context()\n self.assertIsInstance(ctx, contextvars.Context)\n\n def test_context_run_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required'):\n ctx.run()\n\n def test_context_run_2(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n kwargs['spam'] = 'foo'\n args += ('bar',)\n return args, kwargs\n\n for f in (func, functools.partial(func)):\n # partial doesn't support FASTCALL\n\n self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))\n self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, a=2),\n (('bar',), {'a': 2, 'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, 11, a=2),\n ((11, 'bar'), {'a': 2, 'spam': 'foo'}))\n\n a = {}\n self.assertEqual(\n ctx.run(f, 11, **a),\n ((11, 'bar'), {'spam': 'foo'}))\n self.assertEqual(a, {})\n\n def test_context_run_3(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2, a=123)\n\n @isolated_context\n def test_context_run_4(self):\n ctx1 = contextvars.Context()\n ctx2 = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func2():\n self.assertIsNone(var.get(None))\n\n def func1():\n self.assertIsNone(var.get(None))\n var.set('spam')\n ctx2.run(func2)\n self.assertEqual(var.get(None), 'spam')\n\n cur = contextvars.copy_context()\n self.assertEqual(len(cur), 1)\n self.assertEqual(cur[var], 'spam')\n return cur\n\n returned_ctx = ctx1.run(func1)\n self.assertEqual(ctx1, returned_ctx)\n self.assertEqual(returned_ctx[var], 'spam')\n self.assertIn(var, returned_ctx)\n\n def test_context_run_5(self):\n ctx = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func():\n self.assertIsNone(var.get(None))\n var.set('spam')\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n\n self.assertIsNone(var.get(None))\n\n def test_context_run_6(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('a', default=0)\n\n def fun():\n self.assertEqual(c.get(), 0)\n self.assertIsNone(ctx.get(c))\n\n c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(ctx.get(c), 42)\n\n ctx.run(fun)\n\n def test_context_run_7(self):\n ctx = contextvars.Context()\n\n def fun():\n with self.assertRaisesRegex(RuntimeError, 'is already entered'):\n ctx.run(fun)\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_1(self):\n c = contextvars.ContextVar('c')\n with self.assertRaises(LookupError):\n c.get()\n\n self.assertIsNone(c.get(None))\n\n t0 = c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n self.assertIs(t0.old_value, t0.MISSING)\n self.assertIs(t0.old_value, contextvars.Token.MISSING)\n self.assertIs(t0.var, c)\n\n t = c.set('spam')\n self.assertEqual(c.get(), 'spam')\n self.assertEqual(c.get(None), 'spam')\n self.assertEqual(t.old_value, 42)\n c.reset(t)\n\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n\n c.set('spam2')\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t)\n self.assertEqual(c.get(), 'spam2')\n\n ctx1 = contextvars.copy_context()\n self.assertIn(c, ctx1)\n\n c.reset(t0)\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t0)\n self.assertIsNone(c.get(None))\n\n self.assertIn(c, ctx1)\n self.assertEqual(ctx1[c], 'spam2')\n self.assertEqual(ctx1.get(c, 'aa'), 'spam2')\n self.assertEqual(len(ctx1), 1)\n self.assertEqual(list(ctx1.items()), [(c, 'spam2')])\n self.assertEqual(list(ctx1.values()), ['spam2'])\n self.assertEqual(list(ctx1.keys()), [c])\n self.assertEqual(list(ctx1), [c])\n\n ctx2 = contextvars.copy_context()\n self.assertNotIn(c, ctx2)\n with self.assertRaises(KeyError):\n ctx2[c]\n self.assertEqual(ctx2.get(c, 'aa'), 'aa')\n self.assertEqual(len(ctx2), 0)\n self.assertEqual(list(ctx2), [])\n\n @isolated_context\n def test_context_getset_2(self):\n v1 = contextvars.ContextVar('v1')\n v2 = contextvars.ContextVar('v2')\n\n t1 = v1.set(42)\n with self.assertRaisesRegex(ValueError, 'by a different'):\n v2.reset(t1)\n\n @isolated_context\n def test_context_getset_3(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n def fun():\n self.assertEqual(c.get(), 42)\n with self.assertRaises(KeyError):\n ctx[c]\n self.assertIsNone(ctx.get(c))\n self.assertEqual(ctx.get(c, 'spam'), 'spam')\n self.assertNotIn(c, ctx)\n self.assertEqual(list(ctx.keys()), [])\n\n t = c.set(1)\n self.assertEqual(list(ctx.keys()), [c])\n self.assertEqual(ctx[c], 1)\n\n c.reset(t)\n self.assertEqual(list(ctx.keys()), [])\n with self.assertRaises(KeyError):\n ctx[c]\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_4(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n tok = ctx.run(c.set, 1)\n\n with self.assertRaisesRegex(ValueError, 'different Context'):\n c.reset(tok)\n\n @isolated_context\n def test_context_getset_5(self):\n c = contextvars.ContextVar('c', default=42)\n c.set([])\n\n def fun():\n c.set([])\n c.get().append(42)\n self.assertEqual(c.get(), [42])\n\n contextvars.copy_context().run(fun)\n self.assertEqual(c.get(), [])\n\n def test_context_copy_1(self):\n ctx1 = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def ctx1_fun():\n c.set(10)\n\n ctx2 = ctx1.copy()\n self.assertEqual(ctx2[c], 10)\n\n c.set(20)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 10)\n\n ctx2.run(ctx2_fun)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 30)\n\n def ctx2_fun():\n self.assertEqual(c.get(), 10)\n c.set(30)\n self.assertEqual(c.get(), 30)\n\n ctx1.run(ctx1_fun)\n\n @isolated_context\n def test_context_threads_1(self):\n cvar = contextvars.ContextVar('cvar')\n\n def sub(num):\n for i in range(10):\n cvar.set(num + i)\n time.sleep(random.uniform(0.001, 0.05))\n self.assertEqual(cvar.get(), num + i)\n return num\n\n tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)\n try:\n results = list(tp.map(sub, range(10)))\n finally:\n tp.shutdown()\n self.assertEqual(results, list(range(10)))\n","source":"cpython_tests","origin":"Lib/test/test_context.py::ContextTest","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_17.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFieldNoAnnotation(unittest.TestCase):\n def test_field_without_annotation(self):\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n @dataclass\n class C:\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base(self):\n @dataclass\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base_not_dataclass(self):\n # Same test, but with the base class not a dataclass.\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFieldNoAnnotation","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_18.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDocString(unittest.TestCase):\n def assertDocStrEqual(self, a, b):\n # Because 3.6 and 3.7 differ in how inspect.signature work\n # (see bpo #32108), for the time being just compare them with\n # whitespace stripped.\n self.assertEqual(a.replace(' ', ''), b.replace(' ', ''))\n\n def test_existing_docstring_not_overridden(self):\n @dataclass\n class C:\n \"\"\"Lorem ipsum\"\"\"\n x: int\n\n self.assertEqual(C.__doc__, \"Lorem ipsum\")\n\n def test_docstring_no_fields(self):\n @dataclass\n class C:\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C()\")\n\n def test_docstring_one_field(self):\n @dataclass\n class C:\n x: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int)\")\n\n def test_docstring_two_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int)\")\n\n def test_docstring_three_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n z: str\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int, z:str)\")\n\n def test_docstring_one_field_with_default(self):\n @dataclass\n class C:\n x: int = 3\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int=3)\")\n\n def test_docstring_one_field_with_default_none(self):\n @dataclass\n class C:\n x: Union[int, type(None)] = None\n\n self.assertDocStrEqual(C.__doc__, \"C(x:Optional[int]=None)\")\n\n def test_docstring_list_field(self):\n @dataclass\n class C:\n x: List[int]\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int])\")\n\n def test_docstring_list_field_with_default_factory(self):\n @dataclass\n class C:\n x: List[int] = field(default_factory=list)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int]=)\")\n\n def test_docstring_deque_field(self):\n @dataclass\n class C:\n x: deque\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque)\")\n\n def test_docstring_deque_field_with_default_factory(self):\n @dataclass\n class C:\n x: deque = field(default_factory=deque)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque=)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDocString","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_19.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestInit(unittest.TestCase):\n def test_base_has_init(self):\n class B:\n def __init__(self):\n self.z = 100\n pass\n\n # Make sure that declaring this class doesn't raise an error.\n # The issue is that we can't override __init__ in our class,\n # but it should be okay to add __init__ to us if our base has\n # an __init__.\n @dataclass\n class C(B):\n x: int = 0\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertNotIn('z', vars(c))\n\n # Make sure that if we don't add an init, the base __init__\n # gets called.\n @dataclass(init=False)\n class C(B):\n x: int = 10\n c = C()\n self.assertEqual(c.x, 10)\n self.assertEqual(c.z, 100)\n\n def test_no_init(self):\n dataclass(init=False)\n class C:\n i: int = 0\n self.assertEqual(C().i, 0)\n\n dataclass(init=False)\n class C:\n i: int = 2\n def __init__(self):\n self.i = 3\n self.assertEqual(C().i, 3)\n\n def test_overwriting_init(self):\n # If the class has __init__, use it no matter the value of\n # init=.\n\n @dataclass\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(3).x, 6)\n\n @dataclass(init=True)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(4).x, 8)\n\n @dataclass(init=False)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(5).x, 10)\n\n def test_inherit_from_protocol(self):\n # Dataclasses inheriting from protocol should preserve their own `__init__`.\n # See bpo-45081.\n\n class P(Protocol):\n a: int\n\n @dataclass\n class C(P):\n a: int\n\n self.assertEqual(C(5).a, 5)\n\n @dataclass\n class D(P):\n def __init__(self, a):\n self.a = a * 2\n\n self.assertEqual(D(5).a, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestInit","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_20.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestRepr(unittest.TestCase):\n def test_repr(self):\n @dataclass\n class B:\n x: int\n\n @dataclass\n class C(B):\n y: int = 10\n\n o = C(4)\n self.assertEqual(repr(o), 'TestRepr.test_repr..C(x=4, y=10)')\n\n @dataclass\n class D(C):\n x: int = 20\n self.assertEqual(repr(D()), 'TestRepr.test_repr..D(x=20, y=10)')\n\n @dataclass\n class C:\n @dataclass\n class D:\n i: int\n @dataclass\n class E:\n pass\n self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr..C.D(i=0)')\n self.assertEqual(repr(C.E()), 'TestRepr.test_repr..C.E()')\n\n def test_no_repr(self):\n # Test a class with no __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n self.assertIn(f'{__name__}.TestRepr.test_no_repr..C object at',\n repr(C(3)))\n\n # Test a class with a __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'C-class'\n self.assertEqual(repr(C(3)), 'C-class')\n\n def test_overwriting_repr(self):\n # If the class has __repr__, use it no matter the value of\n # repr=.\n\n @dataclass\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=True)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestRepr","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_21.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestEq(unittest.TestCase):\n def test_no_eq(self):\n # Test a class with no __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n self.assertNotEqual(C(0), C(0))\n c = C(3)\n self.assertEqual(c, c)\n\n # Test a class with an __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 10\n self.assertEqual(C(3), 10)\n\n def test_overwriting_eq(self):\n # If the class has __eq__, use it no matter the value of\n # eq=.\n\n @dataclass\n class C:\n x: int\n def __eq__(self, other):\n return other == 3\n self.assertEqual(C(1), 3)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=True)\n class C:\n x: int\n def __eq__(self, other):\n return other == 4\n self.assertEqual(C(1), 4)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 5\n self.assertEqual(C(1), 5)\n self.assertNotEqual(C(1), 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestEq","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_22.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestOrdering(unittest.TestCase):\n def test_functools_total_ordering(self):\n # Test that functools.total_ordering works with this class.\n @total_ordering\n @dataclass\n class C:\n x: int\n def __lt__(self, other):\n # Perform the test \"backward\", just to make\n # sure this is being called.\n return self.x >= other\n\n self.assertLess(C(0), -1)\n self.assertLessEqual(C(0), -1)\n self.assertGreater(C(0), 1)\n self.assertGreaterEqual(C(0), 1)\n\n def test_no_order(self):\n # Test that no ordering functions are added by default.\n @dataclass(order=False)\n class C:\n x: int\n # Make sure no order methods are added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__lt__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n # Test that __lt__ is still called\n @dataclass(order=False)\n class C:\n x: int\n def __lt__(self, other):\n return False\n # Make sure other methods aren't added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n def test_overwriting_order(self):\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __lt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __lt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __le__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __le__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __gt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __gt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __ge__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __ge__(self):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestOrdering","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_23.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestHash(unittest.TestCase):\n def test_unsafe_hash(self):\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n y: str\n self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))\n\n def test_hash_rules(self):\n def non_bool(value):\n # Map to something else that's True, but not a bool.\n if value is None:\n return None\n if value:\n return (3,)\n return 0\n\n def test(case, unsafe_hash, eq, frozen, with_hash, result):\n with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,\n frozen=frozen):\n if result != 'exception':\n if with_hash:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n else:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n pass\n\n # See if the result matches what's expected.\n if result == 'fn':\n # __hash__ contains the function we generated.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNotNone(C.__dict__['__hash__'])\n\n elif result == '':\n # __hash__ is not present in our class.\n if not with_hash:\n self.assertNotIn('__hash__', C.__dict__)\n\n elif result == 'none':\n # __hash__ is set to None.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNone(C.__dict__['__hash__'])\n\n elif result == 'exception':\n # Creating the class should cause an exception.\n # This only happens with with_hash==True.\n assert(with_hash)\n with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n\n else:\n assert False, f'unknown result {result!r}'\n\n # There are 8 cases of:\n # unsafe_hash=True/False\n # eq=True/False\n # frozen=True/False\n # And for each of these, a different result if\n # __hash__ is defined or not.\n for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([\n (False, False, False, '', ''),\n (False, False, True, '', ''),\n (False, True, False, 'none', ''),\n (False, True, True, 'fn', ''),\n (True, False, False, 'fn', 'exception'),\n (True, False, True, 'fn', 'exception'),\n (True, True, False, 'fn', 'exception'),\n (True, True, True, 'fn', 'exception'),\n ], 1):\n test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)\n test(case, unsafe_hash, eq, frozen, True, res_defined_hash)\n\n # Test non-bool truth values, too. This is just to\n # make sure the data-driven table in the decorator\n # handles non-bool values.\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)\n\n\n def test_eq_only(self):\n # If a class defines __eq__, __hash__ is automatically added\n # and set to None. This is normal Python behavior, not\n # related to dataclasses. Make sure we don't interfere with\n # that (see bpo=32546).\n\n @dataclass\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1))\n self.assertNotEqual(C(1), C(4))\n\n # And make sure things work in this case if we specify\n # unsafe_hash=True.\n @dataclass(unsafe_hash=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1.0))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n # And check that the classes __eq__ is being used, despite\n # specifying eq=True.\n @dataclass(unsafe_hash=True, eq=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == 3 and self.i == other.i\n self.assertEqual(C(3), C(3))\n self.assertNotEqual(C(1), C(1))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n def test_0_field_hash(self):\n @dataclass(frozen=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n @dataclass(unsafe_hash=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n def test_1_field_hash(self):\n @dataclass(frozen=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n def test_hash_no_args(self):\n # Test dataclasses with no hash= argument. This exists to\n # make sure that if the @dataclass parameter name is changed\n # or the non-default hashing behavior changes, the default\n # hashability keeps working the same way.\n\n class Base:\n def __hash__(self):\n return 301\n\n # If frozen or eq is None, then use the default value (do not\n # specify any value in the decorator).\n for frozen, eq, base, expected in [\n (None, None, object, 'unhashable'),\n (None, None, Base, 'unhashable'),\n (None, False, object, 'object'),\n (None, False, Base, 'base'),\n (None, True, object, 'unhashable'),\n (None, True, Base, 'unhashable'),\n (False, None, object, 'unhashable'),\n (False, None, Base, 'unhashable'),\n (False, False, object, 'object'),\n (False, False, Base, 'base'),\n (False, True, object, 'unhashable'),\n (False, True, Base, 'unhashable'),\n (True, None, object, 'tuple'),\n (True, None, Base, 'tuple'),\n (True, False, object, 'object'),\n (True, False, Base, 'base'),\n (True, True, object, 'tuple'),\n (True, True, Base, 'tuple'),\n ]:\n\n with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):\n # First, create the class.\n if frozen is None and eq is None:\n @dataclass\n class C(base):\n i: int\n elif frozen is None:\n @dataclass(eq=eq)\n class C(base):\n i: int\n elif eq is None:\n @dataclass(frozen=frozen)\n class C(base):\n i: int\n else:\n @dataclass(frozen=frozen, eq=eq)\n class C(base):\n i: int\n\n # Now, make sure it hashes as expected.\n if expected == 'unhashable':\n c = C(10)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(c)\n\n elif expected == 'base':\n self.assertEqual(hash(C(10)), 301)\n\n elif expected == 'object':\n # I'm not sure what test to use here. object's\n # hash isn't based on id(), so calling hash()\n # won't tell us much. So, just check the\n # function used is object's.\n self.assertIs(C.__hash__, object.__hash__)\n\n elif expected == 'tuple':\n self.assertEqual(hash(C(42)), hash((42,)))\n\n else:\n assert False, f'unknown value for expected={expected!r}'\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestHash","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_24.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFrozen(unittest.TestCase):\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n c = C(10)\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertEqual(c.i, 10)\n\n def test_inherit(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n @dataclass(frozen=True)\n class D(C):\n j: int\n\n d = D(0, 10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n with self.assertRaises(FrozenInstanceError):\n d.j = 6\n self.assertEqual(d.i, 0)\n self.assertEqual(d.j, 10)\n\n def test_inherit_nonfrozen_from_empty_frozen(self):\n @dataclass(frozen=True)\n class C:\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(C):\n j: int\n\n def test_inherit_nonfrozen_from_empty(self):\n @dataclass\n class C:\n pass\n\n @dataclass\n class D(C):\n j: int\n\n d = D(3)\n self.assertEqual(d.j, 3)\n self.assertIsInstance(d, C)\n\n # Test both ways: with an intermediate normal (non-dataclass)\n # class and without an intermediate class.\n def test_inherit_nonfrozen_from_frozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass(frozen=True)\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(I):\n pass\n\n def test_inherit_frozen_from_nonfrozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one'):\n @dataclass(frozen=True)\n class D(I):\n pass\n\n def test_inherit_from_normal_class(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n class C:\n pass\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n @dataclass(frozen=True)\n class D(I):\n i: int\n\n d = D(10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n\n def test_non_frozen_normal_derived(self):\n # See bpo-32953.\n\n @dataclass(frozen=True)\n class D:\n x: int\n y: int = 10\n\n class S(D):\n pass\n\n s = S(3)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n s.cached = True\n\n # But can't change the frozen attributes.\n with self.assertRaises(FrozenInstanceError):\n s.x = 5\n with self.assertRaises(FrozenInstanceError):\n s.y = 5\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.cached, True)\n\n def test_overwriting_frozen(self):\n # frozen uses __setattr__ and __delattr__.\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __setattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __setattr__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __delattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __delattr__(self):\n pass\n\n @dataclass(frozen=False)\n class C:\n x: int\n def __setattr__(self, name, value):\n self.__dict__['x'] = value * 2\n self.assertEqual(C(10).x, 20)\n\n def test_frozen_hash(self):\n @dataclass(frozen=True)\n class C:\n x: Any\n\n # If x is immutable, we can compute the hash. No exception is\n # raised.\n hash(C(3))\n\n # If x is mutable, computing the hash is an error.\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(C({}))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFrozen","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_25.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestSlots(unittest.TestCase):\n def test_simple(self):\n @dataclass\n class C:\n __slots__ = ('x',)\n x: Any\n\n # There was a bug where a variable in a slot was assumed to\n # also have a default value (of type\n # types.MemberDescriptorType).\n with self.assertRaisesRegex(TypeError,\n r\"__init__\\(\\) missing 1 required positional argument: 'x'\"):\n C()\n\n # We can create an instance, and assign to x.\n c = C(10)\n self.assertEqual(c.x, 10)\n c.x = 5\n self.assertEqual(c.x, 5)\n\n # We can't assign to anything else.\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'y'\"):\n c.y = 5\n\n def test_derived_added_field(self):\n # See bpo-33100.\n @dataclass\n class Base:\n __slots__ = ('x',)\n x: Any\n\n @dataclass\n class Derived(Base):\n x: int\n y: int\n\n d = Derived(1, 2)\n self.assertEqual((d.x, d.y), (1, 2))\n\n # We can add a new field to the derived instance.\n d.z = 10\n\n def test_generated_slots(self):\n @dataclass(slots=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n self.assertEqual((c.x, c.y), (1, 2))\n\n c.x = 3\n c.y = 4\n self.assertEqual((c.x, c.y), (3, 4))\n\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'z'\"):\n c.z = 5\n\n def test_add_slots_when_slots_exists(self):\n with self.assertRaisesRegex(TypeError, '^C already specifies __slots__$'):\n @dataclass(slots=True)\n class C:\n __slots__ = ('x',)\n x: int\n\n def test_generated_slots_value(self):\n @dataclass(slots=True)\n class Base:\n x: int\n\n self.assertEqual(Base.__slots__, ('x',))\n\n @dataclass(slots=True)\n class Delivered(Base):\n y: int\n\n self.assertEqual(Delivered.__slots__, ('x', 'y'))\n\n @dataclass\n class AnotherDelivered(Base):\n z: int\n\n self.assertTrue('__slots__' not in AnotherDelivered.__dict__)\n\n def test_returns_new_class(self):\n class A:\n x: int\n\n B = dataclass(A, slots=True)\n self.assertIsNot(A, B)\n\n self.assertFalse(hasattr(A, \"__slots__\"))\n self.assertTrue(hasattr(B, \"__slots__\"))\n\n # Can't be local to test_frozen_pickle.\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsClass:\n foo: str\n bar: int\n\n def test_frozen_pickle(self):\n # bpo-43999\n\n assert self.FrozenSlotsClass.__slots__ == (\"foo\", \"bar\")\n p = pickle.dumps(self.FrozenSlotsClass(\"a\", 1))\n assert pickle.loads(p) == self.FrozenSlotsClass(\"a\", 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestSlots","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_26.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDescriptors(unittest.TestCase):\n def test_set_name(self):\n # See bpo-33141.\n\n # Create a descriptor.\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n def __get__(self, instance, owner):\n if instance is not None:\n return 1\n return self\n\n # This is the case of just normal descriptor behavior, no\n # dataclass code is involved in initializing the descriptor.\n @dataclass\n class C:\n c: int=D()\n self.assertEqual(C.c.name, 'cx')\n\n # Now test with a default value and init=False, which is the\n # only time this is really meaningful. If not using\n # init=False, then the descriptor will be overwritten, anyway.\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n self.assertEqual(C().c, 1)\n\n def test_non_descriptor(self):\n # PEP 487 says __set_name__ should work on non-descriptors.\n # Create a descriptor.\n\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n\n def test_lookup_on_instance(self):\n # See bpo-33175.\n class D:\n pass\n\n d = D()\n # Create an attribute on the instance, not type.\n d.__set_name__ = Mock()\n\n # Make sure d.__set_name__ is not called.\n @dataclass\n class C:\n i: int=field(default=d, init=False)\n\n self.assertEqual(d.__set_name__.call_count, 0)\n\n def test_lookup_on_class(self):\n # See bpo-33175.\n class D:\n pass\n D.__set_name__ = Mock()\n\n # Make sure D.__set_name__ is called.\n @dataclass\n class C:\n i: int=field(default=D(), init=False)\n\n self.assertEqual(D.__set_name__.call_count, 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDescriptors","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_27.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestMakeDataclass(unittest.TestCase):\n def test_simple(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace={'add_one': lambda self: self.x + 1})\n c = C(10)\n self.assertEqual((c.x, c.y), (10, 5))\n self.assertEqual(c.add_one(), 11)\n\n\n def test_no_mutate_namespace(self):\n # Make sure a provided namespace isn't mutated.\n ns = {}\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace=ns)\n self.assertEqual(ns, {})\n\n def test_base(self):\n class Base1:\n pass\n class Base2:\n pass\n C = make_dataclass('C',\n [('x', int)],\n bases=(Base1, Base2))\n c = C(2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n def test_base_dataclass(self):\n @dataclass\n class Base1:\n x: int\n class Base2:\n pass\n C = make_dataclass('C',\n [('y', int)],\n bases=(Base1, Base2))\n with self.assertRaisesRegex(TypeError, 'required positional'):\n c = C(2)\n c = C(1, 2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n self.assertEqual((c.x, c.y), (1, 2))\n\n def test_init_var(self):\n def post_init(self, y):\n self.x *= y\n\n C = make_dataclass('C',\n [('x', int),\n ('y', InitVar[int]),\n ],\n namespace={'__post_init__': post_init},\n )\n c = C(2, 3)\n self.assertEqual(vars(c), {'x': 6})\n self.assertEqual(len(fields(c)), 1)\n\n def test_class_var(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ])\n c = C(1)\n self.assertEqual(vars(c), {'x': 1})\n self.assertEqual(len(fields(c)), 1)\n self.assertEqual(C.y, 10)\n self.assertEqual(C.z, 20)\n\n def test_other_params(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ],\n init=False)\n # Make sure we have a repr, but no init.\n self.assertNotIn('__init__', vars(C))\n self.assertIn('__repr__', vars(C))\n\n # Make sure random other params don't work.\n with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):\n C = make_dataclass('C',\n [],\n xxinit=False)\n\n def test_no_types(self):\n C = make_dataclass('Point', ['x', 'y', 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': 'typing.Any',\n 'z': 'typing.Any'})\n\n C = make_dataclass('Point', ['x', ('y', int), 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': int,\n 'z': 'typing.Any'})\n\n def test_invalid_type_specification(self):\n for bad_field in [(),\n (1, 2, 3, 4),\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'Invalid field: '):\n make_dataclass('C', ['a', bad_field])\n\n # And test for things with no len().\n for bad_field in [float,\n lambda x:x,\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'has no len\\(\\)'):\n make_dataclass('C', ['a', bad_field])\n\n def test_duplicate_field_names(self):\n for field in ['a', 'ab']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'Field name duplicated'):\n make_dataclass('C', [field, 'a', field])\n\n def test_keyword_field_names(self):\n for field in ['for', 'async', 'await', 'as']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field, 'a'])\n\n def test_non_identifier_field_names(self):\n for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field, 'a'])\n\n def test_underscore_field_names(self):\n # Unlike namedtuple, it's okay if dataclass field names have\n # an underscore.\n make_dataclass('C', ['_', '_a', 'a_a', 'a_'])\n\n def test_funny_class_names_names(self):\n # No reason to prevent weird class names, since\n # types.new_class allows them.\n for classname in ['()', 'x,y', '*', '2@3', '']:\n with self.subTest(classname=classname):\n C = make_dataclass(classname, ['a', 'b'])\n self.assertEqual(C.__name__, classname)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestMakeDataclass","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_28.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestReplace(unittest.TestCase):\n def test(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n z: int = field(init=False, default=10)\n t: int = field(init=False, default=100)\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))\n self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))\n\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=3, z=20, t=50)\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, z=20)\n replace(c, x=3, z=20, t=50)\n\n # Make sure the result is still frozen.\n with self.assertRaisesRegex(FrozenInstanceError, \"cannot assign to field 'x'\"):\n c1.x = 3\n\n # Make sure we can't replace an attribute that doesn't exist,\n # if we're also replacing one that does exist. Test this\n # here, because setting attributes on frozen instances is\n # handled slightly differently from non-frozen ones.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'a'\"):\n c1 = replace(c, x=20, a=5)\n\n def test_invalid_field_name(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'z'\"):\n c1 = replace(c, z=3)\n\n def test_invalid_object(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(C, x=3)\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(0, x=3)\n\n def test_no_init(self):\n @dataclass\n class C:\n x: int\n y: int = field(init=False, default=10)\n\n c = C(1)\n c.y = 20\n\n # Make sure y gets the default value.\n c1 = replace(c, x=5)\n self.assertEqual((c1.x, c1.y), (5, 10))\n\n # Trying to replace y is an error.\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=2, y=30)\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, y=30)\n\n def test_classvar(self):\n @dataclass\n class C:\n x: int\n y: ClassVar[int] = 1000\n\n c = C(1)\n d = C(2)\n\n self.assertIs(c.y, d.y)\n self.assertEqual(c.y, 1000)\n\n # Trying to replace y is an error: can't replace ClassVars.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an \"\n \"unexpected keyword argument 'y'\"):\n replace(c, y=30)\n\n replace(c, x=5)\n\n def test_initvar_is_specified(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int]\n\n def __post_init__(self, y):\n self.x *= y\n\n c = C(1, 10)\n self.assertEqual(c.x, 10)\n with self.assertRaisesRegex(ValueError, r\"InitVar 'y' must be \"\n \"specified with replace()\"):\n replace(c, x=3)\n c = replace(c, x=3, y=5)\n self.assertEqual(c.x, 15)\n\n def test_initvar_with_default_value(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int] = None\n z: InitVar[int] = 42\n\n def __post_init__(self, y, z):\n if y is not None:\n self.x += y\n if z is not None:\n self.x += z\n\n c = C(x=1, y=10, z=1)\n self.assertEqual(replace(c), C(x=12))\n self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42))\n self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1))\n\n def test_recursive_repr(self):\n @dataclass\n class C:\n f: \"C\"\n\n c = C(None)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr..C(f=...)\")\n\n def test_recursive_repr_two_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: \"C\"\n\n c = C(None, None)\n c.f = c\n c.g = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_two_attrs\"\n \"..C(f=..., g=...)\")\n\n def test_recursive_repr_indirection(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n c.f = d\n d.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection\"\n \"..C(f=TestReplace.test_recursive_repr_indirection\"\n \"..D(f=...))\")\n\n def test_recursive_repr_indirection_two(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"E\"\n\n @dataclass\n class E:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n e = E(None)\n c.f = d\n d.f = e\n e.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection_two\"\n \"..C(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..D(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..E(f=...)))\")\n\n def test_recursive_repr_misc_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: int\n\n c = C(None, 1)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_misc_attrs\"\n \"..C(f=..., g=1)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestReplace","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_29.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestAbstract(unittest.TestCase):\n def test_abc_implementation(self):\n class Ordered(abc.ABC):\n @abc.abstractmethod\n def __lt__(self, other):\n pass\n\n @abc.abstractmethod\n def __le__(self, other):\n pass\n\n @dataclass(order=True)\n class Date(Ordered):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertFalse(inspect.isabstract(Date))\n self.assertGreater(Date(2020,12,25), Date(2020,8,31))\n\n def test_maintain_abc(self):\n class A(abc.ABC):\n @abc.abstractmethod\n def foo(self):\n pass\n\n @dataclass\n class Date(A):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertTrue(inspect.isabstract(Date))\n msg = 'class Date with abstract method foo'\n self.assertRaisesRegex(TypeError, msg, Date)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestAbstract","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_30.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestMatchArgs(unittest.TestCase):\n def test_match_args(self):\n @dataclass\n class C:\n a: int\n self.assertEqual(C(42).__match_args__, ('a',))\n\n def test_explicit_match_args(self):\n ma = ()\n @dataclass\n class C:\n a: int\n __match_args__ = ma\n self.assertIs(C(42).__match_args__, ma)\n\n def test_bpo_43764(self):\n @dataclass(repr=False, eq=False, init=False)\n class X:\n a: int\n b: int\n c: int\n self.assertEqual(X.__match_args__, (\"a\", \"b\", \"c\"))\n\n def test_match_args_argument(self):\n @dataclass(match_args=False)\n class X:\n a: int\n self.assertNotIn('__match_args__', X.__dict__)\n\n @dataclass(match_args=False)\n class Y:\n a: int\n __match_args__ = ('b',)\n self.assertEqual(Y.__match_args__, ('b',))\n\n @dataclass(match_args=False)\n class Z(Y):\n z: int\n self.assertEqual(Z.__match_args__, ('b',))\n\n # Ensure parent dataclass __match_args__ is seen, if child class\n # specifies match_args=False.\n @dataclass\n class A:\n a: int\n z: int\n @dataclass(match_args=False)\n class B(A):\n b: int\n self.assertEqual(B.__match_args__, ('a', 'z'))\n\n def test_make_dataclasses(self):\n C = make_dataclass('C', [('x', int), ('y', int)])\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=True)\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=False)\n self.assertNotIn('__match__args__', C.__dict__)\n\n C = make_dataclass('C', [('x', int), ('y', int)], namespace={'__match_args__': ('z',)})\n self.assertEqual(C.__match_args__, ('z',))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestMatchArgs","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_31.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestKeywordArgs(unittest.TestCase):\n def test_no_classvar_kwarg(self):\n msg = 'field a is a ClassVar but specifies kw_only'\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=True)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass(kw_only=True)\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n def test_field_marked_as_kwonly(self):\n #######################\n # Using dataclass(kw_only=True)\n @dataclass(kw_only=True)\n class A:\n a: int\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Using dataclass(kw_only=False)\n @dataclass(kw_only=False)\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Not specifying dataclass(kw_only)\n @dataclass\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n def test_match_args(self):\n # kw fields don't show up in __match_args__.\n @dataclass(kw_only=True)\n class C:\n a: int\n self.assertEqual(C(a=42).__match_args__, ())\n\n @dataclass\n class C:\n a: int\n b: int = field(kw_only=True)\n self.assertEqual(C(42, b=10).__match_args__, ('a',))\n\n def test_KW_ONLY(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n\n @dataclass(kw_only=True)\n class B:\n a: int\n _: KW_ONLY\n b: int\n c: int\n B(a=3, b=4, c=5)\n msg = \"takes 1 positional argument but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n B(3, 4, 5)\n\n # Explicitely make a field that follows KW_ONLY be non-keyword-only.\n @dataclass\n class C:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=False)\n c = C(1, 2, b=3)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(c=2, b=3, a=1)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n\n def test_KW_ONLY_as_string(self):\n @dataclass\n class A:\n a: int\n _: 'dataclasses.KW_ONLY'\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n def test_KW_ONLY_twice(self):\n msg = \"'Y' is KW_ONLY, but KW_ONLY has already been specified\"\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n Y: KW_ONLY\n b: int\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n Y: KW_ONLY\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n c: int\n Y: KW_ONLY\n\n # But this usage is okay, since it's not using KW_ONLY.\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=True)\n\n # And if inheriting, it's okay.\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n _: KW_ONLY\n d: int\n\n # Make sure the error is raised in a derived class.\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n X: KW_ONLY\n d: int\n Y: KW_ONLY\n\n\n def test_post_init(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n raise CustomError(f'{b=} {d=}')\n with self.assertRaisesRegex(CustomError, 'b=3 d=4'):\n A(1, c=2, b=3, d=4)\n\n @dataclass\n class B:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n self.a = b\n self.c = d\n b = B(1, c=2, b=3, d=4)\n self.assertEqual(asdict(b), {'a': 3, 'c': 4})\n\n def test_defaults(self):\n # For kwargs, make sure we can have defaults after non-defaults.\n @dataclass\n class A:\n a: int = 0\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n a = A(d=4, b=3)\n self.assertEqual(a.a, 0)\n self.assertEqual(a.b, 3)\n self.assertEqual(a.c, 1)\n self.assertEqual(a.d, 4)\n\n # Make sure we still check for non-kwarg non-defaults not following\n # defaults.\n err_regex = \"non-default argument 'z' follows default argument\"\n with self.assertRaisesRegex(TypeError, err_regex):\n @dataclass\n class A:\n a: int = 0\n z: int\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestKeywordArgs","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"dict-union","pep":"584","introduced_in":"3.9","form":"modern","file":"dict-union/modern_01.py","code":"import collections\nimport collections.abc\nimport gc\nimport pickle\nimport random\nimport string\nimport sys\nimport unittest\nimport weakref\nfrom test import support\nfrom test import mapping_tests\n\n\ndef test_merge_operator(self):\n\n a = {0: 0, 1: 1, 2: 1}\n b = {1: 1, 2: 2, 3: 3}\n\n c = a.copy()\n c |= b\n\n self.assertEqual(a | b, {0: 0, 1: 1, 2: 2, 3: 3})\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n c = b.copy()\n c |= a\n\n self.assertEqual(b | a, {1: 1, 2: 1, 3: 3, 0: 0})\n self.assertEqual(c, {1: 1, 2: 1, 3: 3, 0: 0})\n\n c = a.copy()\n c |= [(1, 1), (2, 2), (3, 3)]\n\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n self.assertIs(a.__or__(None), NotImplemented)\n self.assertIs(a.__or__(()), NotImplemented)\n self.assertIs(a.__or__(\"BAD\"), NotImplemented)\n self.assertIs(a.__or__(\"\"), NotImplemented)\n\n self.assertRaises(TypeError, a.__ior__, None)\n self.assertEqual(a.__ior__(()), {0: 0, 1: 1, 2: 1})\n self.assertRaises(ValueError, a.__ior__, \"BAD\")\n self.assertEqual(a.__ior__(\"\"), {0: 0, 1: 1, 2: 1})\n","source":"cpython_tests","origin":"Lib/test/test_dict.py::DictTest.test_merge_operator","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_01.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom . import _support as test_support\nfrom ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass ZoneInfoCacheTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n def setUp(self):\n self.klass.clear_cache()\n super().setUp()\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @property\n def tzpath(self):\n return [self.zoneinfo_data.tzpath]\n\n def test_ephemeral_zones(self):\n self.assertIs(\n self.klass(\"America/Los_Angeles\"), self.klass(\"America/Los_Angeles\")\n )\n\n def test_strong_refs(self):\n tz0 = self.klass(\"Australia/Sydney\")\n tz1 = self.klass(\"Australia/Sydney\")\n\n self.assertIs(tz0, tz1)\n\n def test_no_cache(self):\n\n tz0 = self.klass(\"Europe/Lisbon\")\n tz1 = self.klass.no_cache(\"Europe/Lisbon\")\n\n self.assertIsNot(tz0, tz1)\n\n def test_cache_reset_tzpath(self):\n \"\"\"Test that the cache persists when tzpath has been changed.\n\n The PEP specifies that as long as a reference exists to one zone\n with a given key, the primary constructor must continue to return\n the same object.\n \"\"\"\n zi0 = self.klass(\"America/Los_Angeles\")\n with self.tzpath_context([]):\n zi1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIs(zi0, zi1)\n\n def test_clear_cache_explicit_none(self):\n la0 = self.klass(\"America/Los_Angeles\")\n self.klass.clear_cache(only_keys=None)\n la1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIsNot(la0, la1)\n\n def test_clear_cache_one_key(self):\n \"\"\"Tests that you can clear a single key from the cache.\"\"\"\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n\n self.klass.clear_cache(only_keys=[\"America/Los_Angeles\"])\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n\n self.assertIsNot(la0, la1)\n self.assertIs(dub0, dub1)\n\n def test_clear_cache_two_keys(self):\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n tok0 = self.klass(\"Asia/Tokyo\")\n\n self.klass.clear_cache(\n only_keys=[\"America/Los_Angeles\", \"Europe/Dublin\"]\n )\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n tok1 = self.klass(\"Asia/Tokyo\")\n\n self.assertIsNot(la0, la1)\n self.assertIsNot(dub0, dub1)\n self.assertIs(tok0, tok1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ZoneInfoCacheTest","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_02.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom . import _support as test_support\nfrom ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass TzPathTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n @staticmethod\n @contextlib.contextmanager\n def python_tzpath_context(value):\n path_var = \"PYTHONTZPATH\"\n try:\n with OS_ENV_LOCK:\n old_env = os.environ.get(path_var, None)\n os.environ[path_var] = value\n yield\n finally:\n if old_env is None:\n del os.environ[path_var]\n else:\n os.environ[path_var] = old_env # pragma: nocover\n\n def test_env_variable(self):\n \"\"\"Tests that the environment variable works with reset_tzpath.\"\"\"\n new_paths = [\n (\"\", []),\n (\"/etc/zoneinfo\", [\"/etc/zoneinfo\"]),\n (f\"/a/b/c{os.pathsep}/d/e/f\", [\"/a/b/c\", \"/d/e/f\"]),\n ]\n\n for new_path_var, expected_result in new_paths:\n with self.python_tzpath_context(new_path_var):\n with self.subTest(tzpath=new_path_var):\n self.module.reset_tzpath()\n tzpath = self.module.TZPATH\n self.assertSequenceEqual(tzpath, expected_result)\n\n def test_env_variable_relative_paths(self):\n test_cases = [\n [(\"path/to/somewhere\",), ()],\n [\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\",),\n ],\n [(\"../relative/path\",), ()],\n [\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\",),\n ],\n [(\"path/to/somewhere\", \"../relative/path\",), ()],\n [\n (\n \"/usr/share/zoneinfo\",\n \"path/to/somewhere\",\n \"../relative/path\",\n ),\n (\"/usr/share/zoneinfo\",),\n ],\n ]\n\n for input_paths, expected_paths in test_cases:\n path_var = os.pathsep.join(input_paths)\n with self.python_tzpath_context(path_var):\n with self.subTest(\"warning\", path_var=path_var):\n # Note: Per PEP 615 the warning is implementation-defined\n # behavior, other implementations need not warn.\n with self.assertWarns(self.module.InvalidTZPathWarning):\n self.module.reset_tzpath()\n\n tzpath = self.module.TZPATH\n with self.subTest(\"filtered\", path_var=path_var):\n self.assertSequenceEqual(tzpath, expected_paths)\n\n def test_reset_tzpath_kwarg(self):\n self.module.reset_tzpath(to=[\"/a/b/c\"])\n\n self.assertSequenceEqual(self.module.TZPATH, (\"/a/b/c\",))\n\n def test_reset_tzpath_relative_paths(self):\n bad_values = [\n (\"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"path/to/somewhere\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\", \"../relative/path\",),\n ]\n for input_paths in bad_values:\n with self.subTest(input_paths=input_paths):\n with self.assertRaises(ValueError):\n self.module.reset_tzpath(to=input_paths)\n\n def test_tzpath_type_error(self):\n bad_values = [\n \"/etc/zoneinfo:/usr/share/zoneinfo\",\n b\"/etc/zoneinfo:/usr/share/zoneinfo\",\n 0,\n ]\n\n for bad_value in bad_values:\n with self.subTest(value=bad_value):\n with self.assertRaises(TypeError):\n self.module.reset_tzpath(bad_value)\n\n def test_tzpath_attribute(self):\n tzpath_0 = [\"/one\", \"/two\"]\n tzpath_1 = [\"/three\"]\n\n with self.tzpath_context(tzpath_0):\n query_0 = self.module.TZPATH\n\n with self.tzpath_context(tzpath_1):\n query_1 = self.module.TZPATH\n\n self.assertSequenceEqual(tzpath_0, query_0)\n self.assertSequenceEqual(tzpath_1, query_1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TzPathTest","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_03.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom . import _support as test_support\nfrom ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass TestModule(ZoneInfoTestBase):\n module = py_zoneinfo\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @cached_property\n def _UTC_bytes(self):\n zone_file = self.zoneinfo_data.path_from_key(\"UTC\")\n with open(zone_file, \"rb\") as f:\n return f.read()\n\n def touch_zone(self, key, tz_root):\n \"\"\"Creates a valid TZif file at key under the zoneinfo root tz_root.\n\n tz_root must exist, but all folders below that will be created.\n \"\"\"\n if not os.path.exists(tz_root):\n raise FileNotFoundError(f\"{tz_root} does not exist.\")\n\n root_dir, *tail = key.rsplit(\"/\", 1)\n if tail: # If there's no tail, then the first component isn't a dir\n os.makedirs(os.path.join(tz_root, root_dir), exist_ok=True)\n\n zonefile_path = os.path.join(tz_root, key)\n with open(zonefile_path, \"wb\") as f:\n f.write(self._UTC_bytes)\n\n def test_getattr_error(self):\n with self.assertRaises(AttributeError):\n self.module.NOATTRIBUTE\n\n def test_dir_contains_all(self):\n \"\"\"dir(self.module) should at least contain everything in __all__.\"\"\"\n module_all_set = set(self.module.__all__)\n module_dir_set = set(dir(self.module))\n\n difference = module_all_set - module_dir_set\n\n self.assertFalse(difference)\n\n def test_dir_unique(self):\n \"\"\"Test that there are no duplicates in dir(self.module)\"\"\"\n module_dir = dir(self.module)\n module_unique = set(module_dir)\n\n self.assertCountEqual(module_dir, module_unique)\n\n def test_available_timezones(self):\n with self.tzpath_context([self.zoneinfo_data.tzpath]):\n self.assertTrue(self.zoneinfo_data.keys) # Sanity check\n\n available_keys = self.module.available_timezones()\n zoneinfo_keys = set(self.zoneinfo_data.keys)\n\n # If tzdata is not present, zoneinfo_keys == available_keys,\n # otherwise it should be a subset.\n union = zoneinfo_keys & available_keys\n self.assertEqual(zoneinfo_keys, union)\n\n def test_available_timezones_weirdzone(self):\n with tempfile.TemporaryDirectory() as td:\n # Make a fictional zone at \"Mars/Olympus_Mons\"\n self.touch_zone(\"Mars/Olympus_Mons\", td)\n\n with self.tzpath_context([td]):\n available_keys = self.module.available_timezones()\n self.assertIn(\"Mars/Olympus_Mons\", available_keys)\n\n def test_folder_exclusions(self):\n expected = {\n \"America/Los_Angeles\",\n \"America/Santiago\",\n \"America/Indiana/Indianapolis\",\n \"UTC\",\n \"Europe/Paris\",\n \"Europe/London\",\n \"Asia/Tokyo\",\n \"Australia/Sydney\",\n }\n\n base_tree = list(expected)\n posix_tree = [f\"posix/{x}\" for x in base_tree]\n right_tree = [f\"right/{x}\" for x in base_tree]\n\n cases = [\n (\"base_tree\", base_tree),\n (\"base_and_posix\", base_tree + posix_tree),\n (\"base_and_right\", base_tree + right_tree),\n (\"all_trees\", base_tree + right_tree + posix_tree),\n ]\n\n with tempfile.TemporaryDirectory() as td:\n for case_name, tree in cases:\n tz_root = os.path.join(td, case_name)\n os.mkdir(tz_root)\n\n for key in tree:\n self.touch_zone(key, tz_root)\n\n with self.tzpath_context([tz_root]):\n with self.subTest(case_name):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n\n def test_exclude_posixrules(self):\n expected = {\n \"America/New_York\",\n \"Europe/London\",\n }\n\n tree = list(expected) + [\"posixrules\"]\n\n with tempfile.TemporaryDirectory() as td:\n for key in tree:\n self.touch_zone(key, td)\n\n with self.tzpath_context([td]):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TestModule","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.10","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_04.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom . import _support as test_support\nfrom ._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass ExtensionBuiltTest(unittest.TestCase):\n \"\"\"Smoke test to ensure that the C and Python extensions are both tested.\n\n Because the intention is for the Python and C versions of ZoneInfo to\n behave identically, these tests necessarily rely on implementation details,\n so the tests may need to be adjusted if the implementations change. Do not\n rely on these tests as an indication of stable properties of these classes.\n \"\"\"\n\n def test_cache_location(self):\n # The pure Python version stores caches on attributes, but the C\n # extension stores them in C globals (at least for now)\n self.assertFalse(hasattr(c_zoneinfo.ZoneInfo, \"_weak_cache\"))\n self.assertTrue(hasattr(py_zoneinfo.ZoneInfo, \"_weak_cache\"))\n\n def test_gc_tracked(self):\n # The pure Python version is tracked by the GC but (for now) the C\n # version is not.\n import gc\n\n self.assertTrue(gc.is_tracked(py_zoneinfo.ZoneInfo))\n self.assertFalse(gc.is_tracked(c_zoneinfo.ZoneInfo))\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ExtensionBuiltTest","origin_revision":"v3.10.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_01.py","code":"from typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_02.py","code":"import typing\nx: typing.List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_03.py","code":"from typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: List[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> List[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_01.py","code":"from typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_02.py","code":"import typing\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_03.py","code":"from typing import List\nSomeAlias = list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: list[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> list[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_01.py","code":"x = lambda foo: None","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[lambdas do not have type annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_02.py","code":"from __future__ import annotations\nfrom typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_03.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not a PEP 585 type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_01.py","code":"open(\"foo\", encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop_before_315","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_02.py","code":"open(\"foo\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_03.py","code":"open(\"foo\", encoding=\"latin1\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"latin1\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_04.py","code":"open(\"foo\", encoding=\"us-ascii\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"us-ascii\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_05.py","code":"open(\"foo\", \"r\", \"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", \"r\", \"utf-8\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_06.py","code":"open(\"foo\", encoding=\"utf-8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[simple case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_07.py","code":"open(\"foo\", encoding=\"UTF8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[alternative spelling]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_08.py","code":"open(*args, encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_18.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"async def c(): return f'{await 1+foo()}'","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_18.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_01.py","code":"if s.startswith(\"foo\"):\n s = s[len(\"foo\"):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_02.py","code":"if s.startswith(S):\n s = s[len(S):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_03.py","code":"if s.endswith(\"foo\"):\n s = s[:-1 * len(\"foo\")]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_04.py","code":"if s.endswith(S):\n s = s[:-1 * len(S)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_05.py","code":"if s.startswith(x):\n s = s[len(x):] # TODO: removeprefix\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_06.py","code":"if True:\n if s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_07.py","code":"if True:\n something_else()\n if s.startswith(x):\n s = s[len(x):]\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_08.py","code":"if (\n x.startswith(y)\n):\n x = x[len(y):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_01.py","code":"s = s.removeprefix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_02.py","code":"s = s.removeprefix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_03.py","code":"s = s.removesuffix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_04.py","code":"s = s.removesuffix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_05.py","code":"s = s.removeprefix(x)\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_06.py","code":"if True:\n s = s.removeprefix(x)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_07.py","code":"if True:\n something_else()\n s = s.removeprefix(x)\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_08.py","code":"x = x.removeprefix(y)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_01.py","code":"if x.startswith(S):\n x = x[len(S):]\nelif x.endswith(T):\n x = x[:-1 * len(T)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop_before_39","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_02.py","code":"if s.startswith(\"a\"):\n s = s.lstrip(\"a\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[unrelated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_03.py","code":"if s.startswith(x):\n s = s[2:]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[cannot prove x is 2]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_04.py","code":"if s.startswith(x):\n s = s[len(x):]\nelse:\n print(\"no!)\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has else]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_05.py","code":"if something:\n print(\"something!\")\nelif s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has elif]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_01.py","code":"from typing import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_02.py","code":"import typing\nD = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": typing.Literal[\"b\", b\"c\"]})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_05.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {\n # first comment\n \"a\": int, # inline comment\n # second comment\n \"b\": str,\n # third comment\n}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_07.py","code":"from typing_extensions import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_08.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_09.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int}, total=True)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nFoo = TypedDict(\"Foo\", {\"lsts\": List[List[int]]})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_11.py","code":"import typing\nif True:\n if False:\n pass\n D = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_12.py","code":"from typing import TypedDict\nFoo = TypedDict(\"Foo\", {\"union\": str | int | None})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_01.py","code":"from typing import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_02.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_03.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_04.py","code":"import typing\nclass D(typing.TypedDict):\n a: typing.Literal['b', b'c']\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_05.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_06.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n # first comment\n a: int # inline comment\n # second comment\n b: str\n # third comment\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_07.py","code":"from typing_extensions import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_08.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_09.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict, total=True):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nclass Foo(TypedDict):\n lsts: List[List[int]]","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_11.py","code":"import typing\nif True:\n if False:\n pass\n class D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_12.py","code":"from typing import TypedDict\nclass Foo(TypedDict):\n union: str | int | None","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_01.py","code":"from wat import TypedDict\nQ = TypedDict(\"Q\")\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[from imported from elsewhere]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_02.py","code":"import typing\nD = typing.TypedDict(\"D\")","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {}, a=int)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[both]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_05.py","code":"import typing\nD = typing.TypedDict(\"D\", 1)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[not a dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {1: str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not a string]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_07.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a-b\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not an identifier]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_08.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"class\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is a keyword]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_09.py","code":"import typing\nD = typing.TypedDict(\"D\", {**d, \"a\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[dictionary splat operator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_10.py","code":"import typing\nC = typing.TypedDict(\"C\", *types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_11.py","code":"import typing\nD = typing.TypedDict(\"D\", **types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starstarkwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_12.py","code":"import typing\nD = typing.TypedDict(\"D\", x=int, total=False)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[kw_typed_dict with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_01.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_02.py","code":"import typing\nx: typing.Union[int]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_03.py","code":"import typing\nx: typing.Union[Foo[str, int], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_04.py","code":"import typing\nx: typing.Union[typing.List[str], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_05.py","code":"import typing\nx: typing.Union[int, str,]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_06.py","code":"import typing\nx: typing.Union[(int, str)]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_07.py","code":"import typing\nx: typing.Union[\n int,\n str\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_08.py","code":"import typing\nx: typing.Union[\n int,\n str,\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_09.py","code":"from typing import Optional\nx: Optional[str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_10.py","code":"import typing\nx: typing.Optional[\n ComplicatedLongType[int]\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: Optional[\"str\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_12.py","code":"from typing import Union, Sequence\ndef f(x: Union[Union[A, B], Sequence[Union[C, D]]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_13.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_14.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_15.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_16.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> Union[int, str]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_01.py","code":"from typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_02.py","code":"x: int\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_03.py","code":"x: Foo[str, int] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_04.py","code":"x: list[str] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_05.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_06.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_07.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_08.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_09.py","code":"from typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_10.py","code":"x: None | (\n ComplicatedLongType[int]\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_12.py","code":"from typing import Union\nfrom collections.abc import Sequence\ndef f(x: A | B | Sequence[C | D]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_13.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x})\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_14.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x}(\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_15.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x}(\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_16.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x})\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: int | str) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> int | str: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_01.py","code":"from __future__ import annotations\nfrom typing import Union\nSomeAlias = Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[<3.9 not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_02.py","code":"from typing import Union\ndef f() -> Union[()]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ empty Union]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_03.py","code":"from typing import Optional\ndef f() -> Optional[\"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Optional of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_04.py","code":"from typing import Union\ndef f() -> Union[int, \"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Union of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_05.py","code":"from typing import Union\ndef f() -> Union[1:2]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[invalid Union slicing]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack[Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack [Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_03.py","code":"from typing import Unpack\ndef f(*args: Unpack[tuple[int, ...]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_03.py","code":"from typing import Unpack\ndef f(*args: *tuple[int, ...]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_01.py","code":"from typing import Unpack\nfoo(Unpack())","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_02.py","code":"from typing import TypeVarTuple, Unpack\nShape = TypeVarTuple(\"Shape\")\nclass Foo(Unpack[Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not inside a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_03.py","code":"from typing import Unpack\nfrom typing import TypedDict\nclass D(TypedDict):\n x: int\ndef f(**kwargs: Unpack[D]) -> None: pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[3.12 TypedDict for kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_01.py","code":"from contextvars import ContextVar\nfrom types import MappingProxyType\nimport re\nimport collections\nimport time\n\n# Okay\nContextVar(\"cv\")\nContextVar(\"cv\", default=())\nContextVar(\"cv\", default=(1, 2, 3))\nContextVar(\"cv\", default=\"foo\")\nContextVar(\"cv\", default=tuple())\nContextVar(\"cv\", default=frozenset())\nContextVar(\"cv\", default=MappingProxyType({}))\nContextVar(\"cv\", default=re.compile(\"foo\"))\nContextVar(\"cv\", default=float(1))\nContextVar(\"cv\", default=frozenset[str]())\nContextVar[frozenset[str]](\"cv\", default=frozenset[str]())\n\n# Bad\nContextVar(\"cv\", default=[])\nContextVar(\"cv\", default={})\nContextVar(\"cv\", default=list())\nContextVar(\"cv\", default=set())\nContextVar(\"cv\", default=dict())\nContextVar(\"cv\", default=[char for char in \"foo\"])\nContextVar(\"cv\", default={char for char in \"foo\"})\nContextVar(\"cv\", default={char: idx for idx, char in enumerate(\"foo\")})\nContextVar(\"cv\", default=collections.deque())\nContextVar(\"cv\", default=set[str]())\nContextVar[set[str]](\"cv\", default=set[str]())\n\ndef bar() -> list[int]:\n return [1, 2, 3]\n\nContextVar(\"cv\", default=bar())\nContextVar(\"cv\", default=time.time())\n\ndef baz(): ...\nContextVar(\"cv\", default=baz())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_02.py","code":"from contextvars import ContextVar\n\nfrom fastapi import Query\nContextVar(\"cv\", default=Query(None))\n\nfrom something_else import Depends\nContextVar(\"cv\", default=Depends())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039_extended.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_01.py","code":"import typing\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, Sequence\n\nKNOWINGLY_MUTABLE_DEFAULT = []\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = []\n immutable_annotation: typing.Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: typing.ClassVar[list[int]] = []\n\n\n@dataclass\nclass B:\n mutable_default: list[int] = []\n immutable_annotation: Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: ClassVar[list[int]] = []\n\n# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n@dataclass\nclass AWithQuotes:\n mutable_default: 'list[int]' = []\n immutable_annotation: 'typing.Sequence[int]' = []\n without_annotation = []\n correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: 'list[int]' = field(default_factory=list)\n class_variable: 'typing.ClassVar[list[int]]'= []\n\n\n# Mutable defaults wrapped in field() calls\n@dataclass\nclass C:\n mutable_default: list[int] = field(default=[]) # RUF008\n mutable_default2: dict[str, int] = field(default={}) # RUF008\n mutable_default3: set[int] = field(default=set()) # RUF008\n mutable_default4: dict[str, int] = field(default=dict()) # RUF008\n correct_factory: list[int] = field(default_factory=list) # okay\n immutable_default: tuple[int, ...] = field(default=()) # okay\n immutable_default2: str = field(default=\"hello\") # okay\n immutable_default3: int = field(default=1) # okay\n non_mutable_var: list[int] = field(default=KNOWINGLY_MUTABLE_DEFAULT) # okay\n class_variable: ClassVar[list[int]] = field(default=[]) # okay\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_02.py","code":"# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n\nfrom __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Example():\n \"\"\"Class that uses ClassVar.\"\"\"\n\n options: ClassVar[dict[str, str]] = {}\n\n\nif typing.TYPE_CHECKING:\n from typing import ClassVar\n\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_03.py","code":"import datetime\nimport re\nimport typing\nfrom dataclasses import dataclass, field\nfrom fractions import Fraction\nfrom pathlib import Path\nfrom typing import ClassVar, NamedTuple\n\n\ndef default_function() -> list[int]:\n return []\n\n\nclass ImmutableType(NamedTuple):\n something: int = 8\n\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\n fine_path: Path = Path()\n fine_date: datetime.date = datetime.date(2042, 1, 1)\n fine_timedelta: datetime.timedelta = datetime.timedelta(hours=7)\n fine_tuple: tuple[int] = tuple([1])\n fine_regex: re.Pattern = re.compile(r\".*\")\n fine_float: float = float(\"-inf\")\n fine_int: int = int(12)\n fine_complex: complex = complex(1, 2)\n fine_str: str = str(\"foo\")\n fine_bool: bool = bool(\"foo\")\n fine_fraction: Fraction = Fraction(1, 2)\n\n\nDEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES = ImmutableType(40)\nDEFAULT_A_FOR_ALL_DATACLASSES = A([1, 2, 3])\n\n\n@dataclass\nclass B:\n hidden_mutable_default: list[int] = default_function()\n another_dataclass: A = A()\n not_optimal: ImmutableType = ImmutableType(20)\n good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES\n okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES\n\n fine_dataclass_function: list[int] = field(default_factory=list)\n\n\nclass IntConversionDescriptor:\n def __init__(self, *, default):\n self._default = default\n\n def __set_name__(self, owner, name):\n self._name = \"_\" + name\n\n def __get__(self, obj, type):\n if obj is None:\n return self._default\n\n return getattr(obj, self._name, self._default)\n\n def __set__(self, obj, value):\n setattr(obj, self._name, int(value))\n\n\n@dataclass\nclass InventoryItem:\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\n\n\n# Regression tests for:\n# https://github.com/astral-sh/ruff/issues/6447\nfrom typing import NewType\n\nListOfStrings = NewType(\"ListOfStrs\", list[str])\nStringsToInts = NewType(\"IntsToStrings\", dict[str, int])\n\nSpecialString = NewType(name=\"SpecialString\", tp=str)\nNegativeInteger = NewType(\"NegInt\", tp=int)\n\nInvalid1 = NewType(*Foo)\nInvalid2 = NewType(\"Invalid2\", name=Foo)\nInvalid3 = NewType(\"Invalid3\", name=Foo, lorem=\"ipsum\")\n\n@dataclass\nclass DataclassWithNewTypeFields:\n # Errors\n a: ListOfStrings = ListOfStrings([])\n b: StringsToInts = StringsToInts()\n c: Invalid1 = Invalid1()\n d: Invalid2 = Invalid2()\n e: Invalid3 = Invalid3()\n\n # No errors\n e: SpecialString = SpecialString(\"Lorem ipsum\")\n f: NegativeInteger = NegativeInteger(-110)\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/15772\ndef f() -> int:\n return 0\n\n@dataclass\nclass ShouldMatchB008RuleOfImmutableTypeAnnotationIgnored:\n this_is_not_fine: list[int] = default_function()\n # ignored\n this_is_fine: int = f()\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/17424\n@dataclass(frozen=True)\nclass C:\n foo: int = 1\n\n\n@dataclass\nclass D:\n c: C = C()\n\n\n@dataclass\nclass E:\n c: C = C()\n\n# https://github.com/astral-sh/ruff/issues/20266\n@dataclass(frozen=True)\nclass C:\n @dataclass(frozen=True)\n class D:\n foo: int = 1\n\n d: D = D() # OK","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_04.py","code":"from dataclasses import dataclass \nfrom typing import TYPE_CHECKING\n\n\ndef default_function() ->list[int]:\n return []\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\nif TYPE_CHECKING:\n from typing import ClassVar\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_05.py","code":"from dataclasses import InitVar, KW_ONLY, MISSING, dataclass, field\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n # Errors\n no_annotation = r\"foo\"\n missing = MISSING\n field = field()\n\n # No errors\n __slots__ = (\"foo\", \"bar\")\n __radd__ = __add__\n _private_attr = 100\n\n with_annotation: str\n with_annotation_and_default: int = 42\n with_annotation_and_field_specifier: bytes = field()\n\n class_var_no_arguments: ClassVar = 42\n class_var_with_arguments: ClassVar[int] = 42\n\n init_var_no_arguments: InitVar = \"lorem\"\n init_var_with_arguments: InitVar[str] = \"ipsum\"\n\n kw_only: KW_ONLY\n tu, ple, [unp, ack, ing] = (0, 1, 2, [3, 4, 5])\n mul, [ti, ple] = (a, ssign), ment = {1: b\"3\", \"2\": 4}, [6j, 5]\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_06.py","code":"from dataclasses import dataclass\nfrom enum import Enum, Flag, IntEnum, IntFlag, StrEnum, ReprEnum\n\nimport attr\nimport attrs\n\n\n## Errors\n\n@dataclass\nclass E(Enum): ...\n\n\n@dataclass # Foobar\nclass E(Flag): ...\n\n\n@dataclass()\nclass E(IntEnum): ...\n\n\n@dataclass() # Foobar\nclass E(IntFlag): ...\n\n\n@dataclass(\n frozen=True\n)\nclass E(StrEnum): ...\n\n\n@dataclass( # Foobar\n frozen=True\n)\nclass E(ReprEnum): ...\n\n\n@dataclass(\n frozen=True\n) # Foobar\nclass E(Enum): ...\n\n\n## No errors\n\n@attrs.define\nclass E(Enum): ...\n\n\n@attrs.frozen\nclass E(Enum): ...\n\n\n@attrs.mutable\nclass E(Enum): ...\n\n\n@attr.s\nclass E(Enum): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_01.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ntry: ...\nexcept* ValueError: ...\nexcept* KeyError: ...\nexcept * Error: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/except_star_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ntry: ...\nexcept* ValueError: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/except_star_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_01.py","code":"import typing\nimport typing_extensions\nfrom typing import Literal\n\n# Shouldn't affect non-union field types.\nfield1: Literal[1] # OK\n\n# Should emit for duplicate field types.\nfield2: Literal[1] | Literal[2] # Error\n\n# Should emit for union types in arguments.\ndef func1(arg1: Literal[1] | Literal[2]): # Error\n print(arg1)\n\n\n# Should emit for unions in return types.\ndef func2() -> Literal[1] | Literal[2]: # Error\n return \"my Literal[1]ing\"\n\n\n# Should emit in longer unions, even if not directly adjacent.\nfield3: Literal[1] | Literal[2] | str # Error\nfield4: str | Literal[1] | Literal[2] # Error\nfield5: Literal[1] | str | Literal[2] # Error\nfield6: Literal[1] | bool | Literal[2] | str # Error\n\n# Should emit for non-type unions.\nfield7 = Literal[1] | Literal[2] # Error\n\n# Should emit for parenthesized unions.\nfield8: Literal[1] | (Literal[2] | str) # Error\n\n# Should handle user parentheses when fixing.\nfield9: Literal[1] | (Literal[2] | str) # Error\nfield10: (Literal[1] | str) | Literal[2] # Error\n\n# Should emit for union in generic parent type.\nfield11: dict[Literal[1] | Literal[2], str] # Error\n\n# Should emit for unions with more than two cases\nfield12: Literal[1] | Literal[2] | Literal[3] # Error\nfield13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error\n\n# Should emit for unions with more than two cases, even if not directly adjacent\nfield14: Literal[1] | Literal[2] | str | Literal[3] # Error\n\n# Should emit for unions with mixed literal internal types\nfield15: Literal[1] | Literal[\"foo\"] | Literal[True] # Error\n\n# Shouldn't emit for duplicate field types with same value; covered by Y016\nfield16: Literal[1] | Literal[1] # OK\n\n# Shouldn't emit if in new parent type\nfield17: Literal[1] | dict[Literal[2], str] # OK\n\n# Shouldn't emit if not in a union parent\nfield18: dict[Literal[1], Literal[2]] # OK\n\n# Should respect name of literal type used\nfield19: typing.Literal[1] | typing.Literal[2] # Error\n\n# Should emit in cases with newlines\nfield20: typing.Union[\n Literal[\n 1 # test\n ],\n Literal[2],\n] # Error, newline and comment will not be emitted in message\n\n# Should handle multiple unions with multiple members\nfield21: Literal[1, 2] | Literal[3, 4] # Error\n\n# Should emit in cases with `typing.Union` instead of `|`\nfield22: typing.Union[Literal[1], Literal[2]] # Error\n\n# Should emit in cases with `typing_extensions.Literal`\nfield23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error\n\n# Should emit in cases with nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error\n\n# Should emit in cases with mixed `typing.Union` and `|`\nfield25: typing.Union[Literal[1], Literal[2] | str] # Error\n\n# Should emit only once in cases with multiple nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error\n\n# Should use the first literal subscript attribute when fixing\nfield25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error\n\nfrom typing import IO, Literal\n\nInlineOption = Literal[\"a\"] | Literal[\"b\"] | IO[str]\n\n# Should use unsafe fix when comments are deleted\nfield26: (\n # First comment\n Literal[\"a\", \"b\"]\n # Second comment\n | Literal[\"c\", \"d\"]\n)\nfield27: (\n Literal[\"a\", \"b\"] # First comment\n | Literal[\"c\", \"d\"] # Second comment\n)\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI030.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_02.py","code":"import typing\nfrom typing import Literal, TypeAlias, Union\n\nA: str | Literal[\"foo\"]\nB: TypeAlias = typing.Union[Literal[b\"bar\", b\"foo\"], bytes, str]\nC: TypeAlias = typing.Union[Literal[5], int, typing.Union[Literal[\"foo\"], str]]\nD: TypeAlias = typing.Union[Literal[b\"str_bytes\", 42], bytes, int]\nE: TypeAlias = typing.Union[typing.Union[typing.Union[typing.Union[Literal[\"foo\"], str]]]]\nF: TypeAlias = typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\nG: typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\n\ndef func(x: complex | Literal[1J], y: Union[Literal[3.14], float]): ...\n\n# OK\nA: Literal[\"foo\"]\nB: TypeAlias = Literal[b\"bar\", b\"foo\"]\nC: TypeAlias = typing.Union[Literal[5], Literal[\"foo\"]]\nD: TypeAlias = Literal[b\"str_bytes\", 42]\n\ndef func(x: Literal[1J], y: Literal[3.14]): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI051.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_03.py","code":"from typing import Literal\nimport typing as t\nimport typing_extensions\n\nx: Literal[True, False, True, False] # PYI062 twice here\n\ny: Literal[1, print(\"hello\"), 3, Literal[4, 1]] # PYI062 on the last 1\n\nz: Literal[{1, 3, 5}, \"foobar\", {1,3,5}] # PYI062 on the set literal\n\nLiteral[1, Literal[1]] # once\nLiteral[1, 2, Literal[1, 2]] # twice\nLiteral[1, Literal[1], Literal[1]] # twice\nLiteral[1, Literal[2], Literal[2]] # once\nt.Literal[1, t.Literal[2, t.Literal[1]]] # once\ntyping_extensions.Literal[1, 1, 1] # twice\nLiteral[\n 1, # comment\n Literal[ # another comment\n 1\n ]\n] # once\n\n# Ensure issue is only raised once, even on nested literals\nMyType = Literal[\"foo\", Literal[True, False, True], \"bar\"] # PYI062\n\nn: Literal[\"No\", \"duplicates\", \"here\", 1, \"1\"]\n\n\n# nested literals, all equivalent to `Literal[1]`\nLiteral[Literal[1]] # no duplicate\nLiteral[Literal[Literal[1], Literal[1]]] # once\nLiteral[Literal[1], Literal[Literal[Literal[1]]]] # once\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI062.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_01.py","code":"# parse_options: { \"target-version\": \"3.9\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/match_before_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_02.py","code":"match 2:\n case Class(x=x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_keyword_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_03.py","code":"match x:\n case [a] | [a]: ...\n case (x, y) | (x, y): ...\n case (x, (y | y)): ...\n case [a, _] | [a, _]: ...\n case [a] | [C(a)]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/different_match_pattern_bindings.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_04.py","code":"match x:\n case {x.a: 1, x.a: 2}: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/duplicate_match_key_attr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_05.py","code":"match x:\n case 2: ...\n case var: ...\nmatch x:\n case 2: ...\n case _: ...\nmatch x:\n case var if True: ... # don't try to refute a guarded pattern\n case 2: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/irrefutable_case_pattern_at_end.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_06.py","code":"# parse_options: { \"target-version\": \"3.10\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_after_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_07.py","code":"match foo:\n case foo_bar: ...\nmatch foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_08.py","code":"match foo:\n case case: ...\nmatch foo:\n case match: ...\nmatch foo:\n case type: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_09.py","code":"match foo:\n case match.bar: ...\n case case.bar: ...\n case type.bar: ...\n case match.case.type.bar.type.case.match: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_attr_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_10.py","code":"match foo:\n case _: ...\nmatch 1:\n case _: ...\nmatch 1.0:\n case _: ...\nmatch 1j:\n case _: ...\nmatch \"foo\":\n case _: ...\nmatch f\"foo {x}\":\n case _: ...\nmatch {1, 2}:\n case _: ...\nmatch ~foo:\n case _: ...\nmatch ...:\n case _: ...\nmatch not foo:\n case _: ...\nmatch await foo():\n case _: ...\nmatch lambda foo: foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_11.py","code":"match match:\n case _: ...\nmatch case:\n case _: ...\nmatch type:\n case _: ...\nmatch None:\n case _: ...\nmatch True:\n case _: ...\nmatch False:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_12.py","code":"match (1, 2) # Identifier\nmatch (1, 2): # Keyword\n case _: ...\nmatch [1:] # Identifier\nmatch [1, 2]: # Keyword\n case _: ...\nmatch * foo # Identifier\nmatch - foo # Identifier\nmatch -foo: # Keyword\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_or_identifier.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_13.py","code":"match subject:\n case [a, b]: ...\n case (a, b): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_parentheses_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_14.py","code":"match subject:\n case a if x: ...\n case a, b: ...\n case a, b if x: ...\n case a: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_15.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_16.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_17.py","code":"match 2:\n case Class(x) | [x] | x: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/multiple_assignment_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_18.py","code":"match ruff:\n case {\"lint\": {\"select\": x} | {\"extend-select\": x}} | {\"select\": x}:\n ...\nmatch 42:\n case [[x] | [x]] | x: ...\nmatch 42:\n case [[x | x] | [x]] | x: ...\nmatch 42:\n case ast.Subscript(n, ast.Constant() | ast.Slice()) | ast.Attribute(n): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/nested_alternative_patterns.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_19.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_01.py","code":"match[0]: int\nmatch [x, y, z]: dict\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_annotated_assignment.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_02.py","code":"match not in case\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_03.py","code":"match\nmatch != foo\n(foo, match)\n[foo, match]\n{foo, match}\nmatch;\nmatch: int\nmatch,\nmatch.foo\nmatch / foo\nmatch << foo\nmatch and foo\nmatch is not foo\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_04.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_01.py","code":"# parse_options: {\"target-version\": \"3.8\"}\ndef foo(a, /): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pos_only_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_02.py","code":"lambda: a\nlambda: 1\nlambda x: 1\nlambda x, y: ...\nlambda a, b, c: 1\nlambda a, b=20, c=30: 1\nlambda x, y: x * y\nlambda y, z=1: z * y\nlambda *a: a\nlambda *a, z, x=0: ...\nlambda *, a, b, c: 1\nlambda *, a, b=20, c=30: 1\nlambda a, b, c, *, d, e: 0\nlambda **kwargs: f()\nlambda *args, **kwargs: f() + 1\nlambda *args, a, b=1, **kwargs: f() + 1\nlambda a, /: ...\nlambda a, /, b: ...\nlambda a=1, /,: ...\nlambda a, b, /, *, c: ...\nlambda kw=1, *, a: ...\nlambda a, b=20, /, c=30: 1\nlambda a, b, /, c, *, d, e: 0\nlambda a, b, /, c, *d, e, **f: 0","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/lambda.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/param_with_star_annotation_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_05.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_06.py","code":"def foo(*args: *int | str): ...\ndef foo(*args: *(int or str)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_07.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_08.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/star_index_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_09.py","code":"*a\n*(a + 1)\n*x.attr\n\narray_slice = array[0, *indexes, -1]\narray[0, *indexes, -1] = array_slice\narray[*indexes_to_select, *indexes_to_select]\narray[3:5, *indexes_to_select]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/starred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_10.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nout[(*(slice(None) for _ in range(2)), *ind)] = 1\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_01.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/decorator_named_expression_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_03.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_function_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_04.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_05.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_comp_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_06.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{x := 1, 2, 3}\n{1, x := 2, 3}\n{1, 2, x := 3}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_literal_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_07.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/walrus_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_08.py","code":"# parse_options: { \"target-version\": \"3.9\" }\n@buttons[0].clicked.connect\ndef spam(): ...\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/decorator_expression_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_09.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_10.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_11.py","code":"[a := 0 for x in range(0)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_rebound_comprehension_variable.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_12.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[(x:=1)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_13.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{(x := 1), 2, 3}\n{(last := x) for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_14.py","code":"# parse_options: {\"target-version\": \"3.9\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_index_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_15.py","code":"# parse_options: {\"target-version\": \"3.9\"}\n{x := 1, 2, 3}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_16.py","code":"class F(y := list): ...\ndef f():\n class G((yield 1)): ...\n class H((yield from 1)): ...\nasync def f():\n class G((await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_17.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_function_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_18.py","code":"# parse_options: {\"target-version\": \"3.13\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_19.py","code":"# parse_options: { \"target-version\": \"3.8\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/walrus_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_20.py","code":"# This only tests the call arguments and not the expression before the opening parenthesis.\n\n# Simple\ncall()\ncall(x, y)\ncall(x, y,) # Trailing comma\ncall(x=1, y=2)\ncall(*x)\ncall(**x)\n\n# Order\ncall(x, y=1)\ncall(x, *y)\ncall(x, **y)\ncall(x=1, *y)\ncall(x=1, **y)\ncall(*x, **y)\ncall(*x, y, z)\ncall(**x, y=1, z=2)\ncall(*x1, *x2, **y1, **y2)\ncall(x=1, **y, z=1)\n\n# Keyword expression\ncall(x=1 if True else 2)\ncall(x=await y)\ncall(x=lambda y: y)\ncall(x=(y := 1))\n\n# Yield expression\ncall((yield x))\ncall((yield from x))\n\n# Named expression\ncall(x := 1)\ncall(x := 1 for i in iter)\n\n# Starred expressions\ncall(*x and y)\ncall(*x | y)\ncall(*await x)\ncall(*lambda x: x)\ncall(*x if True else y)\n\n# Double starred\ncall(**x)\ncall(**x and y)\ncall(**await x)\ncall(**x if True else y)\ncall(**(yield x))\ncall(**lambda x: x)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/arguments.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_21.py","code":"# Simple\n{}\n{1: 2}\n{1: 2, a: 1, b: 'hello'}\n\n# Mixed indentations\n{\n}\n{\n 1:\n 2,\n 3\n :4\n}\n\n# Nested\n{{1: 2}: {3: {4: 5}}}\n\n# Lambda expressions\n{lambda x: x: 1}\n{'A': lambda p: None, 'B': C,}\n\n# Named expressions\n{(x := 1): y}\n{(x := 1): (y := 2)}\n\n# Double star unpacking\n{**d}\n{a: b, **d}\n{**a, **b}\n{\"a\": \"b\", **c, \"d\": \"e\"}\n{1: 2, **{'nested': 'dict'}}\n{x * 1: y ** 2, **call()}\n# Here, `not` isn't allowed but parentheses resets the precedence\n{**(not x)}\n\n# Random expressions\n{1: x if True else y}\n{x if True else y: y for x in range(10) for y in range(10)}\n{{1, 2}: 3, x: {1: 2,},}\n{(x): (y), (z): (a)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/dictionary.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_22.py","code":"(x for target in iter)\n(x async for target in iter)\n(x for target in iter if x in y if a and b if c)\n(x for target1 in iter1 if x and y for target2 in iter2 if a > b)\n(x for target1 in iter1 if x and y async for target2 in iter2 if a > b)\n\n# Named expression\n(x := y + 1 for y in z)\n\n# If expression\n(x if y else y for y in z)\n\n# Arguments\n\" \".join(\n sql\n for sql in (\n \"LIMIT %d\" % limit if limit else None,\n (\"OFFSET %d\" % offset) if offset else None,\n )\n)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/generator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_23.py","code":"# Simple lists\n[]\n[1]\n[1,]\n[1, 2, 3]\n[1, 2, 3,]\n\n# Mixed with indentations\n[\n]\n[\n 1\n]\n[\n 1,\n 2,\n]\n\n# Nested\n[[[1]]]\n[[1, 2], [3, 4]]\n\n# Named expression\n[x := 2]\n[x := 2,]\n[1, x := 2, 3]\n\n# Star expression\n[1, *x, 3]\n[1, *x | y, 3]\n\n# Random expressions\n[1 + 2, [1, 2, 3, 4], (a, b + c, d), {a, b, c}, {a: 1}, x := 2]\n[call1(call2(value.attr()) for element in iter)]\n[item in xs]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/list.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_24.py","code":"(name := 0)\n(name := (x * y))\n(name := 1 + 1)\n(name := (*x, y))\n(name := x if True else y)\n(name := lambda x: x)\n(name := (yield x))\n(name := (yield from x))","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/named.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_25.py","code":"(expr)\n(expr)()\n(expr)()()()\n\n(a and b or c)\n(lambda x: x)\n(x := 2)\n(yield x)\n(yield from x)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/parenthesized.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_26.py","code":"# Simple sets\n{}\n{1}\n{1,}\n{1, 2, 3}\n{1, 2, 3,}\n\n# Mixed with indentations\n{\n}\n{\n 1\n}\n{\n 1,\n 2,\n}\n\n# Nested\n{{1}}\n{{1, 2}, {3, 4}}\n\n# Named expression\n{x := 2}\n{1, x := 2, 3}\n{1, (x := 2),}\n\n# Star expression\n{1, *x, 3}\n{1, *x | y, 3}\n\n# Random expressions\n{1 + 2, (a, b), {1, 2, 3}, {a: b, **d}}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/set.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_27.py","code":"# Various combinations\nx[:]\nx[1:]\nx[:2]\nx[1:2]\nx[::]\nx[1::]\nx[:2:]\nx[1:2:]\nx[::3]\nx[1::3]\nx[:2:3]\nx[1:2:3]\n\n# Named expression\nx[y := 2]\nx[(y := 2):]\nx[y := 2,]\n\n# These are two separate slice elements\nx[1,:2,]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/slice.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_28.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_29.py","code":"# With parentheses\n()\n(())\n((()), ())\n(a,)\n(a, b)\n(a, b,)\n((a, b))\n\n# Without parentheses\na,\na, b\na, b,\n\n# Starred expression\n*a,\na, *b\n*a | b, *await x, (), *()\n(*a,)\n(a, *b)\n(*a | b, *await x, (), *())\n\n# Named expression\n(x := 1,)\n(x, y := 2)\n(x, y := 2, z)\nx, (y := 2), z\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_30.py","code":"# Simple\n-1\n+1\n~1\nnot x\n\n# Multiple\n---1\n-+~1\nnot-+~1\nnot not x\n\n# Precedence check\n- await 1\n+ await 1 ** -2\n~(1, 2)\n-1 + 2\n\n# Precedence check for `not` operator because it is higher than other unary operators\nnot a and b or not c | d and not e\nnot (x := 1)\nnot a | (not b)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/unary_op.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_31.py","code":"yield\nyield x\nyield x + 1\nyield x and y\nyield call()\nyield [1, 2]\nyield {3, 4}\nyield {x: 5}\nyield x, y\nyield (x, y)\nyield x == y\nyield (x := 1)\nyield x, *y\nyield *x,\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_32.py","code":"yield from x\nyield from x + 1\nyield from x and y\nyield from call()\nyield from [1, 2]\nyield from {3, 4}\nyield from {x: 5}\nyield from (x, y)\nyield from x == y\nyield from (x := 1)\nyield from (x, *x | y)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield_from.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_33.py","code":"@function_decorator\ndef test():\n pass\n\n\n@class_decorator\nclass Test:\n pass\n\n\n@decorator\ndef f(): ...\n\n\n@a.b.c\ndef f(): ...\n\n\n@a\n@a.b.c\ndef f(): ...\n\n\n@a\n@1 | 2\n@a.b.c\nclass T: ...\n\n\n@x := 1\n@x if True else y\n@lambda x: x\n@x and y\n@(yield x)\n@(*x, *y)\ndef f(): ...\n\n\n# This is not multiple decorators on the same line but rather a binary (`@`) expression\n@x @y\ndef foo(): ...\n\n\n@x\n\n\n@y\n\n\ndef foo(): ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/other/decorator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_34.py","code":"# These test cases specifically tests out parsing a list of with items that start with a\n# left parenthesis. This makes parsing ambiguous as to whether the left parenthesis is to\n# parenthesize the with items or part of a parenthesized expression. It's not to test the\n# with statement itself.\n\n# The following sections basically separates between which node does the\n# start parenthesis belongs to.\n\n# Parenthesized with items\n# ------------------------\n#\n# - The opening parenthesis belongs to the with statement.\n# - The range of the first with item shouldn't include the parenthesis.\nwith (item): ...\nwith (item,): ... # with a trailing comma\nwith (((item))): ...\nwith (item1, item2): ...\nwith (item1, item2,): ... # with a trailing comma\nwith ((item1), (item2), item3 as f, (item4)): ...\nwith ((item1, item2), item3): ...\nwith ((x, y) as f): ...\nwith (item1 as f1, item2 as f2): ...\nwith (item1 as f1, item2 as f2,): ... # with a trailing comma\nwith (item == 10,): ...\nwith ((item := 10)): ...\nwith ((item := 10,)): ...\nwith ((*item,)): ...\nwith ((item1 := 10), item2): ...\nwith (item1 as f, (item2 := 10)): ...\nwith (foo()): ...\nwith (foo(),): ...\nwith (foo() as f): ...\nwith (f\"{item := 42}\"): ...\nwith (f\"{(item := 42)}\"): ...\nwith ((x for x in range(10)), item): ...\nwith (item, (x for x in range(10))): ...\nwith (item, (x for x in range(10)), item): ...\nwith (data[1:2]): ...\nwith (data[1:2] as f): ...\nwith ((x for x in iter) as y): ...\n\n# Parenthesized expression\n# ------------------------\n#\n# - The opening parenthesis belongs to the context expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (item) as f: ...\nwith (item := 10): ...\nwith (item := 10) as f: ...\nwith ( item := 1 ): ...\nwith (item1 := 42), item2: ...\nwith (root + filename).read(): ... # Postfix expression\nwith (root + filename).read() as f: ... # Postfix expression\nwith (foo)(): ... # Postfix expression\nwith (foo)() as f: ... # Postfix expression\nwith (foo()) as f: ...\nwith (data[1:2]) as f: ...\nwith (1, 2, 3)[0]: ... # Postfix expression\nwith (1, 2, 3)[0] as f: ... # Postfix expression\nwith (item1), (item2): ...\nwith (open('a.py')), (open('b.py')): ...\nwith (yield x): ...\nwith ((yield x)): ...\nwith (yield from x): ...\nwith ((yield from x)): ...\nwith (yield x) as f: ...\nwith (yield x,) as f: ...\n\n\n# Tuple expression\n# ----------------\n#\n# - This is a sub-case of the parenthesized expression and requires transforming the list of\n# with items from the speculative parsing to a single with item containing a tuple expression.\n# - The opening parenthesis belongs to the tuple expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (): ...\nwith () as f: ...\nwith (item := 42,): ...\nwith (1, item := 2): ...\nwith (item1 := 10, item2): ...\nwith (item1, item2 := 2, item3) as f: ...\nwith (item,) as f: ...\nwith (*item,): ...\nwith (*item,) as f: ...\nwith (item1, item2) as f: ...\nwith (item1, item2,) as f: ...\nwith (item1, item2), item3: ...\nwith ((item1, item2), item3) as f: ...\nwith (item1,), item2, (item3, item4) as f: ...\nwith (item1, item2) as f1, item3 as f2: ...\nwith (item1, *item2): ...\nwith (item1, *item2) as f: ...\nwith (item1 := 10, *item2): ...\nwith ((item1 := 10), *item2): ...\n\n\n# Parenthesized generator expression\n# ----------------------------------\n#\n# - The opening parenthesis belongs to the generator expression\n# - The range of the with item should include the parenthesis\nwith (x for x in range(10)): ...\nwith (x async for x in range(10)): ...\nwith (x for x in range(10)), item: ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/ambiguous_lpar_with_items.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_35.py","code":"if 1: 10\nelif 2: 20\nelse: 30\n\nif True:\n 1\n ...\nif x < 1:\n ...\nelse:\n pass\n\nif a:\n pass\nelif b:\n ...\n\nif a and b:\n ...\nelif True:\n ...\nelif c:\n ...\nelif d:\n ...\nelse:\n f()\n\n# Valid test expression\nif a := b: ...\nelif a := b: ...\nif lambda x: x: ...\nelif lambda x: x: ...\nif await x: ...\nelif await x: ...\nif (yield x): ...\nelif (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/if.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_36.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_37.py","code":"return\nreturn x\nreturn *x, *y\nreturn (x := 1)\nreturn None\nreturn x and y\nreturn 1 < 2\nreturn 1, 2,\nreturn call()\nreturn attr.value()\nreturn await x\nreturn lambda x: y\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/return.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_38.py","code":"while x:\n ...\n\nwhile (x > 1) and y:\n pass\nelse:\n ...\n\nwhile x and y:\n ...\n print('Hello World!')\n\nelse:\n print('Olá, Mundo!')\n ...\n\nwhile a := b: ...\nwhile (a := b) and c: ...\nwhile lambda x: x: ...\nwhile await x: ...\n\nif True:\n while x:\n pass\n else:\n pass\nelse:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/while.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.11","idiom_id":"annotated","pep":"593","introduced_in":"3.9","form":"modern","file":"annotated/modern_01.py","code":"\"\"\"\nTests the typing.Annotated special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#annotated\n\n# > The first argument to Annotated must be a valid type\n\nfrom dataclasses import InitVar, dataclass\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Literal,\n NotRequired,\n Required,\n TypeAlias,\n TypeVar,\n TypedDict,\n Union,\n)\n\nT = TypeVar(\"T\")\n\n\nGood1: Annotated[Union[int, str], \"\"]\nGood2: Annotated[int | None, \"\"]\nGood3: Annotated[list[int], \"\"]\nGood4: Annotated[Any, \"\"]\nGood5: Annotated[tuple[int, ...] | list[int], \"\"]\nGood6: Annotated[Callable[..., int], \"\"]\nGood7: Annotated[\"int | str\", \"\"]\nGood8: Annotated[list[\"int | str\"], \"\"]\n\n\nBad1: Annotated[[int, str], \"\"] # E: invalid type expression\nBad2: Annotated[((int, str),), \"\"] # E: invalid type expression\nBad3: Annotated[[int for i in range(1)], \"\"] # E: invalid type expression\nBad4: Annotated[{\"a\": \"b\"}, \"\"] # E: invalid type expression\nBad5: Annotated[(lambda: int)(), \"\"] # E: invalid type expression\nBad6: Annotated[[int][0], \"\"] # E: invalid type expression\nBad7: Annotated[int if 1 < 3 else str, \"\"] # E: invalid type expression\nBad8: Annotated[var1, \"\"] # E: invalid type expression\nBad9: Annotated[True, \"\"] # E: invalid type expression\nBad10: Annotated[1, \"\"] # E: invalid type expression\nBad11: Annotated[list or set, \"\"] # E: invalid type expression\nBad12: Annotated[f\"{'int'}\", \"\"] # E: invalid type expression\n\n\n# > Multiple type annotations are supported (Annotated supports variadic arguments):\n\nMulti1: Annotated[int | str, 3, \"\"]\nMulti2: Annotated[int | str, 3, \"\", lambda x: x, max(1, 2)]\n\n# > Annotated must be called with at least two arguments ( Annotated[int] is not valid)\n\nBad13: Annotated[int] # E: requires at least two arguments\n\n\n# > Annotated types can be nested\n\nNested1: list[Annotated[dict[str, Annotated[str, \"\"]], \"\"]]\nNested2: Annotated[list[Annotated[dict[str, Annotated[Literal[1, 2, 3], \"\"]], \"\"]], \"\"]\n\n\n# > Annotated is not type compatible with type or type[T]\nSmallInt: TypeAlias = Annotated[int, \"\"]\n\nnot_type1: type[Any] = Annotated[int, \"\"] # E\nnot_type2: type[Any] = SmallInt # E\n\n\ndef func4(x: type[T]) -> T:\n return x()\n\n\nfunc4(Annotated[str, \"\"]) # E\nfunc4(SmallInt) # E\n\n\n# > An attempt to call Annotated (whether parameterized or not) should be\n# > treated as a type error by type checkers.\n\nAnnotated() # E\nAnnotated[int, \"\"]() # E\nSmallInt(1) # E\n\n\nclass ClassA:\n a: ClassVar[Annotated[int, \"\"]] = 1\n b: Annotated[ClassVar[int], \"\"] = 1\n c: Final[Annotated[int, \"\"]] = 1\n d: Annotated[Final[int], \"\"] = 1\n\n\n@dataclass\nclass ClassB:\n a: InitVar[Annotated[int, \"\"]]\n b: Annotated[InitVar[int], \"\"]\n\n\nclass ClassC(TypedDict):\n a: Annotated[Required[int], \"\"]\n b: Required[Annotated[int, \"\"]]\n c: Annotated[NotRequired[int], \"\"]\n d: NotRequired[Annotated[int, \"\"]]\n\n\nTA1: TypeAlias = Annotated[int | str, \"\"]\nTA2 = Annotated[Literal[1, 2], \"\"]\nTA3 = Annotated[T, \"\"]\n","source":"typing_tests","origin":"conformance/tests/qualifiers_annotated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_07.py","code":"\"\"\"\nTests the handling of builtins.type[T].\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#type\n\n\nfrom typing import Any, Callable, Generic, Type, TypeAlias, TypeVar, assert_type\n\n\nclass User:\n ...\n\n\nclass BasicUser(User):\n ...\n\n\nclass ProUser(User):\n ...\n\n\nclass TeamUser(User):\n ...\n\n\ndef func1(user_class: type) -> User:\n return user_class()\n\n\ndef func2(user_class: type[User]) -> User:\n return user_class()\n\n\nU = TypeVar(\"U\", bound=User)\n\n\ndef func3(user_class: type[U]) -> U:\n return user_class()\n\n\nassert_type(func1(TeamUser), User)\nassert_type(func2(TeamUser), User)\nassert_type(func3(TeamUser), TeamUser)\n\n\n# > Note that it is legal to use a union of classes as the parameter for type[].\n\n\ndef func4(user_class: type[BasicUser | ProUser]) -> User:\n return user_class()\n\n\nassert_type(func4(BasicUser), User)\nassert_type(func4(ProUser), User)\nfunc4(TeamUser) # E\n\n\n# > Any other special constructs like Callable are not allowed as an argument to type.\n\nT = TypeVar(\"T\")\n\n\ndef func5(x: type[T]) -> None:\n pass\n\n\nfunc5(User) # OK\nfunc5(tuple) # OK\nfunc5(Callable) # E\n\n\n# > When type is parameterized it requires exactly one parameter. Plain type\n# > without brackets, the root of Python’s metaclass hierarchy, is equivalent to type[Any].\n\nbad_type1: type[int, str] # E\n\n\nclass MyMetaA(type):\n ...\n\n\ndef func6(a: type, b: type[Any]):\n assert_type(a, type[Any])\n a = b # OK\n b = a # OK\n a = type # OK\n b = type # OK\n\n\n# > Regarding the behavior of type[Any] (or type), accessing attributes of a\n# > variable with this type only provides attributes and methods defined by\n# > type (for example, __repr__() and __mro__). Such a variable can be called\n# > with arbitrary arguments, and the return type is Any.\n\n\ndef func7(a: type, b: type[Any], c: Type, d: Type[Any]):\n assert_type(a.__mro__, tuple[type, ...])\n assert_type(a.unknown, Any)\n assert_type(a.unknown(), Any)\n\n assert_type(b.__mro__, tuple[type, ...])\n assert_type(b.unknown, Any)\n assert_type(b.unknown(), Any)\n\n assert_type(c.__mro__, tuple[type, ...])\n assert_type(c.unknown, Any)\n assert_type(c.unknown(), Any)\n\n assert_type(d.__mro__, tuple[type, ...])\n assert_type(d.unknown, Any)\n assert_type(d.unknown(), Any)\n\n\ndef func8(a: type[object], b: Type[object]):\n assert_type(a.__name__, str)\n a.unknown # E\n\n assert_type(b.__name__, str)\n b.unknown # E\n\n\n# > type is covariant in its parameter, because type[Derived] is a subtype of type[Base]:\n\n\ndef func9(pro_user_class: type[ProUser]):\n assert_type(func3(pro_user_class), ProUser)\n\n\nTA1: TypeAlias = Type\nTA2: TypeAlias = Type[Any]\nTA3: TypeAlias = type\nTA4: TypeAlias = type[Any]\n\n\ndef func10(a: TA1, b: TA2, c: TA3, d: TA4):\n assert_type(a, type[Any])\n assert_type(b, type[Any])\n assert_type(c, type[Any])\n assert_type(d, type[Any])\n\n\nTA1.unknown # E\nTA2.unknown # E\nTA3.unknown # E\nTA4.unknown # E\n\nTA7: TypeAlias = type[T]\nTA8: TypeAlias = Type[T]\n\n\ndef func11(t1: TA7[T]) -> T:\n return t1()\n\n\ndef func12(t1: TA8[T]) -> T:\n return t1()\n\n\nassert_type(func11(int), int)\nassert_type(func12(int), int)\n\n\ndef func13(v: type):\n x1: Callable[..., Any] = v # OK\n x2: Callable[[int, int], int] = v # OK\n x3: object = v # OK\n x4: type = v # OK\n x5: type[int] = v # OK\n x6: type[Any] = v # OK\n\n\nclass ClassA(Generic[T]):\n def method1(self, v: type) -> type[T]:\n return v # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_type.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_08.py","code":"\"\"\"\nTests the handling of builtins.tuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#tuple-type-form\n\n# > The type of a tuple can be expressed by listing the element types.\nfrom typing import Literal\n\n\nt1: tuple[int] = (1,) # OK\nt1 = (1, 2) # E\nt2: tuple[int, int] = (1, 2) # OK\nt2 = (1,) # E\nt2 = (1, \"\") # E\n\n\ndef func1() -> tuple[Literal[1], Literal[2]]:\n return (1, 2)\n\n\n# > The empty tuple can be typed as tuple[()].\n\nt10: tuple[()] = () # OK\nt10 = (1,) # E\n\n\ndef func2() -> list[tuple[()]]:\n return [(), (), ()]\n\n\n# > Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis.\nt20: tuple[int, ...] = () # OK\nt20 = (1,) # OK\nt20 = (1, 2, 3, 4) # OK\nt20 = (1, 2, 3, \"\") # E\n\n\nt30: tuple[int, ...] # OK\nt31: tuple[int, int, ...] # E\nt32: tuple[...] # E\nt33: tuple[..., int] # E\nt34: tuple[int, ..., int] # E\nt35: tuple[*tuple[str], ...] # E\nt36: tuple[*tuple[str, ...], ...] # E\n","source":"typing_tests","origin":"conformance/tests/tuples_type_form.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_01.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a base class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Generic, TypeVar, dataclass_transform\n\nT = TypeVar(\"T\")\n\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelBase:\n not_a_field: str\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n def __init__(self, not_a_field: str) -> None:\n self.not_a_field = not_a_field\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen dataclass cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass GenericModelBase(Generic[T]):\n not_a_field: T\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass GenericCustomer(GenericModelBase[int]):\n id: int = model_field()\n\n\ngc_1 = GenericCustomer(id=3)\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelBaseFrozen:\n not_a_field: str\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_02.py","code":"\"\"\"\nTests the dataclass_transform mechanism supports the \"converter\" parameter\nin a field specifier class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#converters\n\nfrom typing import (\n Any,\n Callable,\n TypeVar,\n dataclass_transform,\n overload,\n)\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n\ndef model_field(\n *,\n converter: Callable[[S], T],\n default: S | None = None,\n default_factory: Callable[[], S] | None = None,\n) -> T:\n raise NotImplementedError\n\n\n@dataclass_transform(field_specifiers=(model_field,))\nclass ModelBase:\n ...\n\n\n# > The converter must be a callable that must accept a single positional\n# > argument (but may accept other optional arguments, which are ignored for\n# > typing purposes).\n\n\ndef bad_converter1() -> int:\n return 0\n\n\ndef bad_converter2(*, x: int) -> int:\n return 0\n\n\nclass DC1(ModelBase):\n field1: int = model_field(converter=bad_converter1) # E\n field2: int = model_field(converter=bad_converter2) # E\n\n\n# > The type of the first positional parameter provides the type of the\n# > synthesized __init__ parameter for the field.\n\n# > The return type of the callable must be assignable to the field’s\n# > declared type.\n\n\ndef converter_simple(s: str) -> int:\n return int(s)\n\n\ndef converter_with_param_before_args(s: str, *args: int, **kwargs: int) -> int:\n return int(s)\n\n\ndef converter_with_args(*args: str) -> int:\n return int(args[0])\n\n\n@overload\ndef overloaded_converter(s: str) -> int:\n ...\n\n\n@overload\ndef overloaded_converter(s: list[str]) -> int:\n ...\n\n\ndef overloaded_converter(s: str | list[str], *args: str) -> int | str:\n return 0\n\n\nclass ConverterClass:\n @overload\n def __init__(self, val: str) -> None:\n ...\n\n @overload\n def __init__(self, val: bytes) -> None:\n ...\n\n def __init__(self, val: str | bytes) -> None:\n pass\n\n\nclass DC2(ModelBase):\n field0: int = model_field(converter=converter_simple)\n field1: int = model_field(converter=converter_with_param_before_args)\n field2: int = model_field(converter=converter_with_args)\n field3: ConverterClass = model_field(converter=ConverterClass)\n field4: int = model_field(converter=overloaded_converter)\n field5: dict[str, str] = model_field(converter=dict, default=())\n\n\nDC2(1, \"f1\", \"f2\", b\"f3\", []) # E\nDC2(\"f0\", \"f1\", \"f2\", 1, []) # E\nDC2(\"f0\", \"f1\", \"f2\", \"f3\", 3j) # E\n\n\ndc1 = DC2(\"f0\", \"f1\", \"f2\", b\"f6\", [])\n\ndc1.field0 = \"f1\"\ndc1.field3 = \"f6\"\ndc1.field3 = b\"f6\"\n\ndc1.field0 = 1 # E\ndc1.field3 = 1 # E\n\ndc2 = DC2(\"f0\", \"f1\", \"f2\", \"f6\", \"1\", ((\"a\", \"1\"), (\"b\", \"2\")))\n\n\n# > If default or default_factory are provided, the type of the default value\n# > should be assignable to the first positional parameter of the converter.\n\n\nclass DC3(ModelBase):\n field0: int = model_field(converter=converter_simple, default=\"\")\n field1: int = model_field(converter=converter_simple, default=1) # E\n\n field2: int = model_field(converter=converter_simple, default_factory=str)\n field3: int = model_field(converter=converter_simple, default_factory=int) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_converter.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_03.py","code":"\"\"\"\nTests the dataclass_transform mechanism honors implicit default values\nin field parameters.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#field-specifier-parameters\n\nfrom typing import Any, Callable, Literal, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n# > Field specifier functions can use overloads that implicitly specify the\n# > value of init using a literal bool value type (Literal[False] or Literal[True]).\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any],\n init: Literal[False] = False,\n) -> Any:\n ...\n\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: None = None,\n init: Literal[True] = True,\n) -> Any:\n ...\n\n\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any] | None = None,\n init: bool = True,\n) -> Any:\n ...\n\n\ndef field2(*, init: bool = False, kw_only: bool = True) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(kw_only_default=True, field_specifiers=(field1, field2))\ndef create_model(*, init: bool = True) -> Callable[[type[T]], type[T]]:\n raise NotImplementedError\n\n\n@create_model()\nclass CustomerModel1:\n id: int = field1(resolver=lambda: 0)\n name: str = field1(default=\"Voldemort\")\n\n\nCustomerModel1()\nCustomerModel1(name=\"hi\")\n\n# This should generate an error because \"id\" is not\n# supposed to be part of the init function.\nCustomerModel1(id=1, name=\"hi\") # E\n\n\n@create_model()\nclass CustomerModel2:\n id: int = field2()\n name: str = field2(init=True)\n\n\n# This should generate an error because kw_only is True\n# by default for field2.\nCustomerModel2(1) # E\n\nCustomerModel2(name=\"Fred\")\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_field.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_04.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a decorator function.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Callable, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n\n@overload\n@dataclass_transform(kw_only_default=True, order_default=True)\ndef create_model(cls: T) -> T:\n ...\n\n\n@overload\ndef create_model(\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n) -> Callable[[T], T]:\n ...\n\n\ndef create_model(*args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n\n@create_model(kw_only=False, order=False)\nclass Customer1:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2Subclass(Customer2):\n salary: float\n\n\nc1_1 = Customer1(id=3, name=\"Sue\")\nc1_1.id = 4\n\nc1_2 = Customer1(3, \"Sue\")\nc1_2.name = \"Susan\"\n\n# This should generate an error because of a type mismatch.\nc1_2.name = 3 # E\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\n# This should generate an error because salary is not\n# a defined field.\nc1_3 = Customer1(id=3, name=\"Sue\", salary=40000) # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_2 = Customer2(0, \"John\") # E\n\nv2 = c2_1 < c2_2\n\n\n@dataclass_transform(kw_only_default=True, order_default=True, frozen_default=True)\ndef create_model_frozen(cls: T) -> T:\n raise NotImplementedError\n\n\n@create_model_frozen\nclass Customer3:\n id: int\n name: str\n\n\n# This should generate an error because a non-frozen class\n# cannot inherit from a frozen class.\n@create_model # E[Customer3Subclass]\nclass Customer3Subclass(Customer3): # E[Customer3Subclass]\n age: int\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_func.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_05.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a metaclass.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\n\nfrom typing import Any, dataclass_transform\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelMeta(type):\n not_a_field: str\n\n def __init__(self, *args, **kwargs) -> None:\n self.not_a_field: str = \"not a field\"\n\n\nclass ModelBase(metaclass=ModelMeta):\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen class cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1, frozen=False): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\n# OK (other_name is optional).\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelMetaFrozen(type):\n pass\n\n\nclass ModelBaseFrozen(metaclass=ModelMetaFrozen):\n ...\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_meta.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_07.py","code":"\"\"\"\nTests the handling of descriptors within a dataclass.\n\"\"\"\n\n# This portion of the dataclass spec is under-specified in the documentation,\n# but its behavior can be determined from the runtime implementation.\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, TypeVar, assert_type, overload\n\nT = TypeVar(\"T\")\n\n\nclass Desc1:\n @overload\n def __get__(self, __obj: None, __owner: Any) -> \"Desc1\":\n ...\n\n @overload\n def __get__(self, __obj: object, __owner: Any) -> int:\n ...\n\n def __get__(self, __obj: object | None, __owner: Any) -> \"int | Desc1\":\n raise NotImplementedError\n\n def __set__(self, __obj: object, __value: int) -> None:\n ...\n\n\n@dataclass\nclass DC1:\n y: Desc1 = Desc1()\n\n\ndc1 = DC1(3)\n\nassert_type(dc1.y, int)\nassert_type(DC1.y, Desc1)\n\n\nclass Desc2(Generic[T]):\n @overload\n def __get__(self, instance: None, owner: Any) -> list[T]:\n ...\n\n @overload\n def __get__(self, instance: object, owner: Any) -> T:\n ...\n\n def __get__(self, instance: object | None, owner: Any) -> list[T] | T:\n raise NotImplementedError\n\n\n@dataclass\nclass DC2:\n x: Desc2[int]\n y: Desc2[str]\n z: Desc2[str] = Desc2()\n\n\nassert_type(DC2.x, list[int])\nassert_type(DC2.y, list[str])\nassert_type(DC2.z, list[str])\n\ndc2 = DC2(Desc2(), Desc2(), Desc2())\nassert_type(dc2.x, int)\nassert_type(dc2.y, str)\nassert_type(dc2.z, str)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_descriptors.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_08.py","code":"\"\"\"\nTests validation of frozen dataclass instances.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#frozen-instances\n\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass DC1:\n a: float\n b: str\n\ndc1 = DC1(1, \"\")\n\ndc1.a = 1 # E: dataclass is frozen\ndc1.b = \"\" # E: dataclass is frozen\n\n\n# This should generate an error because a non-frozen dataclass\n# cannot inherit from a frozen dataclass.\n@dataclass # E[DC2]\nclass DC2(DC1): # E[DC2]\n pass\n\n@dataclass\nclass DC3:\n a: int\n\n# This should generate an error because a frozen dataclass\n# cannot inherit from a non-frozen dataclass.\n@dataclass(frozen=True) # E[DC4]\nclass DC4(DC3): # E[DC4]\n pass\n\n\n@dataclass(frozen=True)\nclass DC1Child(DC1):\n # This should be allowed because attributes within a frozen\n # dataclass are covariant rather than invariant.\n a: int\n","source":"typing_tests","origin":"conformance/tests/dataclasses_frozen.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_09.py","code":"\"\"\"\nTests the synthesis of the __hash__ method in a dataclass.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Callable, Hashable, assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n\n\nassert_type(DC1.__hash__, None)\n\n# These should generate errors because DC1 isn't hashable.\nDC1(0).__hash__() # E\nv1: Hashable = DC1(0) # E\n\n\n@dataclass(eq=True, frozen=True)\nclass DC2:\n a: int\n\n\ndc2_hash: Callable[..., int] = DC2.__hash__ # OK\nDC2(0).__hash__() # OK\nv2: Hashable = DC2(0) # OK\n\n\n@dataclass(eq=True)\nclass DC3:\n a: int\n\n\nassert_type(DC3.__hash__, None)\n\n# These should generate errors because DC3 isn't hashable.\nDC3(0).__hash__() # E\nv3: Hashable = DC3(0) # E\n\n\n@dataclass(frozen=True)\nclass DC4:\n a: int\n\n\ndc4_hash: Callable[..., int] = DC4.__hash__ # OK\nDC4(0).__hash__() # OK\nv4: Hashable = DC4(0) # OK\n\n\n@dataclass(eq=True, unsafe_hash=True)\nclass DC5:\n a: int\n\n\ndc5_hash: Callable[..., int] = DC5.__hash__ # OK\nDC5(0).__hash__() # OK\nv5: Hashable = DC5(0) # OK\n\n\n@dataclass(eq=True)\nclass DC6:\n a: int\n\n def __hash__(self) -> int:\n return 0\n\n\ndc6_hash: Callable[..., int] = DC6.__hash__ # OK\nDC6(0).__hash__() # OK\nv6: Hashable = DC6(0) # OK\n\n\n@dataclass(frozen=True)\nclass DC7:\n a: int\n\n def __eq__(self, other) -> bool:\n return self.a == other.a\n\n\ndc7_hash: Callable[..., int] = DC7.__hash__ # OK\nDC7(0).__hash__() # OK\nv7: Hashable = DC7(0) # OK\n","source":"typing_tests","origin":"conformance/tests/dataclasses_hash.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_10.py","code":"\"\"\"\nTests inheritance rules for dataclasses.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#inheritance\n\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar\n\n\n@dataclass\nclass DC1:\n a: int\n b: str = \"\"\n\n\n@dataclass\nclass DC2(DC1):\n b: str = \"\"\n a: int = 1\n\n\ndc2_1 = DC2(1, \"\")\n\ndc2_2 = DC2()\n\n\n@dataclass\nclass DC3:\n x: float = 15.0\n y: str = \"\"\n\n\n@dataclass\nclass DC4(DC3):\n z: tuple[int] = (10,)\n x: float = 15\n\n\ndc4_1 = DC4(0.0, \"\", (1,))\n\n\n@dataclass\nclass DC5:\n # While this generates an error at runtime for the stdlib dataclass,\n # other libraries that use dataclass_transform don't have similar\n # restrictions. It is therefore not required that a type checker\n # report an error here.\n x: list[int] = [] # E?\n\n\n@dataclass\nclass DC6:\n x: int\n y: ClassVar[int] = 1\n\n\n@dataclass\nclass DC7(DC6):\n # This should generate an error because a ClassVar cannot override\n # an instance variable of the same name.\n x: ClassVar[int] # E\n\n # This should generate an error because an instance variable cannot\n # override a class variable of the same name.\n y: int # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_11.py","code":"\"\"\"\nTests the keyword-only feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY, field\n\n\n@dataclass\nclass DC1:\n a: str\n _: KW_ONLY\n b: int = 0\n\n\nDC1(\"hi\")\nDC1(a=\"hi\")\nDC1(a=\"hi\", b=1)\nDC1(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC1(\"hi\", 1) # E\n\n\n@dataclass\nclass DC2:\n b: int = field(kw_only=True, default=3)\n a: str\n\n\nDC2(\"hi\")\nDC2(a=\"hi\")\nDC2(a=\"hi\", b=1)\nDC2(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC2(\"hi\", 1) # E\n\n\n@dataclass(kw_only=True)\nclass DC3:\n a: str = field(kw_only=False)\n b: int = 0\n\n\nDC3(\"hi\")\nDC3(a=\"hi\")\nDC3(a=\"hi\", b=1)\nDC3(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC3(\"hi\", 1) # E\n\n\n@dataclass\nclass DC4(DC3):\n c: float\n\n\nDC4(\"\", 0.2, b=3)\nDC4(a=\"\", b=3, c=0.2)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_kwonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_12.py","code":"\"\"\"\nTests the match_args feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY\nfrom typing import assert_type, Literal\n\n# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method\n\n@dataclass(match_args=True)\nclass DC1:\n x: int\n _: KW_ONLY\n y: str\n\nassert_type(DC1.__match_args__, tuple[Literal['x']])\n\n# The match_args default is True\n\n@dataclass\nclass DC2:\n x: int\n\nassert_type(DC2.__match_args__, tuple[Literal['x']])\n\n# __match_args__ is created even if __init__() is not generated\n\n@dataclass(match_args=True, init=False)\nclass DC3:\n x: int = 0\n\nassert_type(DC3.__match_args__, tuple[Literal['x']])\n\n# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.\n\n@dataclass(match_args=False)\nclass DC4:\n x: int\n\nDC4.__match_args__ # E\n\n@dataclass(match_args=True)\nclass DC5:\n __match_args__ = ()\n x: int\n\nassert_type(DC5.__match_args__, tuple[()])\n","source":"typing_tests","origin":"conformance/tests/dataclasses_match_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_13.py","code":"\"\"\"\nTests the synthesized comparison methods for dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass DC1:\n a: str\n b: int\n\n\n@dataclass(order=True)\nclass DC2:\n a: str\n b: int\n\n\ndc1_1 = DC1(\"\", 0)\ndc1_2 = DC1(\"\", 0)\n\nif dc1_1 < dc1_2:\n pass\n\nif dc1_1 <= dc1_2:\n pass\n\nif dc1_1 > dc1_2:\n pass\n\nif dc1_1 >= dc1_2:\n pass\n\nif dc1_1 == dc1_2:\n pass\n\nif dc1_1 != dc1_2:\n pass\n\nif dc1_1 == None:\n pass\n\nif dc1_1 != None:\n pass\n\ndc2_1 = DC2(\"hi\", 2)\n\n# This should generate an error because the types are\n# incompatible.\nif dc1_1 < dc2_1: # E:\n pass\n\nif dc1_1 != dc2_1:\n pass\n","source":"typing_tests","origin":"conformance/tests/dataclasses_order.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_14.py","code":"\"\"\"\nTests type checking of the __post_init__ method in a dataclass.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#post-init-processing\n\nfrom dataclasses import InitVar, dataclass, field, replace\nfrom typing import assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n b: int\n x: InitVar[int]\n c: int\n y: InitVar[str]\n\n def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y\n pass\n\n\ndc1 = DC1(1, 2, 3, 4, \"\")\n\nassert_type(dc1.a, int)\nassert_type(dc1.b, int)\nassert_type(dc1.c, int)\nprint(dc1.x) # E: cannot access InitVar\nprint(dc1.y) # E: cannot access InitVar\n\n@dataclass\nclass DC2:\n x: InitVar[int]\n y: InitVar[str]\n\n def __post_init__(self, x: int) -> None: # E: missing y\n pass\n\n\n@dataclass\nclass DC3:\n _name: InitVar[str] = field()\n name: str = field(init=False)\n\n def __post_init__(self, _name: str):\n ...\n\n\n@dataclass\nclass DC4(DC3):\n _age: InitVar[int] = field()\n age: int = field(init=False)\n\n def __post_init__(self, _name: str, _age: int):\n ...\n","source":"typing_tests","origin":"conformance/tests/dataclasses_postinit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_15.py","code":"\"\"\"\nTests the slots functionality of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass\n\n# This should generate an error because __slots__ is already defined.\n@dataclass(slots=True) # E[DC1]\nclass DC1: # E[DC1]\n x: int\n\n __slots__ = ()\n\n\n@dataclass(slots=True)\nclass DC2:\n x: int\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass(slots=False)\nclass DC3:\n x: int\n\n __slots__ = (\"x\",)\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass\nclass DC4:\n __slots__ = (\"y\", \"x\")\n x: int\n y: str\n\n\nDC4(1, \"bar\")\n\n\n@dataclass(slots=True)\nclass DC5:\n a: int\n\n\nDC5.__slots__\nDC5(1).__slots__\n\n\n@dataclass\nclass DC6:\n a: int\n\n\n# This should generate an error because __slots__ is not defined.\nDC6.__slots__ # E\n\n# This should generate an error because __slots__ is not defined.\nDC6(1).__slots__ # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_slots.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_16.py","code":"\"\"\"\nTests basic handling of the dataclass factory.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html\n# Also, see https://peps.python.org/pep-0557/\n\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar, assert_type\nimport sys\n\nT = TypeVar(\"T\")\n\n\n@dataclass(order=True)\nclass InventoryItem:\n x = 0\n name: str\n unit_price: float\n quantity_on_hand: int = 0\n\n def total_cost(self) -> float:\n return self.unit_price * self.quantity_on_hand\n\n\nv1 = InventoryItem(\"soap\", 2.3)\n\n\nclass InventoryItemInitProto(Protocol):\n def __call__(\n self, name: str, unit_price: float, quantity_on_hand: int = ...\n ) -> None: ...\n\n\n# Validate the type of the synthesized __init__ method.\nx1: InventoryItemInitProto = v1.__init__\n\n# Make sure the following additional methods were synthesized.\nprint(v1.__repr__)\nprint(v1.__eq__)\nprint(v1.__ne__)\nprint(v1.__lt__)\nprint(v1.__le__)\nprint(v1.__gt__)\nprint(v1.__ge__)\n\nassert_type(v1.name, str)\nassert_type(v1.unit_price, float)\nassert_type(v1.quantity_on_hand, int)\n\nv2 = InventoryItem(\"name\") # E: missing unit_price\nv3 = InventoryItem(\"name\", \"price\") # E: incorrect type for unit_price\nv4 = InventoryItem(\"name\", 3.1, 3, 4) # E: too many arguments\n\n\n# > TypeError will be raised if a field without a default value follows a\n# > field with a default value. This is true either when this occurs in a\n# > single class, or as a result of class inheritance.\n@dataclass # E[DC1]\nclass DC1:\n a: int = 0 # E[DC1]: field with default should follow a field with no default.\n b: int # E[DC1]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC2]\nclass DC2:\n a: int = field(default=1) # E[DC2]: field with default should follow a field with no default.\n b: int # E[DC2]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC3]\nclass DC3:\n a: InitVar[int] = 0 # E[DC3]: field with default should follow a field with no default.\n b: int # E[DC3]: field with no default cannot follow field with default.\n\n\n@dataclass\nclass DC4:\n a: int = field(init=False)\n b: int\n\n\nv5 = DC4(0)\nv6 = DC4(0, 1) # E: too many parameters\n\n\n@dataclass\nclass DC5:\n a: int = field(default_factory=str) # E: type mismatch\n\n\ndef f(s: str) -> int:\n return int(s)\n\n\n@dataclass\nclass DC6:\n a: ClassVar[int] = 0\n b: str\n c: Callable[[str], int] = f\n\n\ndc6 = DC6(\"\")\nassert_type(dc6.a, int)\nassert_type(DC6.a, int)\nassert_type(dc6.b, str)\nassert_type(dc6.c, Callable[[str], int])\n\n\n@dataclass\nclass DC7:\n x: int\n\n\n@dataclass(init=False)\nclass DC8(DC7):\n y: int\n\n def __init__(self, a: DC7, y: int):\n self.__dict__ = a.__dict__\n self.y = y\n\n\na = DC7(3)\nb = DC8(a, 5)\n\n# This should generate an error because there is an extra parameter\nDC7(3, 4) # E\n\n# This should generate an error because there is one too few parameters\nDC8(a) # E\n\n\n@dataclass\nclass DC9:\n a: str = field(init=False, default=\"s\")\n b: bool = field()\n\n\n@dataclass\nclass DC10(DC9):\n a: str = field()\n b: bool = field()\n\n\n@dataclass(init=False)\nclass DC11:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC11(3)\n\n\n@dataclass(init=True)\nclass DC12:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC12(3)\n\n\n@dataclass(init=False)\nclass DC13:\n x: int\n x_squared: int\n\n\n# This should generate an error because there is no matching\n# override __init__ method and no synthesized __init__.\nDC13(3) # E\n\n\n@dataclass\nclass DC14:\n prop_1: str = field(init=False)\n prop_2: str = field(default=\"hello\")\n prop_3: str = field(default_factory=lambda: \"hello\")\n\n\n@dataclass\nclass DC15(DC14):\n prop_2: str = \"\"\n\n\ndc15 = DC15(prop_2=\"test\")\n\nassert_type(dc15.prop_1, str)\nassert_type(dc15.prop_2, str)\nassert_type(dc15.prop_3, str)\n\n\nclass DataclassProto(Protocol):\n __dataclass_fields__: ClassVar[dict[str, Any]]\n\n\nv7: DataclassProto = dc15\n\n\n@dataclass\nclass DC16(Generic[T]):\n value: T\n\n\nassert_type(DC16(1), DC16[int])\n\n\nclass DC17(DC16[str]):\n pass\n\n\nassert_type(DC17(\"\"), DC17)\n\n\n@dataclass\nclass DC18:\n x: int = field()\n # This may generate a type checker error because an unannotated field\n # will result in a runtime exception.\n y = field() # E?\n\n\n# > Dataclass fields may be conditional, via checks of the same\n# > statically-known conditions that a type-checker understands elsewhere,\n# > such as Python version:\n\n@dataclass\nclass DC19:\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nDC19(1, 2)\nDC19(1, 2, 3) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_01.py","code":"\"\"\"\nTests the handling of ClassVar and Final in dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import assert_type, ClassVar, Final\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#dataclass-semantics\n\n# > A final class variable on a dataclass must be explicitly annotated as\n# e.g. x: ClassVar[Final[int]] = 3.\n\n\n@dataclass\nclass D:\n final_no_default: Final[int]\n final_with_default: Final[str] = \"foo\"\n final_classvar: ClassVar[Final[int]] = 4\n # we don't require support for Final[ClassVar[...]] because the dataclasses\n # runtime implementation won't recognize it as a ClassVar either\n\n\n# An explicitly marked ClassVar can be accessed on the class:\nassert_type(D.final_classvar, int)\n\n# ...but not assigned to, because it's Final:\nD.final_classvar = 10 # E: can't assign to final attribute\n\n# A non-ClassVar attribute (with or without default) is a dataclass field:\nd = D(final_no_default=1, final_with_default=\"bar\")\nassert_type(d.final_no_default, int)\nassert_type(d.final_with_default, str)\n\n# ... but can't be assigned to (on the class or on an instance):\nd.final_no_default = 10 # E: can't assign to final attribute\nd.final_with_default = \"baz\" # E: can't assign to final attribute\nD.final_no_default = 10 # E: can't assign to final attribute\nD.final_with_default = \"baz\" # E: can't assign to final attribute\n","source":"typing_tests","origin":"conformance/tests/dataclasses_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_02.py","code":"\"\"\"\nTests the typing.Final special form.\n\"\"\"\n\nfrom typing import ClassVar, Final, Literal, NamedTuple, TypedDict, assert_type\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#id1\n\nID1: Final[int] = 1\n\nID2: Final = 1\nassert_type(ID2, Literal[1])\n\n# > If the right hand side is omitted, there must be an explicit type argument to Final.\n\nBAD1: Final # E: missing assignment\n\nBAD2: Final[str, int] = \"\" # E: only one type argument allowed\n\n# > There can be at most one final declaration per module or class for a given\n# > attribute.\n\n# > As self.id: Final = 1 (also optionally with a type in square brackets).\n# > This is allowed only in __init__ methods, so that the final instance\n# > attribute is assigned only once when an instance is created.\n\n\nclass ClassA:\n ID1: Final = 1\n\n # > In class bodies and stub files you can omit the right hand side and just\n # > write ID: Final[float]. If the right hand side is omitted, there must be\n # > an explicit type argument to Final.\n ID2: Final # E: missing initialization\n\n # > A final attribute declared in a class body without an initializer must\n # > be initialized in the __init__ method (except in stub files):\n ID3: Final[int] # E: missing initialization\n\n ID4: Final[int] # OK because initialized in __init__\n\n ID5: Final[int] = 0\n\n ID6: Final[int]\n\n ID7: Final[int] = 0\n\n def __init__(self, cond: bool) -> None:\n self.id1: Final = 1\n self.id2: Final[int] = 1\n\n self.ID4 = 1\n\n self.ID5 = 0 # E: Already initialized\n\n if cond:\n self.ID6 = 1\n else:\n self.ID6 = 2\n\n def method1(self) -> None:\n self.id3: Final = 1 # E: not allowed outside of __init__ method.\n self.id4: Final[int] = 1 # E: not allowed outside of __init__ method.\n\n self.ID7 = 0 # E: cannot modify Final value\n\n self.ID7 += 1 # E: cannot modify Final value\n\n\nRATE: Final = 3000\nRATE = 300 # E: Cannot redefine Final value\n\n# > There can’t be separate class-level and instance-level constants\n# > with the same name.\n\n\nclass ClassB:\n DEFAULT_ID: Final = 0\n\n\nClassB.DEFAULT_ID = 0 # E: Cannot redefined value\n\n\n# > A type checker should prevent final attributes from being overridden in a subclass:\n\n\nclass ClassC:\n BORDER_WIDTH: Final = 2.5\n\n __private: Final = 0\n\n\nclass ClassCChild(ClassC):\n BORDER_WIDTH = 2.5 # E: Cannot override Final value\n\n __private = 0 # OK\n\n\n# > Type checkers should infer a final attribute that is initialized in a class\n# > body as being a class variable. Variables should not be annotated with both\n# > ClassVar and Final. (Except in a dataclass; see dataclasses_final.py.)\n\n\nclass ClassD:\n VALUE1: Final = 1\n\n VALUE2: ClassVar[Final] = 1 # E: Final cannot be used with ClassVar\n VALUE3: Final[ClassVar] = 1 # E: Final cannot be used with ClassVar\n\n\nClassD.VALUE1 # OK\n\n\n# > Final may only be used as the outermost type in assignments or variable\n# > annotations. Using it in any other position is an error. In particular,\n# > Final can’t be used in annotations for function arguments.\n\nx: list[Final[int]] = [] # E\n\n\ndef func1(x: Final[list[int]]) -> None: # E\n ...\n\n\n# > ``Final`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithFinal(TypedDict):\n a: int\n b: Final[int] # E: Final not allowed in a TypedDict\n\n\nclass NTWithFinal(NamedTuple):\n a: int\n b: Final[int] # E: Final not allowed in a NamedTuple\n\n\n# > Type checkers should treat uses of a final name that was initialized with\n# > a literal as if it was replaced by the literal. For example, the following\n# > should be allowed:\n\nX: Final = \"x\"\nY: Final = \"y\"\nN = NamedTuple(\"N\", [(X, int), (Y, int)])\n\nN(x=3, y=4) # OK\nN(a=1) # E\nN(x=\"\", y=\"\") # E\n\n\ndef func2() -> None:\n global ID1\n\n ID1 = 2 # E: cannot modify Final value\n\n x: Final = 3\n\n x += 1 # E: cannot modify Final value\n\n a = (x := 4) # E: cannot modify Final value\n\n for x in [1, 2, 3]: # E: cannot modify Final value\n pass\n\n with open(\"FileName\") as x: # E: cannot modify Final value\n pass\n\n (a, x) = (1, 2) # E: cannot modify Final value\n\n\n# > If a module declares a ``Final`` variable and another module imports that\n# > variable in an import statement by name or wildcard, the imported symbol\n# > inherits the ``Final`` type qualifier. Any attempt to assign a different value\n# > to this symbol should be flagged as an error by a type checker.\n\n\nfrom _qualifiers_final_annotation_1 import TEN\n\nTEN = 9 # E: Cannot redefine Final value\n\nfrom _qualifiers_final_annotation_2 import *\n\nPI = 3.14159 # E: Cannot redefine Final value\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_03.py","code":"\"\"\"\nTests the @final decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#final\n\nfrom typing import final, overload\nfrom _qualifiers_final_decorator import Base3, Base4\n\n# > A type checker should prohibit any class decorated with @final from being\n# > subclassed and any method decorated with @final from being overridden in a\n# > subclass. The method decorator version may be used with all of instance\n# > methods, class methods, static methods, and properties.\n\n\n@final\nclass Base1:\n ...\n\n\nclass Derived1(Base1): # E: Cannot inherit from final class \"Base\"\n ...\n\n\nclass Base2:\n @final\n def method1(self) -> None:\n pass\n\n @final\n @classmethod\n def method2(cls) -> None:\n pass\n\n @final\n @staticmethod\n def method3() -> None:\n pass\n\n # > For overloaded methods, @final should be placed on the implementation.\n\n @overload\n def method4(self, x: int) -> int:\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @final\n def method4(self, x: int | str) -> int | str:\n return 0\n\n\nclass Derived2(Base2):\n def method1(self) -> None: # E\n pass\n\n @classmethod # E[method2]\n def method2(cls) -> None: # E[method2]\n pass\n\n @staticmethod # E[method3]\n def method3() -> None: # E[method3]\n pass\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n def method4(self, x: int | str) -> int | str: # E[method4]\n return 0\n\n\nclass Derived3(Base3):\n @overload # E[Derived3]\n def method(self, x: int) -> int: # E[Derived3]\n ...\n\n @overload # E[Derived3-2]\n @final # E[Derived3-2]: should be applied only to implementation\n def method(self, x: str) -> str: # E[Derived3-2]\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived3]\n return 0\n\n\nclass Derived4(Base4):\n @overload # E[Derived4]\n def method(self, x: int) -> int: # E[Derived4]\n ...\n\n @overload\n def method(self, x: str) -> str:\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived4]\n return 0\n\n\nclass Base5_1:\n ...\n\n\nclass Base5_2:\n @final\n def method(self, v: int) -> None:\n ...\n\n\n# Test multiple inheritance case.\nclass Derived5(Base5_1, Base5_2):\n def method(self) -> None: # E\n ...\n\n\n# > It is an error to use @final on a non-method function.\n\n\n@final # E[func]: not allowed on non-method function.\ndef func1() -> int: # E[func]\n return 0\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_decorator.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_04.py","code":"\"\"\"\nTests the use of Final values when used with TypedDicts.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#use-of-final-values-and-literal-types\n\nfrom typing import Final, Literal, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\n# > Type checkers should allow final names (PEP 591) with string values to be\n# > used instead of string literals in operations on TypedDict objects.\nYEAR: Final = \"year\"\n\nm: Movie = {\"name\": \"Alien\", \"year\": 1979}\nyears_since_epoch = m[YEAR] - 1970\n\n\n# > An expression with a suitable literal type (PEP 586) can be used instead of\n# > a literal value.\ndef get_value(movie: Movie, key: Literal[\"year\", \"name\"]) -> int | str:\n return movie[key]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"literal-string","pep":"675","introduced_in":"3.11","form":"modern","file":"literal-string/modern_01.py","code":"\"\"\"\nTests handling of the LiteralString special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#literalstring\n\n\nfrom typing import (\n Any,\n Generic,\n Literal,\n LiteralString,\n Sequence,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nvariable_annotation: LiteralString\n\n\ndef my_function(literal_string: LiteralString) -> LiteralString:\n raise NotImplementedError\n\n\nclass Foo:\n my_attribute: LiteralString = \"\"\n\n\ntype_argument: list[LiteralString]\n\nT = TypeVar(\"T\", bound=LiteralString)\n\n\nbad_union: Literal[\"hello\", LiteralString] # E\nbad_nesting: Literal[LiteralString] # E\n\n\ndef func1(a: Literal[\"one\"], b: Literal[\"two\"]):\n x1: LiteralString = a\n\n x2: Literal[\"\"] = b # E\n\n\ndef func2(a: LiteralString, b: LiteralString, non_literal: str):\n # > Addition: x + y is of type LiteralString if both x and y are compatible with LiteralString.\n assert_type(a + b, LiteralString)\n\n # > Joining: sep.join(xs) is of type LiteralString if sep’s type is\n # > compatible with LiteralString and xs’s type is compatible with Iterable[LiteralString].\n assert_type(\",\".join((a, b)), LiteralString)\n assert_type(\",\".join((a, non_literal)), str)\n\n # > In-place addition: If s has type LiteralString and x has type compatible with\n # > LiteralString, then s += x preserves s’s type as LiteralString.\n a += \"hello\"\n b += a\n\n # > String formatting: An f-string has type LiteralString if and only if its constituent\n # > expressions are literal strings. s.format(...) has type LiteralString if and only if\n # > s and the arguments have types compatible with LiteralString.\n assert_type(f\"{a} {b}\", LiteralString)\n\n x1: LiteralString = f\"{a} {non_literal}\" # E\n\n assert_type(a + non_literal, str)\n\n # > LiteralString is compatible with the type str\n x2: str = a\n\n # > Other literal types, such as literal integers, are not compatible with LiteralString.\n x3: LiteralString = 3 # E\n x4: LiteralString = b\"test\" # E\n\n\n# > Conditional statements and expressions work as expected.\ndef condition1() -> bool:\n raise NotImplementedError\n\n\ndef return_literal_string() -> LiteralString:\n return \"foo\" if condition1() else \"bar\" # OK\n\n\ndef return_literal_str2(literal_string: LiteralString) -> LiteralString:\n return \"foo\" if condition1() else literal_string # OK\n\n\ndef return_literal_str3() -> LiteralString:\n result: LiteralString\n if condition1():\n result = \"foo\"\n else:\n result = \"bar\"\n\n return result # OK\n\n\n# > TypeVars can be bound to LiteralString.\nTLiteral = TypeVar(\"TLiteral\", bound=LiteralString)\n\n\ndef literal_identity(s: TLiteral) -> TLiteral:\n return s\n\n\ndef func3(s: Literal[\"hello\"]):\n y = literal_identity(s)\n assert_type(y, Literal[\"hello\"])\n\n\ndef func4(s: LiteralString):\n y2 = literal_identity(s)\n assert_type(y2, LiteralString)\n\n\ndef func5(s: str):\n literal_identity(s) # E\n\n\n# > LiteralString can be used as a type argument for generic classes.\nclass Container(Generic[T]):\n def __init__(self, value: T) -> None:\n self.value = value\n\n\ndef func6(s: LiteralString):\n x: Container[LiteralString] = Container(s) # OK\n\n\ndef func7(s: str):\n x_error: Container[LiteralString] = Container(s) # E\n\n\n# > Standard containers like List work as expected.\nxs: list[LiteralString] = [\"foo\", \"bar\", \"baz\"]\n\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\n\n@overload\ndef func8(x: Literal[\"foo\"]) -> C:\n ...\n\n\n@overload\ndef func8(x: LiteralString) -> B:\n ...\n\n\n@overload\ndef func8(x: str) -> A:\n ...\n\n\ndef func8(x: Any) -> Any:\n raise NotImplementedError\n\n\ndef call_func8(x: str) -> None:\n assert_type(func8(\"foo\"), C) # First overload\n assert_type(func8(\"bar\"), B) # Second overload\n assert_type(func8(x), A) # Third overload\n\n\ndef func9(val: list[LiteralString]):\n x1: list[str] = val # E\n\n\ndef func10(val: Sequence[LiteralString]):\n x1: Sequence[str] = val # OK\n","source":"typing_tests","origin":"conformance/tests/literals_literalstring.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_04.py","code":"\"\"\"\nTests interactions between Literal types and other typing features.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#interactions-with-other-types-and-features\nfrom enum import Enum\nfrom typing import IO, Any, Final, Generic, Literal, TypeVar, LiteralString, assert_type, overload\n\n\ndef func1(v: tuple[int, str, list[bool]], a: Literal[0], b: Literal[5], c: Literal[-5]):\n assert_type(v[a], int)\n assert_type(v[2], list[bool])\n\n v[b] # E: index out of range\n v[c] # E: index out of range\n v[4] # E: index out of range\n v[-4] # E: index out of range\n\n\n_PathType = str | bytes | int\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"r\", \"w\", \"a\", \"x\", \"r+\", \"w+\", \"a+\", \"x+\"],\n) -> IO[str]:\n ...\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"rb\", \"wb\", \"ab\", \"xb\", \"r+b\", \"w+b\", \"a+b\", \"x+b\"],\n) -> IO[bytes]:\n ...\n\n\n@overload\ndef open(path: _PathType, mode: str) -> IO[Any]:\n ...\n\n\ndef open(path: _PathType, mode: Any) -> Any:\n raise NotImplementedError\n\n\nassert_type(open(\"path\", \"r\"), IO[str])\nassert_type(open(\"path\", \"wb\"), IO[bytes])\nassert_type(open(\"path\", \"other\"), IO[Any])\n\n\nA = TypeVar(\"A\", bound=int)\nB = TypeVar(\"B\", bound=int)\nC = TypeVar(\"C\", bound=int)\n\n\nclass Matrix(Generic[A, B]):\n def __add__(self, other: \"Matrix[A, B]\") -> \"Matrix[A, B]\":\n raise NotImplementedError\n\n def __matmul__(self, other: \"Matrix[B, C]\") -> \"Matrix[A, C]\":\n raise NotImplementedError\n\n def transpose(self) -> \"Matrix[B, A]\":\n raise NotImplementedError\n\n\ndef func2(a: Matrix[Literal[2], Literal[3]], b: Matrix[Literal[3], Literal[7]]):\n c = a @ b\n assert_type(c, Matrix[Literal[2], Literal[7]])\n\n\nT = TypeVar(\"T\", Literal[\"a\"], Literal[\"b\"], Literal[\"c\"])\nS = TypeVar(\"S\", bound=Literal[\"foo\"])\n\n\nclass Status(Enum):\n SUCCESS = 0\n INVALID_DATA = 1\n FATAL_ERROR = 2\n\n\ndef parse_status1(s: str | Status) -> None:\n if s is Status.SUCCESS:\n assert_type(s, Literal[Status.SUCCESS])\n elif s is Status.INVALID_DATA:\n assert_type(s, Literal[Status.INVALID_DATA])\n elif s is Status.FATAL_ERROR:\n assert_type(s, Literal[Status.FATAL_ERROR])\n else:\n assert_type(s, str)\n\n\n# > Type checkers may optionally perform additional analysis for both\n# > enum and non-enum Literal types beyond what is described in the section above.\n#\n# > For example, it may be useful to perform narrowing based on things\n# > like containment or equality checks:\n\ndef expects_bad_status(status: Literal[\"MALFORMED\", \"ABORTED\"]):\n ...\n\n\ndef expects_pending_status(status: Literal[\"PENDING\"]):\n ...\n\n\ndef parse_status2(status: LiteralString) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n\n# Narrowing `str` to `Literal` strings is unsound given the possiblity of\n# user-defined `str` subclasses that could have custom equality semantics,\n# but is explicitly listed by the spec as optional analysis that type checkers\n# may perform.\ndef parse_status3(status: str) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n\nfinal_val1: Final = 3\nassert_type(final_val1, Literal[3])\n\nfinal_val2: Final = True\nassert_type(final_val2, Literal[True])\n","source":"typing_tests","origin":"conformance/tests/literals_interactions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_05.py","code":"\"\"\"\nTests legal and illegal parameterizations of Literal.\n\"\"\"\n\n# > Literal must be parameterized with at least one type.\n\nfrom typing import Any, Literal, TypeVar\nfrom enum import Enum\n\n\nclass Color(Enum):\n RED = 0\n GREEN = 1\n BLUE = 2\n\n\ngood1: Literal[26]\ngood2: Literal[0x1A]\ngood3: Literal[-4]\ngood4: Literal[+5]\ngood5: Literal[\"hello world\"]\ngood6: Literal[b\"hello world\"]\ngood7: Literal[\"hello world\"]\ngood8: Literal[True]\ngood9: Literal[Color.RED]\ngood10: Literal[None]\n\nReadOnlyMode = Literal[\"r\", \"r+\"]\nWriteAndTruncateMode = Literal[\"w\", \"w+\", \"wt\", \"w+t\"]\nWriteNoTruncateMode = Literal[\"r+\", \"r+t\"]\nAppendMode = Literal[\"a\", \"a+\", \"at\", \"a+t\"]\n\nAllModes = Literal[ReadOnlyMode, WriteAndTruncateMode, WriteNoTruncateMode, AppendMode]\n\ngood11: Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n\nvariable = 3\nT = TypeVar(\"T\")\n\n# > Arbitrary expressions [are illegal]\nbad1: Literal[3 + 4] # E\nbad2: Literal[\"foo\".replace(\"o\", \"b\")] # E\nbad3: Literal[4 + 3j] # E\nbad4: Literal[~5] # E\nbad5: Literal[not False] # E\nbad6: Literal[(1, \"foo\", \"bar\")] # E\nbad7: Literal[{\"a\": \"b\", \"c\": \"d\"}] # E\nbad8: Literal[int] # E\nbad9: Literal[variable] # E\nbad10: Literal[T] # E\nbad11: Literal[3.14] # E\nbad12: Literal[Any] # E\nbad13: Literal[...] # E\n\n\ndef my_function(x: Literal[1 + 2]) -> int: # E\n return x * 3\n\n\nx: Literal # E\ny: Literal[my_function] = my_function # E\n\n\ndef func2(a: Literal[Color.RED]):\n x1: Literal[\"Color.RED\"] = a # E\n\n x2: \"Literal[Color.RED]\" = a # OK\n","source":"typing_tests","origin":"conformance/tests/literals_parameterizations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_06.py","code":"\"\"\"\nTests the semantics of the Literal special form.\n\"\"\"\n\nfrom typing import Literal\nfrom typing import Literal as L\n\n\nv1: Literal[3] = 3\nv2: Literal[3] = 4 # E\n\nv3: L[-3] = -3\n\n\n# > Literal[20] and Literal[0x14] are equivalent\ndef func1(a: Literal[20], b: Literal[0x14], c: Literal[0b10100]):\n x1: Literal[0x14] = a\n x2: Literal[0x14] = b\n x3: Literal[0x14] = c\n\n\n# > Literal[0] and Literal[False] are not equivalent\ndef func2(a: Literal[0], b: Literal[False]):\n x1: Literal[False] = a # E\n x2: Literal[0] = b # E\n\n\n# > Given some value v that is a member of type T, the type Literal[v] shall\n# > be treated as a subtype of T. For example, Literal[3] is a subtype of int.\ndef func3(a: L[3, 4, 5]):\n b = a.__add__(3)\n c = a + 3\n a += 3 # E\n\n\n# > When a Literal is parameterized with more than one value, it’s treated\n# > as exactly equivalent to the union of those types.\ndef func4(a: L[None, 3] | L[3, \"foo\", b\"bar\", True]):\n x1: Literal[3, b\"bar\", True, \"foo\", None] = a\n a = x1\n","source":"typing_tests","origin":"conformance/tests/literals_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_01.py","code":"\"\"\"\nTests basic usage of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#paramspec-variables\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeAlias\n\nP = ParamSpec(\"P\") # OK\nWrongName = ParamSpec(\"NotIt\") # E: name inconsistency\n\n\n# > Valid use locations\n\nTA1: TypeAlias = P # E\n\nTA2: TypeAlias = Callable[P, None] # OK\nTA3: TypeAlias = Callable[Concatenate[int, P], None] # OK\nTA4: TypeAlias = Callable[..., None] # OK\nTA5: TypeAlias = Callable[..., None] # OK\n\n\ndef func1(x: P) -> P: # E\n raise NotImplementedError\n\n\ndef func2(x: Concatenate[int, P]) -> int: # E\n raise NotImplementedError\n\n\ndef func3(x: list[P]) -> None: # E\n ...\n\n\ndef func4(x: Callable[[int, str], P]) -> None: # E\n ...\n\n\ndef func5(*args: P, **kwargs: P) -> None: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_02.py","code":"\"\"\"\nTests the usage of a ParamSpec and its components (P.args, P.kwargs).\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#the-components-of-a-paramspec\n\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef puts_p_into_scope1(f: Callable[P, int]) -> None:\n def inner(*args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def mixed_up(*args: P.kwargs, **kwargs: P.args) -> None: # E\n pass\n\n def misplaced1(x: P.args) -> None: # E\n pass\n\n def bad_kwargs1(*args: P.args, **kwargs: P.args) -> None: # E\n pass\n\n def bad_kwargs2(*args: P.args, **kwargs: Any) -> None: # E\n pass\n\n\ndef out_of_scope(*args: P.args, **kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef puts_p_into_scope2(f: Callable[P, int]) -> None:\n stored_args: P.args # E\n stored_kwargs: P.kwargs # E\n\n def just_args(*args: P.args) -> None: # E\n pass\n\n def just_kwargs(**kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef decorator(f: Callable[P, int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n assert_type(f(*args, **kwargs), int) # OK\n\n f(*kwargs, **args) # E\n\n f(1, *args, **kwargs) # E\n\n return foo # OK\n\n\ndef add(f: Callable[P, int]) -> Callable[Concatenate[str, P], None]:\n def foo(s: str, *args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def bar(*args: P.args, s: str, **kwargs: P.kwargs) -> None: # E\n pass\n\n return foo # OK\n\n\ndef remove(f: Callable[Concatenate[int, P], int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n f(1, *args, **kwargs) # OK\n\n f(*args, 1, **kwargs) # E\n\n f(*args, **kwargs) # E\n\n return foo # OK\n\n\ndef outer(f: Callable[P, None]) -> Callable[P, None]:\n def foo(x: int, *args: P.args, **kwargs: P.kwargs) -> None:\n f(*args, **kwargs)\n\n def bar(*args: P.args, **kwargs: P.kwargs) -> None:\n foo(1, *args, **kwargs) # OK\n foo(x=1, *args, **kwargs) # E\n\n return bar\n\n\ndef twice(f: Callable[P, int], *args: P.args, **kwargs: P.kwargs) -> int:\n return f(*args, **kwargs) + f(*args, **kwargs)\n\n\ndef a_int_b_str(a: int, b: str) -> int:\n return 0\n\n\ntwice(a_int_b_str, 1, \"A\") # OK\ntwice(a_int_b_str, b=\"A\", a=1) # OK\ntwice(a_int_b_str, \"A\", 1) # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_components.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_03.py","code":"\"\"\"\nTests semantics of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#semantics\n\n\nfrom typing import Callable, Concatenate, Generic, ParamSpec, TypeVar, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef changes_return_type_to_str(x: Callable[P, int]) -> Callable[P, str]:\n raise NotImplementedError\n\n\ndef returns_int(a: str, b: bool, /) -> int:\n raise NotImplementedError\n\n\nf1 = changes_return_type_to_str(returns_int)\nassert_type(f1, Callable[[str, bool], str])\n\nv1 = f1(\"A\", True) # OK\nassert_type(v1, str)\nf1(a=\"A\", b=True) # E: positional-only\nf1(\"A\", \"A\") # E: wrong type\n\n\ndef func1(x: Callable[P, int], y: Callable[P, int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\ndef x_y(x: int, y: str) -> int:\n raise NotImplementedError\n\n\ndef y_x(y: int, x: str) -> int:\n raise NotImplementedError\n\n\nf2 = func1(x_y, x_y)\nassert_type(f2(1, \"\"), bool)\nassert_type(f2(y=\"\", x=1), bool)\n\nf3 = func1(x_y, y_x) # E?: Could return (a: int, b: str, /) -> bool\n# (a callable with two positional-only parameters)\n# This works because both callables have types that are\n# behavioral subtypes of Callable[[int, str], int]\n# Also OK for type checkers to reject this.\n\n\ndef keyword_only_x(*, x: int) -> int:\n raise NotImplementedError\n\n\ndef keyword_only_y(*, y: int) -> int:\n raise NotImplementedError\n\n\nfunc1(keyword_only_x, keyword_only_y) # E\n\n\nU = TypeVar(\"U\")\n\n\nclass Y(Generic[U, P]):\n f: Callable[P, str]\n prop: U\n\n def __init__(self, f: Callable[P, str], prop: U) -> None:\n self.f = f\n self.prop = prop\n\n\ndef callback_a(q: int, /) -> str:\n raise NotImplementedError\n\n\ndef func(x: int) -> None:\n y1 = Y(callback_a, x)\n assert_type(y1, Y[int, [int]])\n y2 = y1.f\n assert_type(y2, Callable[[int], str])\n\n\ndef bar(x: int, *args: bool) -> int:\n raise NotImplementedError\n\n\ndef add(x: Callable[P, int]) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\na1 = add(bar) # Should return (a: str, /, x: int, *args: bool) -> bool\nassert_type(a1(\"\", 1, False, True), bool)\nassert_type(a1(\"\", x=1), bool)\na1(1, x=1) # E\n\n\ndef remove(x: Callable[Concatenate[int, P], int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\nr1 = remove(bar) # Should return (*args: bool) -> bool\nassert_type(r1(False, True, True), bool)\nassert_type(r1(), bool)\nr1(1) # E\n\n\ndef transform(\n x: Callable[Concatenate[int, P], int]\n) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\nt1 = transform(bar) # Should return (a: str, /, *args: bool) -> bool\nassert_type(t1(\"\", True, False, True), bool)\nassert_type(t1(\"\"), bool)\nt1(1) # E\n\n\ndef expects_int_first(x: Callable[Concatenate[int, P], int]) -> None:\n ...\n\n\n@expects_int_first # E\ndef one(x: str) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef two(*, x: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef three(**kwargs: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # OK\ndef four(*args: int) -> int:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_04.py","code":"\"\"\"\nTests the handling of a ParamSpec specialization.\n\"\"\"\n\nfrom typing import Any, Callable, Concatenate, Generic, ParamSpec, TypeVar, cast\n\n\nT = TypeVar(\"T\")\nP1 = ParamSpec(\"P1\")\nP2 = ParamSpec(\"P2\")\n\n\nclass ClassA(Generic[T, P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\nclass ClassB(ClassA[T, P1], Generic[T, P1, P2]):\n f1: Callable[P1, int] = cast(Any, \"\")\n f2: Callable[P2, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\ndef func20(x: ClassA[int, P2]) -> str: # OK\n return \"\"\n\n\ndef func21(x: ClassA[int, Concatenate[int, P2]]) -> str: # OK\n return \"\"\n\n\ndef func22(x: ClassB[int, [int, bool], ...]) -> str: # OK\n return \"\"\n\n\ndef func23(x: ClassA[int, ...]) -> str: # OK\n return \"\"\n\n\ndef func24(x: ClassB[int, [], []]) -> str: # OK\n return \"\"\n\n\ndef func25(x: ClassA[int, int]) -> str: # E\n return \"\"\n\n\nclass ClassC(Generic[P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n\n\ndef func30(x: ClassC[[int, str, bool]]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n\n\ndef func31(x: ClassC[int, str, bool]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_01.py","code":"\"\"\"\nTests the handling of class objects as implementations of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#type-and-class-objects-vs-protocols\n\n# > Variables and parameters annotated with Type[Proto] accept only concrete\n# (non-protocol) subtypes of Proto.\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Protocol\n\n\nclass Proto(Protocol):\n @abstractmethod\n def meth(self) -> int:\n ...\n\n\nclass Concrete:\n def meth(self) -> int:\n return 42\n\n\ndef fun(cls: type[Proto]) -> int:\n return cls().meth() # OK\n\n\nfun(Proto) # E\nfun(Concrete) # OK\n\n\nvar: type[Proto]\nvar = Proto # E\nvar = Concrete # OK\nvar().meth() # OK\n\n\n# > A class object is considered an implementation of a protocol if accessing\n# > all members on it results in types compatible with the protocol members.\n\n\nclass ProtoA1(Protocol):\n def method1(self, x: int) -> int:\n ...\n\n\nclass ProtoA2(Protocol):\n def method1(_self, self: Any, x: int) -> int:\n ...\n\n\nclass ConcreteA:\n def method1(self, x: int) -> int:\n return 0\n\n\npa1: ProtoA1 = ConcreteA # E: signatures don't match\npa2: ProtoA2 = ConcreteA # OK\n\n\nclass ProtoB1(Protocol):\n @property\n def prop1(self) -> int:\n ...\n\n\nclass ConcreteB:\n @property\n def prop1(self) -> int:\n return 0\n\n\npb1: ProtoB1 = ConcreteB # E\n\n\nclass ProtoC1(Protocol):\n attr1: ClassVar[int]\n\n\nclass ProtoC2(Protocol):\n attr1: int\n\n\nclass ConcreteC1:\n attr1: ClassVar[int] = 1\n\n\nclass ConcreteC2:\n attr1: int = 1\n\n\nclass CMeta(type):\n attr1: int\n\n def __init__(self, *args, **kwargs) -> None:\n self.attr1: int = 1\n\n\nclass ConcreteC3(metaclass=CMeta):\n pass\n\n\npc1: ProtoC1 = ConcreteC1 # E\npc2: ProtoC2 = ConcreteC1 # OK\npc3: ProtoC1 = ConcreteC2 # E\npc4: ProtoC2 = ConcreteC2 # E\npc5: ProtoC1 = ConcreteC3 # E?: Explicit ClassVar matching is unspecified\npc6: ProtoC2 = ConcreteC3 # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_class_objects.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_02.py","code":"\"\"\"\nTests the basic definition rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#defining-a-protocol\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Iterable, NamedTuple, Protocol, Sequence\nfrom dataclasses import dataclass\n\n\nclass SupportsClose(Protocol):\n def close(self) -> None:\n ...\n\n\nclass Resource:\n def close(self) -> None:\n pass\n\n\ndef close_all(things: Iterable[SupportsClose]) -> None:\n for t in things:\n t.close()\n\n\nf = open(\"foo.txt\")\nr = Resource()\nclose_all([f, r]) # OK\nclose_all([1]) # E: 'int' has no 'close' method\n\n\nclass Example(Protocol):\n def first(self) -> int: # This is a protocol member\n return 42\n\n @abstractmethod\n def second(self) -> int: # Method without a default implementation\n raise NotImplementedError\n\n # > Static methods, class methods, and properties are equally allowed in protocols.\n\n @staticmethod\n def third() -> int:\n ...\n\n @classmethod\n def fourth(cls) -> int:\n ...\n\n @property\n def fifth(self) -> int:\n ...\n\n\n# > To define a protocol variable, one can use PEP 526 variable annotations\n# > in the class body. Additional attributes only defined in the body of a\n# > method by assignment via self are not allowed.\n\n\nclass Template(Protocol):\n name: str # This is a protocol member\n value: int = 0 # This one too (with default)\n\n def method(self) -> None:\n self.name = \"name\" # OK\n self.temp: list[int] = [] # E: use of self variables not allowed\n\n\nclass Concrete:\n def __init__(self, name: str, value: int) -> None:\n self.name = name\n self.value = value\n\n def method(self) -> None:\n return\n\n\nvar: Template = Concrete(\"value\", 42) # OK\n\n\n# > To distinguish between protocol class variables and protocol instance\n# > variables, the special ClassVar annotation should be used as specified\n# > by PEP 526. By default, protocol variables as defined above are considered\n# > readable and writable. To define a read-only protocol variable, one can\n# > use an (abstract) property.\n\n\nclass Template2(Protocol):\n val1: ClassVar[Sequence[int]]\n\n\nclass Concrete2_Good1:\n val1: ClassVar[Sequence[int]] = [2]\n\n\nclass Concrete2_Bad1:\n ...\n\n\nclass Concrete2_Bad2:\n val1: Sequence[float] = [2]\n\n\nclass Concrete2_Bad3:\n val1: list[int] = [2]\n\n\nclass Concrete2_Bad4:\n val1: Sequence[int] = [2]\n\n\nv2_good1: Template2 = Concrete2_Good1() # OK\nv2_bad1: Template2 = Concrete2_Bad1() # E\nv2_bad2: Template2 = Concrete2_Bad2() # E\nv2_bad3: Template2 = Concrete2_Bad3() # E\nv2_bad4: Template2 = Concrete2_Bad4() # E?: Explicit ClassVar matching is unspecified\n\n\nclass Template3(Protocol):\n val1: Sequence[int]\n\n\nclass Concrete3_Good1:\n val1: Sequence[int] = [0]\n\n\nclass Concrete3_Good2:\n def __init__(self) -> None:\n self.val1: Sequence[int] = [0]\n\n\nclass Concrete3_Bad1:\n ...\n\n\nclass Concrete3_Bad2:\n val1: ClassVar[Sequence[int]] = [0]\n\n\nclass Concrete3_Bad3:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete3_Bad4:\n val1: Sequence[float] = [0]\n\n\nclass Concrete3_Bad5:\n val1: list[int] = [0]\n\n\nv3_good1: Template3 = Concrete3_Good1() # OK\nv3_bad1: Template3 = Concrete3_Bad1() # E\nv3_bad2: Template3 = Concrete3_Bad2() # E\nv3_bad3: Template3 = Concrete3_Bad3() # E\nv3_bad4: Template3 = Concrete3_Bad4() # E\nv3_bad5: Template3 = Concrete3_Bad5() # E\n\n\nclass Template4(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n\nclass Concrete4_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete4_Good2:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete4_Good3:\n val1: Sequence[float] = [0]\n\n\nclass Concrete4_Good4:\n val1: Sequence[int] = [0]\n\n\nclass Concrete4_Good5:\n val1: list[float] = [0]\n\n\nclass Concrete4_Good6(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete4_Good7:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete4_Bad1:\n def val1(self) -> Sequence[int]: # Not a property\n return [0]\n\n\nclass Concrete4_Bad2:\n ...\n\n\nv4_good1: Template4 = Concrete4_Good1() # OK\nv4_good2: Template4 = Concrete4_Good2() # OK\nv4_good3: Template4 = Concrete4_Good3() # OK\nv4_good4: Template4 = Concrete4_Good4() # OK\nv4_good5: Template4 = Concrete4_Good5() # OK\nv4_good6: Template4 = Concrete4_Good6() # OK\nv4_good7: Template4 = Concrete4_Good7() # OK\nv4_bad1: Template4 = Concrete4_Bad1() # E\nv4_bad2: Template4 = Concrete4_Bad2() # E\n\n\nclass Template5(Protocol):\n def method1(self, a: int, b: int) -> float:\n ...\n\n\nclass Concrete5_Good1:\n def method1(self, a: float, b: float) -> int:\n return 0\n\n\nclass Concrete5_Good2:\n def method1(self, *args: float, **kwargs: float) -> Any:\n return 0.0\n\n\nclass Concrete5_Good3:\n def method1(self, a, b) -> Any:\n return 0.0\n\n\nclass Concrete5_Good4:\n @classmethod\n def method1(cls, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Good5:\n @staticmethod\n def method1(a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad1:\n def method1(self, a, c) -> int:\n return 0\n\n\nclass Concrete5_Bad2:\n def method1(self, a: int, c: int) -> int:\n return 0\n\n\nclass Concrete5_Bad3:\n def method1(self, *, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad4:\n def method1(self, a: int, b: int, /) -> float:\n return 0\n\n\nclass Concrete5_Bad5:\n @staticmethod\n def method1(self, a: int, b: int) -> float:\n return 0\n\n\nv5_good1: Template5 = Concrete5_Good1() # OK\nv5_good2: Template5 = Concrete5_Good2() # OK\nv5_good3: Template5 = Concrete5_Good3() # OK\nv5_good4: Template5 = Concrete5_Good4() # OK\nv5_good5: Template5 = Concrete5_Good5() # OK\nv5_bad1: Template5 = Concrete5_Bad1() # E\nv5_bad2: Template5 = Concrete5_Bad2() # E\nv5_bad3: Template5 = Concrete5_Bad3() # E\nv5_bad4: Template5 = Concrete5_Bad4() # E\nv5_bad5: Template5 = Concrete5_Bad5() # E\n\n\nclass Template6(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n ...\n\n\nclass Concrete6_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n pass\n\n\nclass Concrete6_Good2:\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete6_Good3:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete6_Bad1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete6_Bad2(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=True)\nclass Concrete6_Bad3:\n val1: Sequence[float] = (0,)\n\n\nv6_good1: Template6 = Concrete6_Good1() # OK\nv6_good2: Template6 = Concrete6_Good2() # OK\nv6_good3: Template6 = Concrete6_Good3() # OK\nv6_bad1: Template6 = Concrete6_Bad1() # E\nv6_bad2: Template6 = Concrete6_Bad2() # E: named tuple is immutable\nv6_bad3: Template6 = Concrete6_Bad3() # E: dataclass is frozen\n\n\n# The specification leaves two possible interpretations of a ClassVar protocol\n# member. One interpretation requires the implementing attribute to be explicitly\n# declared with ClassVar. The other interpretation imposes only structural\n# requirements: the attribute must be readable and writable on the class object\n# and readable on instances of the class. Both interpretations therefore require\n# the following assignments to be rejected.\n\n\nclass Template7(Protocol):\n val1: ClassVar[int]\n\n\nclass Concrete7_Bad1:\n def __init__(self) -> None:\n self.val1: int = 42\n\n\nclass Concrete7Meta(type):\n val1: int = 42\n\n\nclass Concrete7_Bad2(metaclass=Concrete7Meta):\n pass\n\n\nv7_bad1: Template7 = Concrete7_Bad1() # E: val1 is not readable on the class object\nv7_bad2: Template7 = Concrete7_Bad2() # E: val1 is not readable on instances\n","source":"typing_tests","origin":"conformance/tests/protocols_definition.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_03.py","code":"\"\"\"\nTests the handling of explicit protocol classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#explicitly-declaring-implementation\n\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar, Protocol\n\n\nclass PColor(Protocol):\n @abstractmethod\n def draw(self) -> str:\n ...\n\n def complex_method(self) -> int:\n return 1\n\n\nclass NiceColor(PColor):\n def draw(self) -> str:\n return \"deep blue\"\n\n\nclass BadColor(PColor):\n def draw(self) -> str:\n return super().draw() # E: no default implementation\n\n\nclass ImplicitColor: # Note no 'PColor' base here\n def draw(self) -> str:\n return \"probably gray\"\n\n def complex_method(self) -> int:\n return 0\n\n\nv1: PColor = NiceColor() # OK\nv2: PColor = ImplicitColor() # OK\n\n\nclass RGB(Protocol):\n rgb: tuple[int, int, int]\n other: int\n\n @abstractmethod\n def intensity(self) -> int:\n return 1\n\n def transparency(self) -> int:\n ...\n\n\nclass Point(RGB):\n def __init__(self, red: int, green: int, blue: str) -> None:\n self.rgb = red, green, blue # E: 'blue' must be 'int'\n self.other = 0\n\n\np = Point(0, 0, \"\") # E: Cannot instantiate abstract class\n\n\nclass Proto1(Protocol):\n cm1: ClassVar[int]\n cm2: ClassVar[int] = 0\n\n im1: int\n im2: int = 2\n im3: int\n\n def __init__(self):\n self.im3 = 3\n\n\nclass Proto2(Protocol):\n cm10: int\n\n\nclass Proto3(Proto2, Protocol):\n cm11: int\n\n\nclass Concrete1(Proto1):\n def __init__(self):\n self.im1 = 1\n self.im3 = 3\n\n\nc1 = Concrete1() # E: cannot instantiate abstract class\n\n\nclass Concrete2(Proto1):\n cm1 = 3\n im1 = 0\n\n\nc2 = Concrete2()\n\n\nclass Concrete3(Proto1, Proto3):\n cm1 = 3\n\n def __init__(self):\n self.im1 = 0\n self.cm10 = 10\n self.cm11 = 11\n\n\nc3 = Concrete3()\n\n\nclass Concrete4(Proto1, Proto3):\n cm1 = 3\n cm10 = 3\n\n def __init__(self):\n self.im1 = 3\n self.im10 = 10\n self.cm11 = 3\n\n\nc4 = Concrete4()\n\n\nclass Proto5(Protocol):\n def method1(self) -> int:\n ...\n\n\nclass Concrete5(Proto5):\n pass\n\n\nc5 = Concrete5() # E: cannot instantiate abstract class\n\n\nclass Proto6(Protocol):\n x: int\n\n\nclass Mixin:\n x = 3\n\n\nclass Concrete6(Mixin, Proto6):\n pass\n\n\nclass Proto7(Protocol):\n @abstractmethod\n def method1(self):\n ...\n\n\nclass Mixin7(Proto7, ABC):\n def method1(self) -> None:\n pass\n\n\nclass Concrete7A(Proto7):\n pass\n\n\nc7a = Concrete7A() # E: cannot instantiate abstract class\n\n\nclass Concrete7B(Mixin7, Proto7):\n pass\n\n\nc7b = Concrete7B()\n","source":"typing_tests","origin":"conformance/tests/protocols_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_04.py","code":"\"\"\"\nTests the handling of generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\n\nfrom typing import Callable, Generic, Iterator, Protocol, Self, TypeVar, assert_type\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Iterable(Protocol[T_co]):\n def __iter__(self) -> Iterator[T_co]:\n ...\n\n\n# > Protocol[T, S, ...] is allowed as a shorthand for Protocol, Generic[T, S, ...].\n# In particular, the implicit order of type parameters is dictated by\n# the order in which they appear in the `Protocol` subscript.\n\n\nclass Proto1(Iterable[T_co], Protocol[S, T_co]):\n def method1(self, x: S) -> S:\n ...\n\n\nclass Concrete1:\n def __iter__(self) -> Iterator[int]:\n return (x for x in [1, 2, 3])\n\n def method1(self, x: str) -> str:\n return \"\"\n\n\np1: Proto1[str, int] = Concrete1() # OK\np2: Proto1[int, str] = Concrete1() # E: incompatible type\n\n\n# > It is an error to combine the shorthand with Generic[T, S, ...]\nclass Proto2(Protocol[T_co], Generic[T_co]): # E\n ...\n\n\n# > User-defined generic protocols support explicitly declared variance.\nclass Box(Protocol[T_co]):\n def content(self) -> T_co:\n ...\n\n\ndef func1(box_int: Box[int], box_float: Box[float]):\n v1: Box[float] = box_int # OK\n v2: Box[int] = box_float # E\n\n\nclass Sender(Protocol[T_contra]):\n def send(self, data: T_contra) -> int:\n return 0\n\n\ndef func2(sender_int: Sender[int], sender_float: Sender[float]):\n v1: Sender[int] = sender_float # OK\n v2: Sender[float] = sender_int # E\n\n\nclass AttrProto(Protocol[T]):\n attr: T\n\n\ndef func3(attr_int: AttrProto[int], attr_float: AttrProto[float]):\n v1: AttrProto[float] = attr_int # E\n v2: AttrProto[int] = attr_float # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n# > The self-types in protocols follow the rules for other methods.\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n# > In addition, the first argument in an instance method can be annotated\n# > with a type variable. In this case the return type may use the same\n# > type variable, thus making that method a generic function.\n\n\nT_bounded = TypeVar(\"T_bounded\", bound=\"HasParent\")\n\n\nclass HasParent(Protocol):\n def get_parent(self: T_bounded) -> T_bounded:\n ...\n\n\nGenericHasParent = TypeVar(\"GenericHasParent\", bound=HasParent)\n\n\ndef generic_get_parent(n: GenericHasParent) -> GenericHasParent:\n return n.get_parent()\n\n\nclass ConcreteHasParent:\n def get_parent(self) -> Self:\n return self\n\n\nparent = generic_get_parent(ConcreteHasParent()) # OK\nassert_type(parent, ConcreteHasParent)\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > `Self` is valid within Protocols, similar to its use in classes:\n\n\nclass HasParentProperty(Protocol):\n @property\n def parent(self) -> Self:\n ...\n\n\nclass ConcreteParentProperty:\n @property\n def parent(self) -> Self:\n return self\n\n\nclass InvalidParentProperty:\n @property\n def parent(self) -> HasParentProperty:\n return ConcreteParentProperty()\n\n\nhp1: HasParentProperty = ConcreteParentProperty() # OK\nhp2: HasParentProperty = InvalidParentProperty() # E\n\n\n\nclass HasMethod(Protocol):\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n ...\n\n\nclass ConcreteHasMethod:\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n return \"\"\n\n\nclass InvalidHasMethod:\n def m(self, item: int, callback: Callable[[int], str]) -> str:\n return \"\"\n\n\nhm1: HasMethod = ConcreteHasMethod() # OK\nhm2: HasMethod = InvalidHasMethod() # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > Checking a class for assignability to a protocol: If a protocol uses `Self`\n# > in methods or attribute annotations, then a class `Foo` is assignable\n# > to the protocol if its corresponding methods and attribute annotations use\n# > either `Self` or `Foo` or any of `Foo`'s subclasses.\n\n\nclass HasGreaterThan(Protocol):\n def __gt__(self, other: Self) -> bool:\n ...\n\n\nclass ConcreteGreaterThan1:\n def __gt__(self, other: Self) -> bool:\n return False\n\n\nclass ConcreteGreaterThan2:\n def __gt__(self, other: \"ConcreteGreaterThan2\") -> bool:\n return False\n\n\nclass InvalidGreaterThan:\n def __gt__(self, other: int) -> bool:\n return False\n\n\nhg1: HasGreaterThan = ConcreteGreaterThan1() # OK\nhg2: HasGreaterThan = ConcreteGreaterThan2() # OK\nhg3: HasGreaterThan = InvalidGreaterThan() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_generic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_05.py","code":"\"\"\"\nTests merging and extending of protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#merging-and-extending-protocols\n\nfrom abc import abstractmethod\nfrom typing import Protocol\nfrom collections.abc import Sized\n\n\nclass SizedAndClosable1(Sized, Protocol):\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable2(Protocol):\n def __len__(self) -> int:\n ...\n\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable3(SizedAndClosable1): # Note: not a protocol\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete1:\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete2:\n def close(self) -> None:\n pass\n\n\ns1: SizedAndClosable1 = SCConcrete1() # OK\ns2: SizedAndClosable2 = SCConcrete1() # OK\ns3: SizedAndClosable1 = SizedAndClosable3() # OK\ns4: SizedAndClosable2 = SizedAndClosable3() # OK\ns5: Sized = SCConcrete1() # OK\n\ns6: SizedAndClosable1 = SCConcrete2() # E: doesn't implement `__len__`\ns7: SizedAndClosable2 = SCConcrete2() # E: doesn't implement `__len__`\ns8: SizedAndClosable3 = SCConcrete2() # E: SizedAndClosable3 is not a protocol\n\n\ndef func1(s1: SizedAndClosable1, s2: SizedAndClosable2):\n # > The two definitions of SizedAndClosable are equivalent.\n v1: SizedAndClosable2 = s1\n v2: SizedAndClosable1 = s2\n\n\n# > If Protocol is included in the base class list, all the other base classes\n# > must be protocols.\n\n\nclass BadProto(SizedAndClosable3, Protocol): # E: SizedAndClosable3 is not a protocol\n ...\n\n\n# > Without this base, the class is “downgraded” to a regular ABC that\n# > cannot be used with structural subtyping.\nclass SizedAndClosable4(SizedAndClosable1):\n def __len__(self) -> int:\n return 0\n\n @abstractmethod\n def close(self) -> None:\n raise NotImplementedError\n\n\nx = SizedAndClosable4() # E: cannot instantiate abstract class\ny: SizedAndClosable4 = SCConcrete1() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_merging.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_06.py","code":"\"\"\"\nTests the handling of modules as the implementation of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#modules-as-implementations-of-protocols\n\n# > A module object is accepted where a protocol is expected if the public\n# > interface of the given module is compatible with the expected protocol.\n\nimport _protocols_modules1\nimport _protocols_modules2\nfrom typing import Protocol\n\n\nclass Options1(Protocol):\n timeout: int\n one_flag: bool\n other_flag: bool\n\n\nclass Options2(Protocol):\n timeout: str\n\n\nop1: Options1 = _protocols_modules1 # OK\nop2: Options2 = _protocols_modules1 # E\n\n\nclass Reporter1(Protocol):\n def on_error(self, x: int) -> None:\n ...\n\n def on_success(self) -> None:\n ...\n\n\nclass Reporter2(Protocol):\n def on_error(self, x: int) -> int:\n ...\n\n\nclass Reporter3(Protocol):\n def not_implemented(self, x: int) -> int:\n ...\n\n\nrp1: Reporter1 = _protocols_modules2 # OK\nrp2: Reporter2 = _protocols_modules2 # E\nrp3: Reporter3 = _protocols_modules2 # E\n","source":"typing_tests","origin":"conformance/tests/protocols_modules.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_07.py","code":"\"\"\"\nTests the handling of recursive protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#recursive-protocols\n\n\nfrom typing import Generic, Iterable, Never, Protocol, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Traversable(Protocol):\n def leaves(self) -> Iterable[\"Traversable\"]:\n ...\n\n\nclass SimpleTree:\n def leaves(self) -> list[\"SimpleTree\"]:\n return []\n\n\nroot: Traversable = SimpleTree() # OK\n\n\nclass Tree(Generic[T]):\n def leaves(self) -> list[\"Tree[T]\"]:\n return []\n\n\ndef walk(graph: Traversable) -> None:\n pass\n\n\ntree: Tree[float] = Tree()\nwalk(tree) # OK\n\n\nclass ProtoA(Protocol[T_co, T_contra]):\n def method1(self) -> \"ProtoA[T_co, T_contra]\":\n ...\n\n @classmethod\n def method2(cls, value: T_contra) -> None:\n ...\n\n\nclass ProtoB(Protocol[T_co, T_contra]):\n def method3(self) -> ProtoA[T_co, T_contra]:\n ...\n\n\nclass ImplA:\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls, value: int) -> None:\n pass\n\n\nclass ImplB:\n def method3(self) -> ImplA:\n return ImplA()\n\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls: type[ProtoB[object, T]], value: list[T]) -> None:\n pass\n\n\ndef func1(x: ProtoA[Never, T]) -> T:\n raise NotImplementedError\n\n\nv1 = func1(ImplB())\nassert_type(v1, list[int])\n","source":"typing_tests","origin":"conformance/tests/protocols_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_08.py","code":"\"\"\"\nTests the handling of the @runtime_checkable decorator for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#runtime-checkable-decorator-and-narrowing-types-by-isinstance\n\n# > A protocol can be used as a second argument in isinstance() and\n# > issubclass() only if it is explicitly opt-in by @runtime_checkable decorator.\n\nfrom typing import Any, Protocol, runtime_checkable\n\n\nclass Proto1(Protocol):\n name: str\n\n\n@runtime_checkable\nclass Proto2(Protocol):\n name: str\n\n\ndef func1(a: Any):\n if isinstance(a, Proto1): # E: not runtime_checkable\n return\n\n if isinstance(a, Proto2): # OK\n return\n\n\n# > isinstance() can be used with both data and non-data protocols, while\n# > issubclass() can be used only with non-data protocols.\n\n\n@runtime_checkable\nclass DataProtocol(Protocol):\n name: str\n\n def method1(self) -> int:\n ...\n\n\n@runtime_checkable\nclass NonDataProtocol(Protocol):\n def method1(self) -> int:\n ...\n\n\ndef func2(a: Any):\n if isinstance(a, DataProtocol): # OK\n return\n\n if isinstance(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, DataProtocol): # E\n return\n\n if issubclass(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, (NonDataProtocol, DataProtocol)): # E\n return\n\n\n# > Type checkers should reject an isinstance() or issubclass() call if there\n# > is an unsafe overlap between the type of the first argument and the protocol.\n\n\n@runtime_checkable\nclass Proto3(Protocol):\n def method1(self, a: int) -> int:\n ...\n\n\nclass Concrete3A:\n def method1(self, a: str) -> None:\n pass\n\n\nclass Concrete3B:\n method1: int = 1\n\n\ndef func3():\n if isinstance(Concrete3A(), Proto2): # OK\n pass\n\n if isinstance(Concrete3A(), Proto3): # E: unsafe overlap\n pass\n\n if isinstance(Concrete3B(), (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n\n if issubclass(Concrete3A, (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n","source":"typing_tests","origin":"conformance/tests/protocols_runtime_checkable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_09.py","code":"\"\"\"\nTests the handling of annotated \"self\" parameters in a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n\nfrom typing import Generic, Protocol, Self, TypeVar\n\n\nC = TypeVar(\"C\", bound=\"Copyable\")\n\n\nclass Copyable(Protocol):\n def copy(self: C) -> C:\n return self\n\n\nclass One:\n def copy(self) -> \"One\":\n return One()\n\n\nT = TypeVar(\"T\", bound=\"Other\")\n\n\nclass Other:\n def copy(self: T) -> T:\n return self\n\n\nc: Copyable\nc = One() # OK\nc = Other() # OK\n\n\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT2_co = TypeVar(\"T2_co\", covariant=True)\n\n\nclass P1Parent(Protocol[T2_co]):\n def f0(self, /) -> Self:\n ...\n\n\nclass P1Child(P1Parent[T2_co], Protocol[T2_co]):\n ...\n\n\nclass C1(Generic[T1_co]):\n def f0(self, /) -> Self:\n return self\n\n\na1: P1Parent[str] = C1[str]()\nb1: P1Child[str] = C1[str]()\n\n\nclass P2Parent(Protocol[T1_co]):\n def f0(self, right: Self, /) -> \"P2Parent[T1_co]\":\n return right\n\n\nclass P2Child(P2Parent[T1_co], Protocol[T1_co]):\n ...\n\n\nclass C2(Generic[T2_co]):\n def f0(self, other: Self) -> \"C2[T2_co]\":\n return other\n\n\na2: P2Parent[str] = C2[str]() # OK\nb2: P2Child[str] = C2[str]() # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_self.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_10.py","code":"\"\"\"\nTests subtyping rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#subtyping-relationships-with-other-types\n\n# > Protocols cannot be instantiated.\n\nfrom typing import Hashable, Iterable, Protocol, Sequence, TypeVar\n\n\nclass Proto1(Protocol):\n pass\n\n\np1 = Proto1() # E: protocol cannot be instantiated\n\n\n# > A protocol is never a subtype of a concrete type.\n\n# > A concrete type X is a subtype of protocol P if and only if X implements\n# > all protocol members of P with compatible types. In other words, subtyping\n# > with respect to a protocol is always structural.\n\n\nclass Proto2(Protocol):\n def method1(self) -> None:\n ...\n\n\nclass Concrete2:\n def method1(self) -> None:\n pass\n\n\ndef func1(p2: Proto2, c2: Concrete2):\n v1: Proto2 = c2 # OK\n v2: Concrete2 = p2 # E\n\n\n# > A protocol P1 is a subtype of another protocol P2 if P1 defines all\n# > protocol members of P2 with compatible types.\n\n\nclass Proto3(Protocol):\n def method1(self) -> None:\n ...\n\n def method2(self) -> None:\n ...\n\n\ndef func2(p2: Proto2, p3: Proto3):\n v1: Proto2 = p3 # OK\n v2: Proto3 = p2 # E\n\n\n# > Generic protocols follow the rules for generic abstract classes, except\n# > for using structural compatibility instead of compatibility defined by\n# > inheritance relationships.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n\nclass Proto4(Protocol[S, T]):\n def method1(self, a: S, b: T) -> tuple[S, T]:\n ...\n\n\nclass Proto5(Protocol[T]):\n def method1(self, a: T, b: T) -> tuple[T, T]:\n ...\n\n\ndef func3(p4_int: Proto4[int, int], p5_int: Proto5[int]):\n v1: Proto4[int, int] = p5_int # OK\n v2: Proto5[int] = p4_int # OK\n v3: Proto4[int, float] = p5_int # E\n v4: Proto5[float] = p4_int # E\n\n\nS_co = TypeVar(\"S_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Proto6(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\nclass Proto7(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\ndef func4(p6: Proto6[float, float]):\n v1: Proto7[object, int] = p6 # OK\n v2: Proto7[float, float] = p6 # OK\n v3: Proto7[complex, int] = p6 # OK\n\n v4: Proto7[int, float] = p6 # E\n v5: Proto7[float, object] = p6 # E\n\n\n# > Unions of protocol classes behaves the same way as for non-protocol classes.\n\n\nclass SupportsExit(Protocol):\n def exit(self) -> int:\n ...\n\n\nclass SupportsQuit(Protocol):\n def quit(self) -> int | None:\n ...\n\n\ndef finish(task: SupportsExit | SupportsQuit) -> int:\n return 0\n\n\nclass DefaultJob:\n def quit(self) -> int:\n return 0\n\n\nfinish(DefaultJob()) # OK\n\n\n# > One can use multiple inheritance to define an intersection of protocols.\n\n\nclass HashableFloats(Iterable[float], Hashable, Protocol):\n pass\n\n\ndef cached_func(args: HashableFloats) -> float:\n return 0.0\n\n\ncached_func((1, 2, 3)) # OK, tuple is both hashable and iterable\n","source":"typing_tests","origin":"conformance/tests/protocols_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_11.py","code":"\"\"\"\nTests type variable variance inference for generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\nfrom typing import Protocol, TypeVar\nfrom typing_extensions import ParamSpec\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", bound=int)\nT3 = TypeVar(\"T3\", bytes, str)\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT1_contra = TypeVar(\"T1_contra\", contravariant=True)\nP = ParamSpec(\"P\", contravariant=True)\nR = TypeVar(\"R\", covariant=True)\n\n# > Type checkers will warn if the inferred variance is different from the\n# > declared variance.\n\n\nclass AnotherBox(Protocol[T1]): # E: T should be covariant\n def content(self) -> T1:\n ...\n\n\nclass Protocol1(Protocol[T1, T2, T3]): # OK\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1 | T2:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n def m4(self) -> T3:\n ...\n\n\nclass Protocol2(Protocol[T1, T2, T3]): # E: T3 should be contravariant\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n\nclass Protocol3(Protocol[T1_co]):\n def m1(self) -> None:\n pass\n\n\nclass Protocol4(Protocol[T1]): # E: T1 should be contravariant\n def m1(self, p0: T1) -> None:\n ...\n\n\nclass Protocol5(Protocol[T1_co]): # E[covariant_in_input+]\n def m1(self, p0: T1_co) -> None: # E[covariant_in_input+]\n ...\n\n\nclass Protocol6(Protocol[T1]): # E: T1 should be covariant\n def m1(self) -> T1:\n ...\n\n\nclass Protocol7(Protocol[T1_contra]): # E[contravariant_in_output+]\n def m1(self) -> T1_contra: # E[contravariant_in_output+]\n ...\n\n\nclass Protocol8(Protocol[T1]): # OK\n def m1(self) -> T1:\n ...\n\n def m2(self, p1: T1) -> None:\n pass\n\n\nclass Callback(Protocol[P, R]): # OK\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\nclass Protocol9(Protocol[T1_co]): # OK\n @property\n def prop1(self) -> T1_co:\n ...\n\n\nclass Protocol10(Protocol[T1_co]): # OK\n def m1(self) -> type[T1_co]:\n ...\n\n\nclass Protocol11(Protocol[T1]): # OK\n x: T1 | None\n\n\nclass Protocol12(Protocol[T1]): # E: T1 should be covariant\n # __init__ method is exempt from variance calculations.\n def __init__(self, x: T1) -> None:\n ...\n\n\nclass Protocol13(Protocol[T1_contra]): # OK\n def m1(self: \"Protocol13[T1_contra]\", x: T1_contra) -> None:\n ...\n\n @classmethod\n def m2(cls: \"type[Protocol13[T1_contra]]\") -> None:\n ...\n\n\nclass Protocol14(Protocol[T1]): # OK\n def m1(self) -> list[T1]:\n ...\n","source":"typing_tests","origin":"conformance/tests/protocols_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"required-notrequired","pep":"655","introduced_in":"3.11","form":"modern","file":"required-notrequired/modern_01.py","code":"\"\"\"\nTests the Required and NotRequired special forms.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#required-and-notrequired\n\nfrom typing import Annotated, NotRequired, Required, TypedDict\n\n\n# Required and NotRequired are valid only within a TypedDict.\nclass NotTypedDict:\n x: Required[int] # E: Required not allowed in this context\n\n\ndef func1(\n x: NotRequired[int], # E: NotRequired not allowed in this context\n) -> None:\n pass\n\n\nclass TD1(TypedDict, total=False):\n a: int\n\n\nclass TD2(TD1, total=True):\n b: int\n\n\nclass TD3(TypedDict):\n a: NotRequired[int]\n b: Required[int]\n\n\nclass TD4(TypedDict, total=False):\n a: int\n b: Required[int]\n\n\nclass TD5(TypedDict, total=True):\n a: NotRequired[int]\n b: int\n\n\ntd3: TD3 = {\"b\": 0}\ntd4: TD4 = {\"b\": 0}\ntd5: TD5 = {\"b\": 0}\n\n# These are all equivalent types, so they should be\n# bidirectionally type compatible.\ntd3 = td4\ntd3 = td5\ntd4 = td3\ntd4 = td5\ntd5 = td3\ntd5 = td4\n\n\nclass TD6(TypedDict):\n a: Required[Required[int]] # E: Nesting not allowed\n b: Required[NotRequired[int]] # E: Nesting not allowed\n\n\nclass TD7(TypedDict):\n # > Required[] and NotRequired[] can be used with Annotated[], in any nesting order.\n x: Annotated[Required[int], \"\"]\n y: Required[Annotated[int, \"\"]]\n z: Annotated[Required[Annotated[int, \"\"]], \"\"]\n\n\nRecursiveMovie = TypedDict(\n \"RecursiveMovie\", {\"title\": Required[str], \"predecessor\": NotRequired[\"RecursiveMovie\"]}\n)\n\nmovie: RecursiveMovie = {\"title\": \"Beethoven 3\", \"predecessor\": {\"title\": \"Beethoven 2\"}}\n","source":"typing_tests","origin":"conformance/tests/typeddicts_required.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_01.py","code":"\"\"\"\nTests for advanced or special-case usage of the typing.Self type.\n\"\"\"\n\nfrom typing import assert_type, Self\n\n\nclass ParentA:\n # Test for property that returns Self.\n @property\n def prop1(self) -> Self:\n raise NotImplementedError\n\nclass ChildA(ParentA):\n ...\n\n\nassert_type(ParentA().prop1, ParentA)\nassert_type(ChildA().prop1, ChildA)\n\n\n# Test for a child that accesses an attribute within a parent\n# whose type is annotated using Self.\nclass ParentB:\n a: list[Self]\n\n @classmethod\n def method1(cls) -> Self:\n raise NotImplementedError\n\nclass ChildB(ParentB):\n b: int = 0\n\n def method2(self) -> None:\n assert_type(self, Self)\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = self.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(self.method1(), Self)\n\n @classmethod\n def method3(cls) -> None:\n assert_type(cls, type[Self])\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = cls.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(cls.method1(), Self)\n","source":"typing_tests","origin":"conformance/tests/generics_self_advanced.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_02.py","code":"\"\"\"\nTests for usage of the typing.Self type with attributes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-attribute-annotations\n\nfrom typing import TypeVar, Generic, Self\nfrom dataclasses import dataclass\n\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass LinkedList(Generic[T]):\n value: T\n next: Self | None = None\n\n\n@dataclass\nclass OrdinalLinkedList(LinkedList[int]):\n def ordinal_value(self) -> str:\n return str(self.value)\n\n\n# This should result in a type error.\nxs = OrdinalLinkedList(value=1, next=LinkedList[int](value=2)) # E\n\nif xs.next is not None:\n xs.next = OrdinalLinkedList(value=3, next=None) # OK\n\n # This should result in a type error.\n xs.next = LinkedList[int](value=3, next=None) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_attributes.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_03.py","code":"\"\"\"\nTests for basic usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#self.\n\nfrom typing import Callable, Generic, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n\nclass Shape:\n def set_scale(self, scale: float) -> Self:\n assert_type(self, Self)\n self.scale = scale\n return self\n\n def method2(self) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n def method3(self) -> \"Shape\":\n return self\n\n @classmethod\n def from_config(cls, config: dict[str, float]) -> Self:\n assert_type(cls, type[Self])\n return cls()\n\n @classmethod\n def cls_method2(cls) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n @classmethod\n def cls_method3(cls) -> \"Shape\":\n return cls()\n\n def difference(self, other: Self) -> float:\n assert_type(other, Self)\n return 0.0\n\n def apply(self, f: Callable[[Self], None]) -> None:\n return f(self)\n\n\nclass Circle(Shape):\n pass\n\n\nassert_type(Shape().set_scale(1.0), Shape)\nassert_type(Circle().set_scale(1.0), Circle)\n\nassert_type(Shape.from_config({}), Shape)\nassert_type(Circle.from_config({}), Circle)\n\n\nclass Container(Generic[T]):\n value: T\n\n def __init__(self, value: T) -> None:\n self.value = value\n\n def set_value(self, value: T) -> Self:\n raise NotImplementedError\n\n # This should generate an error because Self isn't subscriptable.\n def foo(self, other: Self[int]) -> None: # E\n pass\n\n\ndef object_with_concrete_type(\n int_container: Container[int], str_container: Container[str]\n) -> None:\n assert_type(int_container.set_value(42), Container[int])\n assert_type(str_container.set_value(\"hello\"), Container[str])\n\n\ndef object_with_generic_type(\n container: Container[T],\n value: T,\n) -> Container[T]:\n val = container.set_value(value)\n assert_type(val, Container[T])\n return val\n","source":"typing_tests","origin":"conformance/tests/generics_self_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_04.py","code":"\"\"\"\nTests for usage of the typing.Self type with protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n\nfrom typing import Protocol, Self, assert_type\n\n\nclass ShapeProtocol(Protocol):\n def set_scale(self, scale: float) -> Self:\n ...\n\n\nclass ReturnSelf:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> Self:\n self.scale = scale\n return self\n\n\nclass ReturnConcreteShape:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> \"ReturnConcreteShape\":\n self.scale = scale\n return self\n\n\nclass BadReturnType:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> int:\n self.scale = scale\n return 42\n\n\nclass ReturnDifferentClass:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> ReturnConcreteShape:\n return ReturnConcreteShape()\n\n\ndef accepts_shape(shape: ShapeProtocol) -> None:\n y = shape.set_scale(0.5)\n assert_type(y, ShapeProtocol)\n\n\ndef main(\n return_self_shape: ReturnSelf,\n return_concrete_shape: ReturnConcreteShape,\n bad_return_type: BadReturnType,\n return_different_class: ReturnDifferentClass,\n) -> None:\n accepts_shape(return_self_shape) # OK\n accepts_shape(return_concrete_shape) # OK\n\n # This should generate a type error.\n accepts_shape(bad_return_type) # E\n\n # Not OK because it returns a non-subclass.\n accepts_shape(return_different_class) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_protocols.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_05.py","code":"\"\"\"\nTests for valid and invalid usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#valid-locations-for-self\n\nfrom typing import Any, Callable, Generic, Self, TypeAlias, TypeVar\n\nclass ReturnsSelf:\n def foo(self) -> Self: # Accepted\n return self\n\n @classmethod\n def bar(cls) -> Self: # Accepted\n return cls(1)\n\n def __new__(cls, value: int) -> Self: # Accepted\n return cls(1)\n\n def explicitly_use_self(self: Self) -> Self: # Accepted\n return self\n\n # Accepted (Self can be nested within other types)\n def returns_list(self) -> list[Self]:\n return []\n\n # Accepted (Self can be nested within other types)\n @classmethod\n def return_cls(cls) -> type[Self]:\n return cls\n\nclass Child(ReturnsSelf):\n # Accepted (we can override a method that uses Self annotations)\n def foo(self) -> Self:\n return self\n\nclass TakesSelf:\n def foo(self, other: Self) -> bool: # Accepted\n return True\n\nclass Recursive:\n # Accepted (treated as an @property returning ``Self | None``)\n next: Self | None\n\nclass CallableAttribute:\n def foo(self) -> int:\n return 0\n\n # Accepted (treated as an @property returning the Callable type)\n bar: Callable[[Self], int] = foo\n\nclass HasNestedFunction:\n x: int = 42\n\n def foo(self) -> None:\n\n # Accepted (Self is bound to HasNestedFunction).\n def nested(z: int, inner_self: Self) -> Self:\n print(z)\n print(inner_self.x)\n return inner_self\n\n nested(42, self) # OK\n\n\nclass Outer:\n class Inner:\n def foo(self) -> Self: # Accepted (Self is bound to Inner)\n return self\n\n\n# This should generate an error.\ndef foo(bar: Self) -> Self: ... # E: not within a class\n\n# This should generate an error.\nbar: Self # E: not within a class\n\nTFoo2 = TypeVar(\"TFoo2\", bound=\"Foo2\")\n\nclass Foo2:\n # Rejected (Self is treated as unknown).\n def has_existing_self_annotation(self: TFoo2) -> Self: # E\n raise NotImplementedError\n\nclass Foo3:\n def return_concrete_type(self) -> Self:\n return Foo3() # E (see FooChild below for rationale)\n\nclass Foo3Child(Foo3):\n child_value: int = 42\n\n def child_method(self) -> None:\n y = self.return_concrete_type()\n y.child_value\n\nT = TypeVar(\"T\")\n\nclass Bar(Generic[T]):\n def bar(self) -> T:\n raise NotImplementedError\n\n# This should generate an error.\nclass Baz(Bar[Self]): ... # E\n\nclass Baz2(Self): ... # E\n\n# This should generate an error.\nTupleSelf: TypeAlias = tuple[Self] # E\n\nclass Base:\n @staticmethod\n # This should generate an error.\n def make() -> Self: # E\n raise NotImplementedError\n\n @staticmethod\n # This should generate an error.\n def return_parameter(foo: Self) -> Self: # E\n raise NotImplementedError\n\nclass MyMetaclass(type):\n # This should generate an error.\n def __new__(cls, *args: Any) -> Self: # E\n raise NotImplementedError\n\n # This should generate an error.\n def __mul__(cls, count: int) -> list[Self]: # E\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_self_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_01.py","code":"\"\"\"\nTests explicit type aliases defined with `TypeAlias`.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#typealias\n\nfrom typing import Any, Callable, Concatenate, Literal, ParamSpec, TypeVar, Union, assert_type\nfrom typing import TypeAlias as TA\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1: TA = Union[int, str]\nGoodTypeAlias2: TA = int | None\nGoodTypeAlias3: TA = list[GoodTypeAlias2]\nGoodTypeAlias4: TA = list[T]\nGoodTypeAlias5: TA = tuple[T, ...] | list[T]\nGoodTypeAlias6: TA = tuple[int, int, S, T]\nGoodTypeAlias7: TA = Callable[..., int]\nGoodTypeAlias8: TA = Callable[[int, T], T]\nGoodTypeAlias9: TA = Callable[Concatenate[int, P], R]\nGoodTypeAlias10: TA = Any\nGoodTypeAlias11: TA = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12: TA = Callable[P, None]\nGoodTypeAlias13: TA = \"int | str\"\nGoodTypeAlias14: TA = list[\"int | str\"]\nGoodTypeAlias15: TA = Literal[3, 4, 5, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12,\n p13: GoodTypeAlias13,\n p14: GoodTypeAlias14,\n p15: GoodTypeAlias15,\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, Callable[..., None])\n assert_type(p13, int | str)\n assert_type(p14, list[int | str])\n assert_type(p15, Literal[3, 4, 5, None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be allowed as type aliases.\nBadTypeAlias1: TA = eval(\"\".join(map(chr, [105, 110, 116]))) # E\nBadTypeAlias2: TA = [int, str] # E\nBadTypeAlias3: TA = ((int, str),) # E\nBadTypeAlias4: TA = [int for i in range(1)] # E\nBadTypeAlias5: TA = {\"a\": \"b\"} # E\nBadTypeAlias6: TA = (lambda: int)() # E\nBadTypeAlias7: TA = [int][0] # E\nBadTypeAlias8: TA = int if 1 < 3 else str # E\nBadTypeAlias9: TA = var1 # E\nBadTypeAlias10: TA = True # E\nBadTypeAlias11: TA = 1 # E\nBadTypeAlias12: TA = list or set # E\nBadTypeAlias13: TA = f\"{'int'}\" # E\n\n\nListAlias: TA = list\nListOrSetAlias: TA = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2: ListAlias[int] # E: already specialized\nx3 = ListOrSetAlias() # E: cannot instantiate union\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_02.py","code":"\"\"\"\nTests recursive (self-referential) type aliases.\n\"\"\"\n\n# The typing specification doesn't mandate support for recursive\n# (self-referential) type aliases prior to PEP 695, but it also\n# doesn't indicates that they shouldn't work.\n# Most type checkers now support them, and many libraries and code\n# bases have started to rely on them.\n# PEP 695 formally mandates that recursive type aliases work.\n\nfrom typing import Mapping, TypeAlias, TypeVar, Union\n\nJson = Union[None, int, str, float, list[\"Json\"], dict[str, \"Json\"]]\n\nj1: Json = [1, {\"a\": 1}] # OK\nj2: Json = 3.4 # OK\nj3: Json = [1.2, None, [1.2, [\"\"]]] # OK\nj4: Json = {\"a\": 1, \"b\": 3j} # E: incompatible type\nj5: Json = [2, 3j] # E: incompatible type\n\n\n# This type alias should be equivalent to Json.\nJson2 = Union[None, int, str, float, list[\"Json2\"], dict[str, \"Json2\"]]\n\ndef func1(j1: Json) -> Json2:\n return j1\n\n\nRecursiveTuple = str | int | tuple[\"RecursiveTuple\", ...]\n\n\nt1: RecursiveTuple = (1, 1) # OK\nt2: RecursiveTuple = (1, \"1\") # OK\nt3: RecursiveTuple = (1, \"1\", 1, \"2\") # OK\nt4: RecursiveTuple = (1, (\"1\", 1), \"2\") # OK\nt5: RecursiveTuple = (1, (\"1\", 1), (1, (1, 2))) # OK\nt6: RecursiveTuple = (1, (\"1\", 1), (1, (1, [2]))) # E\nt7: RecursiveTuple = (1, [1]) # E\n\n\nRecursiveMapping = str | int | Mapping[str, \"RecursiveMapping\"]\n\nm1: RecursiveMapping = 1 # OK\nm2: RecursiveMapping = \"1\" # OK\nm3: RecursiveMapping = {\"1\": \"1\"} # OK\nm4: RecursiveMapping = {\"1\": \"1\", \"2\": 1} # OK\nm5: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {}} # OK\nm6: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": \"2\", \"2\": {}}} # OK\nm7: RecursiveMapping = {\"1\": [1]} # E\nm8: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": [1, 2]} # E\nm9: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": 1, \"2\": [1, 2, 3]}} # E\n\n\nT1 = TypeVar(\"T1\", str, int)\nT2 = TypeVar(\"T2\")\n\nGenericTypeAlias1 = list[\"GenericTypeAlias1[T1]\" | T1]\nSpecializedTypeAlias1 = GenericTypeAlias1[str]\n\ng1: SpecializedTypeAlias1 = [\"hi\", [\"hi\", \"hi\"]] # OK\ng2: GenericTypeAlias1[str] = [\"hi\", \"bye\", [\"\"], [[\"hi\"]]] # OK\ng3: GenericTypeAlias1[str] = [\"hi\", [2.4]] # E\n\nGenericTypeAlias2 = list[\"GenericTypeAlias2[T1, T2]\" | T1 | T2]\n\ng4: GenericTypeAlias2[str, int] = [[3, [\"hi\"]], \"hi\"] # OK\ng5: GenericTypeAlias2[str, float] = [[3, [\"hi\", 3.4, [3.4]]], \"hi\"] # OK\ng6: GenericTypeAlias2[str, int] = [[3, [\"hi\", 3, [3.4]]], \"hi\"] # E\n\n\nRecursiveUnion: TypeAlias = Union[\"RecursiveUnion\", int] # E: cyclical reference\n\n# On one line because different type checkers report the error on different lines\nMutualReference1: TypeAlias = Union[\"MutualReference2\", int]; MutualReference2: TypeAlias = Union[\"MutualReference1\", str] # E: cyclical reference\n","source":"typing_tests","origin":"conformance/tests/aliases_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-guard","pep":"647","introduced_in":"3.10","form":"modern","file":"type-guard/modern_01.py","code":"\"\"\"\nTests TypeGuard functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeguard\n\nfrom typing import Any, Callable, Protocol, Self, TypeGuard, TypeVar, assert_type\n\n\nT = TypeVar(\"T\")\n\ndef is_two_element_tuple(val: tuple[T, ...]) -> TypeGuard[tuple[T, T]]:\n return len(val) == 2\n\ndef func1(names: tuple[str, ...]):\n if is_two_element_tuple(names):\n assert_type(names, tuple[str, str])\n else:\n assert_type(names, tuple[str, ...])\n\n\ndef is_str_list(val: list[object], allow_empty: bool) -> TypeGuard[list[str]]:\n if len(val) == 0:\n return allow_empty\n return all(isinstance(x, str) for x in val)\n\ndef is_set_of(val: set[Any], type: type[T]) -> TypeGuard[set[T]]:\n return all(isinstance(x, type) for x in val)\n\ndef func2(val: set[object]):\n if is_set_of(val, int):\n assert_type(val, set[int])\n else:\n assert_type(val, set[object])\n\n\nT_A = TypeVar(\"T_A\", bound=\"A\")\n\nclass A:\n def tg_1(self, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @classmethod\n def tg_2(cls, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @staticmethod\n def tg_3(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n def tg4(self, val: object) -> TypeGuard[Self]:\n return isinstance(val, type(self))\n\n def tg5(self: T_A, val: object) -> TypeGuard[T_A]:\n return isinstance(val, type(self))\n\nclass B(A):\n pass\n\n# > Type checkers should assume that type narrowing should be applied to\n# > the expression that is passed as the first positional argument to a\n# > user-defined type guard. If the type guard function accepts more than\n# > one argument, no type narrowing is applied to those additional argument\n# > expressions.\n\ndef func3() -> None:\n val1 = object()\n if A().tg_1(val1):\n assert_type(val1, int)\n\n val2 = object()\n if A().tg_2(val2):\n assert_type(val2, int)\n\n val3 = object()\n if A.tg_2(val3):\n assert_type(val3, int)\n\n val4 = object()\n if A().tg_3(val4):\n assert_type(val4, int)\n\n val5 = object()\n if A.tg_3(val5):\n assert_type(val5, int)\n\n val6 = object()\n if B().tg4(val6):\n assert_type(val6, B)\n\n val7 = object()\n if B().tg4(val7):\n assert_type(val7, B)\n\n\n# > If a type guard function is implemented as an instance method or class\n# > method, the first positional argument maps to the second parameter\n# > (after “self” or “cls”).\n\nclass C:\n # Type checker should emit error here.\n def tg_1(self) -> TypeGuard[int]: # E\n return False\n\n @classmethod\n # Type checker should emit error here.\n def tg_2(cls) -> TypeGuard[int]: # E\n return False\n\n# > ``TypeGuard`` is also valid as the return type of a ``Callable`` type. In that\n# > context, it is treated as a subtype of bool. For example, ``Callable[..., TypeGuard[int]]``\n# > is assignable to ``Callable[..., bool]``.\n\n\ndef takes_callable_bool(f: Callable[[object], bool]) -> None:\n pass\n\n\ndef takes_callable_str(f: Callable[[object], str]) -> None:\n pass\n\n\ndef simple_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ntakes_callable_bool(simple_typeguard) # OK\ntakes_callable_str(simple_typeguard) # E\n\n\nclass CallableBoolProto(Protocol):\n def __call__(self, val: object) -> bool: ...\n\n\nclass CallableStrProto(Protocol):\n def __call__(self, val: object) -> str: ...\n\n\ndef takes_callable_bool_proto(f: CallableBoolProto) -> None:\n pass\n\n\ndef takes_callable_str_proto(f: CallableStrProto) -> None:\n pass\n\n\ntakes_callable_bool_proto(simple_typeguard) # OK\ntakes_callable_str_proto(simple_typeguard) # E\n\n# > Unlike ``TypeGuard``, ``TypeIs`` is invariant in its argument type:\n# > ``TypeIs[B]`` is not a subtype of ``TypeIs[A]``,\n# > even if ``B`` is a subtype of ``A``.\n\ndef takes_int_typeguard(f: Callable[[object], TypeGuard[int]]) -> None:\n pass\n\n\ndef int_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ndef bool_typeguard(val: object) -> TypeGuard[bool]:\n return isinstance(val, bool)\n\n\ntakes_int_typeguard(int_typeguard) # OK\ntakes_int_typeguard(bool_typeguard) # OK\n","source":"typing_tests","origin":"conformance/tests/narrowing_typeguard.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_13.py","code":"\"\"\"\nTests the \"alternative\" (non-class) syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#alternative-syntax\n\nfrom typing import TypedDict\n\n\nMovie = TypedDict(\"Movie\", {\"name\": str, \"year\": int, \"illegal key name\": bool})\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982, \"illegal key name\": True}\n\nMovieOptional = TypedDict(\"MovieOptional\", {\"name\": str, \"year\": int}, total=False)\n\nmovie_opt1: MovieOptional = {}\nmovie_opt2: MovieOptional = {\"year\": 1982}\n\n# > A type checker is only expected to accept a dictionary display expression as\n# > the second argument to TypedDict. In particular, a variable that refers to a\n# > dictionary object does not need to be supported, to simplify implementation.\nmy_dict = {\"name\": str}\nBadTypedDict1 = TypedDict(\"BadTypedDict1\", my_dict) # E\n\n\n# This should generate an error because it uses a non-str key.\nBadTypedDict2 = TypedDict(\"BadTypedDict2\", {1: str}) # E\n\n\n# This should generate an error because it uses a non-matching name.\nBadTypedDict3 = TypedDict(\"WrongName\", {\"name\": str}) # E\n\n\n# This should generate an error because of the additional parameter.\nBadTypedDict4 = TypedDict(\"BadTypedDict4\", {\"name\": str}, total=False, other=False) # E\n\n\n# > The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13.\n# > It may also be unsupported by static type checkers.\n\nMovie2 = TypedDict(\"Movie2\", name=str, year=int) # E?\n\nmovie2: Movie2\nmovie2 = {\"name\": \"Blade Runner\", \"year\": 1982} # E?: May generate errors if keyword-argument syntax is unsupported\nmovie2 = {\"name\": \"Blade Runner\", \"year\": \"\"} # E?: Incorrect type for year\n","source":"typing_tests","origin":"conformance/tests/typeddicts_alt_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_14.py","code":"\"\"\"\nTests the class syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import Generic, TypeVar, TypedDict\nimport sys\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n # > String literal forward references are valid in the value types.\n director: \"Person\"\n\n\nclass Person(TypedDict):\n name: str\n age: int\n\n\n# > Methods are not allowed, since the runtime type of a TypedDict object\n# > will always be just dict (it is never a subclass of dict).\nclass BadTypedDict1(TypedDict):\n name: str\n\n # Methods are not allowed, so this should generate an error.\n def method1(self): # E\n pass\n\n # Methods are not allowed, so this should generate an error.\n @classmethod # E[method2]\n def method2(cls): # E[method2]\n pass\n\n # Methods are not allowed, so this should generate an error.\n @staticmethod # E[method3]\n def method3(): # E[method3]\n pass\n\n\nclass CustomMeta(type):\n pass\n\n\n# > Specifying a custom metaclass is not allowed.\nclass BadTypedDict2(TypedDict, metaclass=CustomMeta): # E\n name: str\n\n\n# This should generate an error because \"other\" is not an allowed keyword argument.\nclass BadTypedDict3(TypedDict, other=True): # E\n name: str\n\n# > `if` conditions that the type checker is able to\n# > statically evaluate are also permitted (e.g. `if sys.version_info > (3, 14)`),\n# > in order to specify items that exist only under the given conditions.\nclass ConditionalField(TypedDict):\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nConditionalField(x=1, y=2)\nConditionalField(x=1, y=2, z=3) # E\n\n\n# > TypedDicts may be made generic by adding Generic[T] among the bases.\nT = TypeVar(\"T\")\n\n\nclass GenericTypedDict(TypedDict, Generic[T]):\n name: str\n value: T\n\n\n# > An empty TypedDict can be created by only including pass in the\n# > body (if there is a docstring, pass can be omitted):\nclass EmptyDict1(TypedDict):\n pass\n\n\nclass EmptyDict2(TypedDict):\n \"\"\"Docstring\"\"\"\n\n\nclass MovieTotal(TypedDict, total=True):\n name: str\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n","source":"typing_tests","origin":"conformance/tests/typeddicts_class_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_15.py","code":"\"\"\"\nTests inheritance rules for TypedDict classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclass BookBasedMovie(Movie):\n based_on: str\n\nclass BookBasedMovieAlso(TypedDict):\n name: str\n year: int\n based_on: str\n\nb1: BookBasedMovie = {\"name\": \"Little Women\", \"year\": 2019, \"based_on\": \"Little Women\"}\n\nb2: BookBasedMovieAlso = b1\n\n\nclass X(TypedDict):\n x: int\n\nclass Y(TypedDict):\n y: str\n\nclass XYZ(X, Y):\n z: bool\n\nx1 = XYZ(x=1, y=\"\", z=True)\n\n# > A TypedDict cannot inherit from both a TypedDict type and a\n# > non-TypedDict base class other than Generic.\n\nclass NonTypedDict:\n pass\n\nclass BadTypedDict(TypedDict, NonTypedDict): # E\n pass\n\n\n# > Changing a field type of a parent TypedDict class in a subclass is\n# > not allowed.\n\nclass X1(TypedDict):\n x: str\n\nclass Y1(X1): # E[Y1]\n x: int # E[Y1]: cannot overwrite TypedDict field \"x\"\n\n\n# > Multiple inheritance does not allow conflict types for the same name field:\nclass X2(TypedDict):\n x: int\n\nclass Y2(TypedDict):\n x: str\n\nclass XYZ2(X2, Y2): # E: cannot overwrite TypedDict field \"x\" while merging\n xyz: bool\n","source":"typing_tests","origin":"conformance/tests/typeddicts_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_16.py","code":"\"\"\"\nTests operations provided by a TypedDict object.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#supported-and-unsupported-operations\n\n\nfrom typing import TypedDict, assert_type\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie\n\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982}\nmovie[\"name\"] = \"Other\"\nmovie[\"year\"] = 1981\n\nmovie[\"name\"] = 1982 # E: wrong type\nmovie[\"year\"] = \"\" # E: wrong type\nmovie[\"other\"] = \"\" # E: unknown key added\n\nprint(movie[\"other\"]) # E: unknown key referenced\n\nmovie = {\"name\": \"Blade Runner\"} # E: year is missing\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982.1} # E: year is wrong type\n\n# > The use of a key that is not known to exist should be reported as an error.\nmovie = {\"name\": \"\", \"year\": 1900, \"other\": 2} # E: extra key\n\n\ndef func1(variable_key: str):\n # > A key that is not a literal should generally be rejected.\n movie: Movie = {variable_key: \"\", \"year\": 1900} # E: variable key\n\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"name\")\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"other\") # E?\n\n\nmovie.clear() # E: clear not allowed\n\ndel movie[\"name\"] # E: del not allowed for required key\n\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n year: int\n\n\nmovie_optional: MovieOptional = {}\n\nassert_type(movie_optional.get(\"name\"), str | None)\n\nmovie_optional.clear() # E: clear not allowed\n\ndel movie_optional[\"name\"]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_operations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_17.py","code":"\"\"\"\nTests the type consistency rules for TypedDict objects.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#type-consistency\n\nfrom typing import Any, Literal, Mapping, TypedDict\n\n\nclass A1(TypedDict):\n x: int | None\n\n\nclass B1(TypedDict):\n x: int\n\n\nb1: B1 = {\"x\": 0}\n\n# > Value types behave invariantly.\na1: A1 = b1 # E: 'B1' not compatible with 'A1'\n\n# > any TypedDict type is consistent with Mapping[str, object]\nv1: Mapping[str, object] = b1\n\n# > A TypedDict type with a required key is not consistent with a TypedDict\n# > type where the same key is a non-required key.\n\nclass A2(TypedDict, total=False):\n x: int\n\n\nclass B2(TypedDict):\n x: int\n\n\nb2: B2 = {\"x\": 0}\na2: A2 = b2 # E: 'B2' not compatible with 'A2'\n\n\n# > A TypedDict type A is consistent with TypedDict B if A is structurally\n# > compatible with B. This is true if and only if both of these conditions\n# > are satisfied:\n# > 1. For each key in B, A has the corresponding key and the corresponding\n# > value type in A is consistent with the value type in B. For each key in B,\n# > the value type in B is also consistent with the corresponding value type\n# > in A.\n# > 2. For each required key in B, the corresponding key is required in A. For\n# > each non-required key in B, the corresponding key is not required in A.\n\n\nclass A3(TypedDict):\n x: int\n\n\nclass B3(TypedDict):\n x: int\n y: int\n\n\nb3: B3 = {\"x\": 0, \"y\": 0}\na3: A3 = b3\n\na3 = {\"x\": 0}\nb3 = a3 # E\n\n\n# This should generate an error because it's a literal assignment.\na3_1: A3 = {\"x\": 0, \"y\": 0} # E\n\n# This should not generate an error.\na3_2 = b3\n\n# > A TypedDict isn’t consistent with any Dict[...] type.\n\nd1: dict[str, int] = b3 # E\nd2: dict[str, object] = b3 # E\nd3: dict[Any, Any] = b3 # E\n\n# > A TypedDict with all int values is not consistent with Mapping[str, int].\n\nm1: Mapping[str, int] = b3 # E\nm2: Mapping[str, object] = b3 # OK\nm3: Mapping[str, Any] = b3 # OK\n\n\n# Test \"get\" method.\nUserType1 = TypedDict(\"UserType1\", {\"name\": str, \"age\": int}, total=False)\nuser1: UserType1 = {\"name\": \"Bob\", \"age\": 40}\n\nname1: str = user1.get(\"name\", \"n/a\")\nage1: int = user1.get(\"age\", 42)\n\nUserType2 = TypedDict(\"UserType2\", {\"name\": str, \"age\": int})\nuser2: UserType2 = {\"name\": \"Bob\", \"age\": 40}\n\nname2: str | None = user2.get(\"name\")\n\n# The spec does not say whether type checkers should adjust the return type of `.get()`\n# to exclude `None` if it is known that the key exists. Either option is acceptable.\nname3: str = user2.get(\"name\") # E?\n\nage2: int = user2.get(\"age\", 42)\n\nage3: int | str = user2.get(\"age\", \"42\")\n\nage4: int = user2.get(\"age\", \"42\") # E?\n\n# Test nested TypedDicts.\nclass Inner1(TypedDict):\n inner_key: str\n\n\nclass Inner2(TypedDict):\n inner_key: Inner1\n\n\nclass Outer1(TypedDict):\n outer_key: Inner2\n\n\no1: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": \"hi\"}}}\n\n# This should generate an error because the inner-most value\n# should be a string.\no2: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": 1}}} # E\n\n\nclass Inner3(TypedDict):\n x: int\n\n\nclass Inner4(TypedDict):\n x: int\n\n\nclass Outer2(TypedDict):\n y: str\n z: Literal[\"\"] | Inner3\n\n\nclass Outer3(TypedDict):\n y: str\n z: Literal[\"\"] | Inner4\n\n\ndef func1(td: Outer3):\n ...\n\n\no3: Outer2 = {\"y\": \"\", \"z\": {\"x\": 0}}\no4: Outer3 = o3\n","source":"typing_tests","origin":"conformance/tests/typeddicts_type_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_18.py","code":"\"\"\"\nTests for basic usage of TypedDict.\n\"\"\"\n\nfrom typing import TypeVar, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982}\n\n\ndef record_movie(movie: Movie) -> None:\n ...\n\n\nrecord_movie({\"name\": \"Blade Runner\", \"year\": 1982})\n\n\nmovie[\"director\"] = \"Ridley Scott\" # E: invalid key 'director'\nmovie[\"year\"] = \"1982\" # E: invalid value type (\"int\" expected)\n\n# The code below should be rejected, since 'title' is not a valid key,\n# and the 'name' key is missing:\nmovie2: Movie = {\"title\": \"Blade Runner\", \"year\": 1982} # E\n\nm = Movie(name='Blade Runner', year=1982)\n\n\n# > TypedDict type objects cannot be used in isinstance() tests such as\n# > isinstance(d, Movie).\nif isinstance(movie, Movie): # E\n pass\n\n\n# TypedDict should not be allowed as a bound for a TypeVar.\nT = TypeVar(\"T\", bound=TypedDict) # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_11.py","code":"\"\"\"\nTests for the use of TypeVarTuple with \"*args\" parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#args-as-a-type-variable-tuple\n\n# > If *args is annotated as a type variable tuple, the types of the individual\n# > arguments become the types in the type variable tuple.\n\nfrom typing import TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef args_to_tuple(*args: *Ts) -> tuple[*Ts]:\n raise NotImplementedError\n\n\nclass Env:\n ...\n\n\ndef exec_le(path: str, *args: *tuple[*Ts, Env], env: Env | None = None) -> tuple[*Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(x: int, y: str):\n assert_type(args_to_tuple(x, y), tuple[int, str])\n\n assert_type(exec_le(\"\", Env()), tuple[()]) # OK\n assert_type(exec_le(y, x, y, Env()), tuple[int, str]) # OK\n exec_le(\"\", 0, \"\") # E\n exec_le(\"\", 0, \"\", env=Env()) # E\n\n\n# > Using an unpacked unbounded tuple is equivalent to the\n# > PEP 484#arbitrary-argument-lists-and-default-argument-values behavior of\n# > *args: int, which accepts zero or more values of type int.\n\n\ndef func1(*args: *tuple[int, ...]) -> None:\n ...\n\n\nfunc1() # OK\nfunc1(1, 2, 3, 4, 5) # OK\nfunc1(1, \"2\", 3) # E\n\n\ndef func2(*args: *tuple[int, *tuple[str, ...], str]) -> None:\n ...\n\n\nfunc2(1, \"\") # OK\nfunc2(1, \"\", \"\", \"\", \"\") # OK\nfunc2(1, 1, \"\") # E\nfunc2(1) # E\nfunc2(\"\") # E\n\n\ndef func3(*args: *tuple[int, str]) -> None:\n ...\n\n\nfunc3(1, \"hello\") # OK\nfunc3(1) # E\n\n\ndef func4(*args: tuple[*Ts]):\n ...\n\n\nfunc4((0,), (1,)) # OK\nfunc4((0,), (1, 2)) # E (length mismatch)\nfunc4((0,), (\"1\",)) # OK\n\n\n# This is a syntax error, so leave it commented out.\n# def func5(**kwargs: *Ts): # E\n# ...\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_12.py","code":"\"\"\"\nTests the use of TypeVarTuple within a Callable.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variable-tuples-with-callable\n\n# > Type variable tuples can also be used in the arguments section of a Callable.\n\n\nfrom typing import Callable, TypeVar, TypeVarTuple, assert_type\n\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Process:\n def __init__(self, target: Callable[[*Ts], None], args: tuple[*Ts]) -> None:\n ...\n\n\ndef func1(arg1: int, arg2: str) -> None:\n ...\n\n\nProcess(target=func1, args=(0, \"\")) # OK\nProcess(target=func1, args=(\"\", 0)) # E\n\n\ndef func2(f: Callable[[int, *Ts, T], tuple[T, *Ts]]) -> tuple[*Ts, T]:\n raise NotImplementedError\n\n\ndef callback1(a: int, b: str, c: int, d: complex) -> tuple[complex, str, int]:\n raise NotImplementedError\n\n\ndef callback2(a: int, d: str) -> tuple[str]:\n raise NotImplementedError\n\n\nassert_type(func2(callback1), tuple[str, int, complex])\nassert_type(func2(callback2), tuple[str])\n\n\ndef func3(*args: *tuple[int, *Ts, T]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(a: int, b: str, c: float, d: complex):\n assert_type(func3(a, b, c, d), tuple[complex, str, float])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_callable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_13.py","code":"\"\"\"\nTests type concatenation using TypeVarTuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-concatenation\n\n# > Type variable tuples don’t have to be alone; normal types can be prefixed and/or suffixed.\n\nfrom typing import Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nShape = TypeVarTuple(\"Shape\")\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef add_batch_axis(x: Array[*Shape]) -> Array[Batch, *Shape]:\n raise NotImplementedError\n\n\ndef del_batch_axis(x: Array[Batch, *Shape]) -> Array[*Shape]:\n raise NotImplementedError\n\n\ndef add_batch_channels(x: Array[*Shape]) -> Array[Batch, *Shape, Channels]:\n raise NotImplementedError\n\n\ndef func1(a: Array[Height, Width]):\n b = add_batch_axis(a) # OK\n assert_type(b, Array[Batch, Height, Width])\n c = del_batch_axis(b) # OK\n assert_type(c, Array[Height, Width])\n d = add_batch_channels(a) # OK\n assert_type(d, Array[Batch, Height, Width, Channels])\n\n\ndef prefix_tuple(x: T, y: tuple[*Ts]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef call_prefix_tuple(x: int, y: bool, z: str):\n result = prefix_tuple(x=x, y=(y, z))\n assert_type(result, tuple[int, bool, str])\n\n\ndef move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n return (*tup[1:], tup[0])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_concat.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_14.py","code":"\"\"\"\nTests the use of TypeVarTuple in function overloads.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#overloads-for-accessing-individual-types\n\nfrom typing import Any, Generic, TypeVar, TypeVarTuple, assert_type, overload\n\n\nShape = TypeVarTuple(\"Shape\")\nAxis1 = TypeVar(\"Axis1\")\nAxis2 = TypeVar(\"Axis2\")\nAxis3 = TypeVar(\"Axis3\")\n\n\nclass Array(Generic[*Shape]):\n @overload\n def transpose(self: \"Array[Axis1, Axis2]\") -> \"Array[Axis2, Axis1]\":\n ...\n\n @overload\n def transpose(self: \"Array[Axis1, Axis2, Axis3]\") -> \"Array[Axis3, Axis2, Axis1]\":\n ...\n\n def transpose(self) -> Any:\n raise NotImplementedError\n\n\ndef func1(a: Array[Axis1, Axis2], b: Array[Axis1, Axis2, Axis3]):\n assert_type(a.transpose(), Array[Axis2, Axis1])\n assert_type(b.transpose(), Array[Axis3, Axis2, Axis1])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_overloads.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_15.py","code":"\"\"\"\nTests the handling of a TypeVarTuple specialization.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#behaviour-when-type-parameters-are-not-specified\n\nfrom typing import Any, Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nTime = NewType(\"Time\", int)\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef takes_any_array1(arr: Array):\n ...\n\n\ndef takes_any_array2(arr: Array[*tuple[Any, ...]]):\n ...\n\n\ndef func1(x: Array[Height, Width]):\n takes_any_array1(x) # OK\n takes_any_array2(x) # OK\n\n\ndef func2(y: Array[Time, Height, Width]):\n takes_any_array1(y) # OK\n takes_any_array2(y) # OK\n\n\n# > Generic aliases can be created using a type variable tuple in a similar\n# > way to regular type variables.\n\nIntTuple = tuple[int, *Ts]\nNamedArray = tuple[str, Array[*Ts]]\n\n\ndef func3(a: IntTuple[float, bool], b: NamedArray[Height]):\n assert_type(a, tuple[int, float, bool])\n assert_type(b, tuple[str, Array[Height]])\n\n\ndef func4(a: IntTuple[()], b: NamedArray[()]):\n assert_type(a, tuple[int])\n assert_type(b, tuple[str, Array[()]])\n\n\nShape = TypeVarTuple(\"Shape\")\nDType = TypeVar(\"DType\")\n\n\nclass Array2(Generic[DType, *Shape]):\n ...\n\n\nFloatArray = Array2[float, *Shape]\nArray1D = Array2[DType, Any]\n\n\ndef func5_0(a: Array1D, b: Array1D[int]):\n assert_type(a, Array2[Any, Any])\n assert_type(b, Array2[int, Any])\n\n\ndef takes_float_array_of_any_shape(x: FloatArray):\n ...\n\n\ndef func5_1(x: FloatArray[Height, Width]):\n takes_float_array_of_any_shape(x) # OK\n\n\ndef takes_float_array_with_specific_shape(y: FloatArray[Height, Width]):\n ...\n\n\ndef func5_2(x: FloatArray):\n takes_float_array_with_specific_shape(x) # OK\n\n\nT = TypeVar(\"T\")\nVariadicTuple = tuple[T, *Ts]\n\n\ndef func6(a: VariadicTuple[str, int], b: VariadicTuple[float], c: VariadicTuple):\n assert_type(a, tuple[str, int])\n assert_type(b, tuple[float])\n assert_type(c, tuple[Any, *tuple[Any, ...]])\n\n\nTs1 = TypeVarTuple(\"Ts1\")\nTs2 = TypeVarTuple(\"Ts2\")\n\nIntTupleVar = tuple[int, *Ts1] # OK\nIntFloatTupleVar = IntTupleVar[float, *Ts2] # OK\nIntFloatsTupleVar = IntTupleVar[*tuple[float, ...]] # OK\n\n\nIntTupleGeneric = tuple[int, T]\n\nIntTupleGeneric[str] # OK\nIntTupleGeneric[*Ts] # E\nIntTupleGeneric[*tuple[float, ...]] # E\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nTA1 = tuple[*Ts, T1, T2] # OK\nTA2 = tuple[T1, T2, *Ts] # OK\nTA3 = tuple[T1, *Ts, T2, T3] # OK\nTA4 = tuple[T1, T2, *tuple[int, ...]] # OK\nTA5 = tuple[T1, *Ts, T2, *Ts] # E\nTA6 = tuple[T1, *Ts, T2, *tuple[int, ...]] # E\n\n\nTA7 = tuple[*Ts, T1, T2]\n\nv1: TA7[int] # E: requires at least two type arguments\n\n\ndef func7(a: TA7[*Ts, T1, T2]) -> tuple[tuple[*Ts], T1, T2]:\n raise NotImplementedError\n\n\ndef func8(a: TA7[str, bool], b: TA7[str, bool, float], c: TA7[str, bool, float, int]):\n assert_type(func7(a), tuple[tuple[()], str, bool])\n assert_type(func7(b), tuple[tuple[str], bool, float])\n assert_type(func7(c), tuple[tuple[str, bool], float, int])\n\n\nTA8 = tuple[T1, *Ts, T2, T3]\n\n\ndef func9(a: TA8[T1, *Ts, T2, T3]) -> tuple[tuple[*Ts], T1, T2, T3]:\n raise NotImplementedError\n\n\ndef func10(a: TA8[str, bool, float], b: TA8[str, bool, float, int]):\n assert_type(func9(a), tuple[tuple[()], str, bool, float])\n assert_type(func9(b), tuple[tuple[bool], str, float, int])\n\n\nTA9 = tuple[*Ts, T1]\nTA10 = TA9[*tuple[int, ...]] # OK\n\n\ndef func11(a: TA10, b: TA9[*tuple[int, ...], str], c: TA9[*tuple[int, ...], str]):\n assert_type(a, tuple[*tuple[int, ...], int])\n assert_type(b, tuple[*tuple[int, ...], str])\n assert_type(c, tuple[*tuple[int, ...], str])\n\n\nTA11 = tuple[T, *Ts1]\nTA12 = TA11[*Ts2] # E\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_16.py","code":"\"\"\"\nTests unpack operations for TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#unpacking-tuple-types\n\nfrom typing import Any, Generic, NewType, TypeVarTuple\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nTs = TypeVarTuple(\"Ts\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef process_batch_channels(x: Array[Batch, *tuple[Any, ...], Channels]) -> None:\n ...\n\n\ndef func3(\n x: Array[Batch, Height, Width, Channels], y: Array[Batch, Channels], z: Array[Batch]\n):\n process_batch_channels(x) # OK\n process_batch_channels(y) # OK\n process_batch_channels(z) # E\n\n\nShape = TypeVarTuple(\"Shape\")\n\n\ndef expect_variadic_array(x: Array[Batch, *Shape]) -> None:\n ...\n\n\ndef expect_precise_array(x: Array[Batch, Height, Width, Channels]) -> None:\n ...\n\n\ndef func4(y: Array[*tuple[Any, ...]]):\n expect_variadic_array(y) # OK\n expect_precise_array(y) # OK\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_unpack.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_17.py","code":"\"\"\"\nTests the handling of unpacked tuples embedded within other tuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#unpacked-tuple-form\n\n# > An unpacked form of ``tuple`` (using an unpack operator ``*``)\n# > can be used within a tuple type argument list\n\n# > Unpacking a concrete tuple type is analogous to unpacking a tuple of values at runtime.\n\n\nfrom typing import TypeVarTuple, Unpack, assert_type\n\n\ndef func1(x: tuple[int, *tuple[bool, bool], str]):\n assert_type(x, tuple[int, bool, bool, str])\n assert_type(x, tuple[*tuple[int, bool], bool, str])\n assert_type(x, tuple[int, bool, *tuple[bool, str]])\n\n\n# > Unpacking an unbounded tuple preserves the unbounded tuple as it is.\n\n\ndef func2(x: tuple[int, *tuple[bool, ...], str]):\n assert_type(x, tuple[int, *tuple[bool, ...], str])\n\n\n# > For example, tuple[int, *tuple[str]] is equivalent to tuple[int, str].\n\nu1: tuple[*tuple[int], *tuple[int]] = (int(1), int(1)) # OK\nassert_type(u1, tuple[int, int])\nu2: tuple[*tuple[int, ...], *tuple[int]] # OK\n\n\n# > Only one unbounded tuple can be used within another tuple:\n\nt1: tuple[*tuple[str], *tuple[str]] # OK\nt2: tuple[*tuple[str, *tuple[str, ...]]] # OK\nt3: tuple[*tuple[str, ...], *tuple[int, ...]] # E\nt4: tuple[*tuple[str, *tuple[str, ...]], *tuple[int, ...]] # E\n\n\n# > An unpacked TypeVarTuple counts as an unbounded tuple in the context of this rule\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef func3(t: tuple[*Ts]):\n t5: tuple[*tuple[str], *Ts] # OK\n t6: tuple[*tuple[str, ...], *Ts] # E\n\n\n# > The ``*`` syntax requires Python 3.11 or newer. For older versions of Python,\n# > the ``typing.Unpack`` special form can be used:\n\nt11: tuple[Unpack[tuple[str]], Unpack[tuple[str]]] # OK\nt12: tuple[Unpack[tuple[str, Unpack[tuple[str, ...]]]]] # OK\nt13: tuple[Unpack[tuple[str, ...]], Unpack[tuple[int, ...]]] # E\nt14: tuple[ # E[t14]\n Unpack[tuple[str, Unpack[tuple[str, ...]]]], Unpack[tuple[int, ...]] # E[t14]\n]\n","source":"typing_tests","origin":"conformance/tests/tuples_unpacked.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n an = g.__anext__()\n try:\n while True:\n try:\n an.__next__()\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n break\n else:\n res.append('EMPTY StopIteration')\n break\n except StopAsyncIteration:\n raise\n except Exception as ex:\n res.append(str(type(ex)))\n break\n except StopAsyncIteration:\n res.append('STOP')\n break\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_exception_11(self):\n def sync_gen():\n yield 10\n yield 20\n\n def sync_gen_wrapper():\n yield 1\n sg = sync_gen()\n sg.send(None)\n try:\n sg.throw(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n async def async_gen():\n yield 10\n yield 20\n\n async def async_gen_wrapper():\n yield 1\n asg = async_gen()\n await asg.asend(None)\n try:\n await asg.athrow(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n\n self.assertTrue(inspect.isawaitable(g.aclose()))\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n asyncio.set_event_loop_policy(None)\n\n def check_async_iterator_anext(self, ait_class):\n with self.subTest(anext=\"pure-Python\"):\n self._check_async_iterator_anext(ait_class, py_anext)\n with self.subTest(anext=\"builtin\"):\n self._check_async_iterator_anext(ait_class, anext)\n\n def _check_async_iterator_anext(self, ait_class, anext):\n g = ait_class()\n async def consume():\n results = []\n results.append(await anext(g))\n results.append(await anext(g))\n results.append(await anext(g, 'buckle my shoe'))\n return results\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2, 'buckle my shoe'])\n with self.assertRaises(StopAsyncIteration):\n self.loop.run_until_complete(consume())\n\n async def test_2():\n g1 = ait_class()\n self.assertEqual(await anext(g1), 1)\n self.assertEqual(await anext(g1), 2)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n\n g2 = ait_class()\n self.assertEqual(await anext(g2, \"default\"), 1)\n self.assertEqual(await anext(g2, \"default\"), 2)\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n\n return \"completed\"\n\n result = self.loop.run_until_complete(test_2())\n self.assertEqual(result, \"completed\")\n\n def test_send():\n p = ait_class()\n obj = anext(p, \"completed\")\n with self.assertRaises(StopIteration):\n with contextlib.closing(obj.__await__()) as g:\n g.send(None)\n\n test_send()\n\n async def test_throw():\n p = ait_class()\n obj = anext(p, \"completed\")\n self.assertRaises(SyntaxError, obj.throw, SyntaxError)\n return \"completed\"\n\n result = self.loop.run_until_complete(test_throw())\n self.assertEqual(result, \"completed\")\n\n def test_async_generator_anext(self):\n async def agen():\n yield 1\n yield 2\n self.check_async_iterator_anext(agen)\n\n def test_python_async_iterator_anext(self):\n class MyAsyncIter:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n async def __anext__(self):\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIter)\n\n def test_python_async_iterator_types_coroutine_anext(self):\n import types\n class MyAsyncIterWithTypesCoro:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n @types.coroutine\n def __anext__(self):\n if False:\n yield \"this is a generator-based coroutine\"\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIterWithTypesCoro)\n\n def test_async_gen_aiter(self):\n async def gen():\n yield 1\n yield 2\n g = gen()\n async def consume():\n return [i async for i in aiter(g)]\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_aiter_class(self):\n results = []\n class Gen:\n async def __aiter__(self):\n yield 1\n yield 2\n g = Gen()\n async def consume():\n ait = aiter(g)\n while True:\n try:\n results.append(await anext(ait))\n except StopAsyncIteration:\n break\n self.loop.run_until_complete(consume())\n self.assertEqual(results, [1, 2])\n\n def test_aiter_idempotent(self):\n async def gen():\n yield 1\n applied_once = aiter(gen())\n applied_twice = aiter(applied_once)\n self.assertIs(applied_once, applied_twice)\n\n def test_anext_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await anext()\n async def call_with_too_many_args():\n await anext(gen(), 1, 3)\n async def call_with_wrong_type_args():\n await anext(1, gen())\n async def call_with_kwarg():\n await anext(aiterator=gen())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_kwarg())\n\n def test_anext_bad_await(self):\n async def bad_awaitable():\n class BadAwaitable:\n def __await__(self):\n return 42\n class MyAsyncIter:\n def __aiter__(self):\n return self\n def __anext__(self):\n return BadAwaitable()\n regex = r\"__await__.*iterator\"\n awaitable = anext(MyAsyncIter(), \"default\")\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n awaitable = anext(MyAsyncIter())\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(bad_awaitable())\n self.assertEqual(result, \"completed\")\n\n async def check_anext_returning_iterator(self, aiter_class):\n awaitable = anext(aiter_class(), \"default\")\n with self.assertRaises(TypeError):\n await awaitable\n awaitable = anext(aiter_class())\n with self.assertRaises(TypeError):\n await awaitable\n return \"completed\"\n\n def test_anext_return_iterator(self):\n class WithIterAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return iter(\"abc\")\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithIterAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_return_generator(self):\n class WithGenAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n yield\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithGenAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_await_raises(self):\n class RaisingAwaitable:\n def __await__(self):\n raise ZeroDivisionError()\n yield\n class WithRaisingAwaitableAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return RaisingAwaitable()\n async def do_test():\n awaitable = anext(WithRaisingAwaitableAnext())\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n awaitable = anext(WithRaisingAwaitableAnext(), \"default\")\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(do_test())\n self.assertEqual(result, \"completed\")\n\n def test_anext_iter(self):\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyError(Exception):\n pass\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n def test1(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError, MyError(), None), 2)\n try:\n g.send(None)\n except StopIteration as e:\n err = e\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(err.value, \"default\")\n\n def test2(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError, MyError(), None), 2)\n with self.assertRaises(MyError):\n g.throw(MyError, MyError(), None)\n\n def test3(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n g.close()\n with self.assertRaisesRegex(RuntimeError, 'cannot reuse'):\n self.assertEqual(g.send(None), 1)\n\n def test4(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n self.assertEqual(g.throw(MyError, MyError(), None), 20)\n with self.assertRaisesRegex(MyError, 'val'):\n g.throw(MyError, MyError('val'), None)\n\n def test5(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n return\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n with self.assertRaisesRegex(StopIteration, 'default'):\n g.throw(MyError, MyError(), None)\n\n def test6(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n await _async_yield(1)\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n with self.assertRaises(MyError):\n g.throw(MyError, MyError(), None)\n\n def run_test(test):\n with self.subTest('pure-Python anext()'):\n test(py_anext)\n with self.subTest('builtin anext()'):\n test(anext)\n\n run_test(test1)\n run_test(test2)\n run_test(test3)\n run_test(test4)\n run_test(test5)\n run_test(test6)\n\n def test_aiter_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await aiter()\n async def call_with_too_many_args():\n await aiter(gen(), 1)\n async def call_with_wrong_type_arg():\n await aiter(1)\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_arg())\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n await asyncio.sleep(0.01)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n gc_collect() # For PyPy or other GCs.\n\n await asyncio.sleep(0.1)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_aclose_12(self):\n DONE = 0\n\n async def target():\n await asyncio.sleep(0.01)\n 1 / 0\n\n async def foo():\n nonlocal DONE\n task = asyncio.create_task(target())\n try:\n yield 1\n finally:\n try:\n await task\n except ZeroDivisionError:\n DONE = 1\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout)\n yield 1\n finally:\n await asyncio.sleep(0)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1))\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t1)\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t2)\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(finalized, 2)\n\n def test_async_gen_asyncio_shutdown_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n self.assertEqual(messages, [])\n\n def test_async_gen_asyncio_shutdown_exception_01(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n message, = messages\n self.assertEqual(message['asyncgen'], it)\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('an error occurred during closing of asynchronous generator',\n message['message'])\n\n def test_async_gen_asyncio_shutdown_exception_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n gc_collect()\n\n asyncio.run(main())\n\n message, = messages\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('unhandled exception during asyncio.run() shutdown',\n message['message'])\n\n def test_async_gen_expression_01(self):\n async def arange(n):\n for i in range(n):\n await asyncio.sleep(0.01)\n yield i\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 async for i in arange(n))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(10)])\n\n def test_async_gen_expression_02(self):\n async def wrap(n):\n await asyncio.sleep(0.01)\n return n\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 for i in range(n) if await wrap(i))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(1, 10)])\n\n def test_asyncgen_nonstarted_hooks_are_cancellable(self):\n # See https://bugs.python.org/issue38013\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n\n asyncio.run(main())\n\n self.assertEqual([], messages)\n\n def test_async_gen_await_same_anext_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.__anext__()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"\n ):\n await nxt\n\n await it.aclose() # prevent unfinished iterator warning\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_await_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.aclose()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n await nxt\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_twice_with_different_coros(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n await it.aclose()\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_after_exhaustion(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n async for _ in it:\n pass\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_compatible_with_get_stack(self):\n async def async_generator():\n yield object()\n\n async def run():\n ag = async_generator()\n asyncio.create_task(ag.aclose())\n tasks = asyncio.all_tasks()\n for task in tasks:\n # No AttributeError raised\n task.get_stack()\n\n self.loop.run_until_complete(run())\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"breakpoint","pep":"553","introduced_in":"3.7","form":"modern","file":"breakpoint/modern_01.py","code":"import ast\nimport asyncio\nimport builtins\nimport collections\nimport decimal\nimport fractions\nimport gc\nimport io\nimport locale\nimport os\nimport pickle\nimport platform\nimport random\nimport re\nimport sys\nimport traceback\nimport types\nimport unittest\nimport warnings\nfrom contextlib import ExitStack\nfrom functools import partial\nfrom inspect import CO_COROUTINE\nfrom itertools import product\nfrom textwrap import dedent\nfrom types import AsyncGeneratorType, FunctionType, CellType\nfrom operator import neg\nfrom test import support\nfrom test.support import (swap_attr, maybe_get_event_loop_policy)\nfrom test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink)\nfrom test.support.script_helper import assert_python_ok\nfrom test.support.warnings_helper import check_warnings\nfrom unittest.mock import MagicMock, patch\n\n\nclass TestBreakpoint(unittest.TestCase):\n def setUp(self):\n # These tests require a clean slate environment. For example, if the\n # test suite is run with $PYTHONBREAKPOINT set to something else, it\n # will mess up these tests. Similarly for sys.breakpointhook.\n # Cleaning the slate here means you can't use breakpoint() to debug\n # these tests, but I think that's okay. Just use pdb.set_trace() if\n # you must.\n self.resources = ExitStack()\n self.addCleanup(self.resources.close)\n self.env = self.resources.enter_context(EnvironmentVarGuard())\n del self.env['PYTHONBREAKPOINT']\n self.resources.enter_context(\n swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))\n\n def test_breakpoint(self):\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once()\n\n def test_breakpoint_with_breakpointhook_set(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_breakpointhook_reset(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n # Reset the hook and it will not be called again.\n sys.breakpointhook = sys.__breakpointhook__\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_args_and_keywords(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint(1, 2, 3, four=4, five=5)\n my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)\n\n def test_breakpoint_with_passthru_error(self):\n def my_breakpointhook():\n pass\n sys.breakpointhook = my_breakpointhook\n self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_builtin(self):\n self.env['PYTHONBREAKPOINT'] = 'int'\n with patch('builtins.int') as mock:\n breakpoint('7')\n mock.assert_called_once_with('7')\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_other(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_noop_0(self):\n self.env['PYTHONBREAKPOINT'] = '0'\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_not_called()\n\n def test_envar_good_path_empty_string(self):\n # PYTHONBREAKPOINT='' is the same as it not being set.\n self.env['PYTHONBREAKPOINT'] = ''\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_unimportable(self):\n for envar in (\n '.', '..', '.foo', 'foo.', '.int', 'int.',\n '.foo.bar', '..foo.bar', '/./',\n 'nosuchbuiltin',\n 'nosuchmodule.nosuchcallable',\n ):\n with self.subTest(envar=envar):\n self.env['PYTHONBREAKPOINT'] = envar\n mock = self.resources.enter_context(patch('pdb.set_trace'))\n w = self.resources.enter_context(check_warnings(quiet=True))\n breakpoint()\n self.assertEqual(\n str(w.message),\n f'Ignoring unimportable $PYTHONBREAKPOINT: \"{envar}\"')\n self.assertEqual(w.category, RuntimeWarning)\n mock.assert_not_called()\n\n def test_envar_ignored_when_hook_is_set(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n sys.breakpointhook = int\n breakpoint()\n mock.assert_not_called()\n","source":"cpython_tests","origin":"Lib/test/test_builtin.py::TestBreakpoint","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, ZeroDivisionError)\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(RuntimeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n exc = cm.exception\n self.assertRegex(str(exc), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(exc), r'\\battr\\b')\n self.assertRegex(str(exc), r'\\bDescriptor\\b')\n self.assertIsInstance(exc.__cause__, TypeError)\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_03.py","code":"import concurrent.futures\nimport contextvars\nimport functools\nimport gc\nimport random\nimport time\nimport unittest\nimport weakref\nfrom test.support import threading_helper\n\n\nclass ContextTest(unittest.TestCase):\n def test_context_var_new_1(self):\n with self.assertRaisesRegex(TypeError, 'takes exactly 1'):\n contextvars.ContextVar()\n\n with self.assertRaisesRegex(TypeError, 'must be a str'):\n contextvars.ContextVar(1)\n\n c = contextvars.ContextVar('aaa')\n self.assertEqual(c.name, 'aaa')\n\n with self.assertRaises(AttributeError):\n c.name = 'bbb'\n\n self.assertNotEqual(hash(c), hash('aaa'))\n\n @isolated_context\n def test_context_var_repr_1(self):\n c = contextvars.ContextVar('a')\n self.assertIn('a', repr(c))\n\n c = contextvars.ContextVar('a', default=123)\n self.assertIn('123', repr(c))\n\n lst = []\n c = contextvars.ContextVar('a', default=lst)\n lst.append(c)\n self.assertIn('...', repr(c))\n self.assertIn('...', repr(lst))\n\n t = c.set(1)\n self.assertIn(repr(c), repr(t))\n self.assertNotIn(' used ', repr(t))\n c.reset(t)\n self.assertIn(' used ', repr(t))\n\n def test_context_subclassing_1(self):\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContextVar(contextvars.ContextVar):\n # Potentially we might want ContextVars to be subclassable.\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContext(contextvars.Context):\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyToken(contextvars.Token):\n pass\n\n def test_context_new_1(self):\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1, a=1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(a=1)\n contextvars.Context(**{})\n\n def test_context_typerrors_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx[1]\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n 1 in ctx\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx.get(1)\n\n def test_context_get_context_1(self):\n ctx = contextvars.copy_context()\n self.assertIsInstance(ctx, contextvars.Context)\n\n def test_context_run_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required'):\n ctx.run()\n\n def test_context_run_2(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n kwargs['spam'] = 'foo'\n args += ('bar',)\n return args, kwargs\n\n for f in (func, functools.partial(func)):\n # partial doesn't support FASTCALL\n\n self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))\n self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, a=2),\n (('bar',), {'a': 2, 'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, 11, a=2),\n ((11, 'bar'), {'a': 2, 'spam': 'foo'}))\n\n a = {}\n self.assertEqual(\n ctx.run(f, 11, **a),\n ((11, 'bar'), {'spam': 'foo'}))\n self.assertEqual(a, {})\n\n def test_context_run_3(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2, a=123)\n\n @isolated_context\n def test_context_run_4(self):\n ctx1 = contextvars.Context()\n ctx2 = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func2():\n self.assertIsNone(var.get(None))\n\n def func1():\n self.assertIsNone(var.get(None))\n var.set('spam')\n ctx2.run(func2)\n self.assertEqual(var.get(None), 'spam')\n\n cur = contextvars.copy_context()\n self.assertEqual(len(cur), 1)\n self.assertEqual(cur[var], 'spam')\n return cur\n\n returned_ctx = ctx1.run(func1)\n self.assertEqual(ctx1, returned_ctx)\n self.assertEqual(returned_ctx[var], 'spam')\n self.assertIn(var, returned_ctx)\n\n def test_context_run_5(self):\n ctx = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func():\n self.assertIsNone(var.get(None))\n var.set('spam')\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n\n self.assertIsNone(var.get(None))\n\n def test_context_run_6(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('a', default=0)\n\n def fun():\n self.assertEqual(c.get(), 0)\n self.assertIsNone(ctx.get(c))\n\n c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(ctx.get(c), 42)\n\n ctx.run(fun)\n\n def test_context_run_7(self):\n ctx = contextvars.Context()\n\n def fun():\n with self.assertRaisesRegex(RuntimeError, 'is already entered'):\n ctx.run(fun)\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_1(self):\n c = contextvars.ContextVar('c')\n with self.assertRaises(LookupError):\n c.get()\n\n self.assertIsNone(c.get(None))\n\n t0 = c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n self.assertIs(t0.old_value, t0.MISSING)\n self.assertIs(t0.old_value, contextvars.Token.MISSING)\n self.assertIs(t0.var, c)\n\n t = c.set('spam')\n self.assertEqual(c.get(), 'spam')\n self.assertEqual(c.get(None), 'spam')\n self.assertEqual(t.old_value, 42)\n c.reset(t)\n\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n\n c.set('spam2')\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t)\n self.assertEqual(c.get(), 'spam2')\n\n ctx1 = contextvars.copy_context()\n self.assertIn(c, ctx1)\n\n c.reset(t0)\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t0)\n self.assertIsNone(c.get(None))\n\n self.assertIn(c, ctx1)\n self.assertEqual(ctx1[c], 'spam2')\n self.assertEqual(ctx1.get(c, 'aa'), 'spam2')\n self.assertEqual(len(ctx1), 1)\n self.assertEqual(list(ctx1.items()), [(c, 'spam2')])\n self.assertEqual(list(ctx1.values()), ['spam2'])\n self.assertEqual(list(ctx1.keys()), [c])\n self.assertEqual(list(ctx1), [c])\n\n ctx2 = contextvars.copy_context()\n self.assertNotIn(c, ctx2)\n with self.assertRaises(KeyError):\n ctx2[c]\n self.assertEqual(ctx2.get(c, 'aa'), 'aa')\n self.assertEqual(len(ctx2), 0)\n self.assertEqual(list(ctx2), [])\n\n @isolated_context\n def test_context_getset_2(self):\n v1 = contextvars.ContextVar('v1')\n v2 = contextvars.ContextVar('v2')\n\n t1 = v1.set(42)\n with self.assertRaisesRegex(ValueError, 'by a different'):\n v2.reset(t1)\n\n @isolated_context\n def test_context_getset_3(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n def fun():\n self.assertEqual(c.get(), 42)\n with self.assertRaises(KeyError):\n ctx[c]\n self.assertIsNone(ctx.get(c))\n self.assertEqual(ctx.get(c, 'spam'), 'spam')\n self.assertNotIn(c, ctx)\n self.assertEqual(list(ctx.keys()), [])\n\n t = c.set(1)\n self.assertEqual(list(ctx.keys()), [c])\n self.assertEqual(ctx[c], 1)\n\n c.reset(t)\n self.assertEqual(list(ctx.keys()), [])\n with self.assertRaises(KeyError):\n ctx[c]\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_4(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n tok = ctx.run(c.set, 1)\n\n with self.assertRaisesRegex(ValueError, 'different Context'):\n c.reset(tok)\n\n @isolated_context\n def test_context_getset_5(self):\n c = contextvars.ContextVar('c', default=42)\n c.set([])\n\n def fun():\n c.set([])\n c.get().append(42)\n self.assertEqual(c.get(), [42])\n\n contextvars.copy_context().run(fun)\n self.assertEqual(c.get(), [])\n\n def test_context_copy_1(self):\n ctx1 = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def ctx1_fun():\n c.set(10)\n\n ctx2 = ctx1.copy()\n self.assertEqual(ctx2[c], 10)\n\n c.set(20)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 10)\n\n ctx2.run(ctx2_fun)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 30)\n\n def ctx2_fun():\n self.assertEqual(c.get(), 10)\n c.set(30)\n self.assertEqual(c.get(), 30)\n\n ctx1.run(ctx1_fun)\n\n @isolated_context\n @threading_helper.requires_working_threading()\n def test_context_threads_1(self):\n cvar = contextvars.ContextVar('cvar')\n\n def sub(num):\n for i in range(10):\n cvar.set(num + i)\n time.sleep(random.uniform(0.001, 0.05))\n self.assertEqual(cvar.get(), num + i)\n return num\n\n tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)\n try:\n results = list(tp.map(sub, range(10)))\n finally:\n tp.shutdown()\n self.assertEqual(results, list(range(10)))\n","source":"cpython_tests","origin":"Lib/test/test_context.py::ContextTest","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_17.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFieldNoAnnotation(unittest.TestCase):\n def test_field_without_annotation(self):\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n @dataclass\n class C:\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base(self):\n @dataclass\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base_not_dataclass(self):\n # Same test, but with the base class not a dataclass.\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFieldNoAnnotation","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_18.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDocString(unittest.TestCase):\n def assertDocStrEqual(self, a, b):\n # Because 3.6 and 3.7 differ in how inspect.signature work\n # (see bpo #32108), for the time being just compare them with\n # whitespace stripped.\n self.assertEqual(a.replace(' ', ''), b.replace(' ', ''))\n\n def test_existing_docstring_not_overridden(self):\n @dataclass\n class C:\n \"\"\"Lorem ipsum\"\"\"\n x: int\n\n self.assertEqual(C.__doc__, \"Lorem ipsum\")\n\n def test_docstring_no_fields(self):\n @dataclass\n class C:\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C()\")\n\n def test_docstring_one_field(self):\n @dataclass\n class C:\n x: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int)\")\n\n def test_docstring_two_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int)\")\n\n def test_docstring_three_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n z: str\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int, z:str)\")\n\n def test_docstring_one_field_with_default(self):\n @dataclass\n class C:\n x: int = 3\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int=3)\")\n\n def test_docstring_one_field_with_default_none(self):\n @dataclass\n class C:\n x: Union[int, type(None)] = None\n\n self.assertDocStrEqual(C.__doc__, \"C(x:Optional[int]=None)\")\n\n def test_docstring_list_field(self):\n @dataclass\n class C:\n x: List[int]\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int])\")\n\n def test_docstring_list_field_with_default_factory(self):\n @dataclass\n class C:\n x: List[int] = field(default_factory=list)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int]=)\")\n\n def test_docstring_deque_field(self):\n @dataclass\n class C:\n x: deque\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque)\")\n\n def test_docstring_deque_field_with_default_factory(self):\n @dataclass\n class C:\n x: deque = field(default_factory=deque)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque=)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDocString","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_19.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestInit(unittest.TestCase):\n def test_base_has_init(self):\n class B:\n def __init__(self):\n self.z = 100\n pass\n\n # Make sure that declaring this class doesn't raise an error.\n # The issue is that we can't override __init__ in our class,\n # but it should be okay to add __init__ to us if our base has\n # an __init__.\n @dataclass\n class C(B):\n x: int = 0\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertNotIn('z', vars(c))\n\n # Make sure that if we don't add an init, the base __init__\n # gets called.\n @dataclass(init=False)\n class C(B):\n x: int = 10\n c = C()\n self.assertEqual(c.x, 10)\n self.assertEqual(c.z, 100)\n\n def test_no_init(self):\n @dataclass(init=False)\n class C:\n i: int = 0\n self.assertEqual(C().i, 0)\n\n @dataclass(init=False)\n class C:\n i: int = 2\n def __init__(self):\n self.i = 3\n self.assertEqual(C().i, 3)\n\n def test_overwriting_init(self):\n # If the class has __init__, use it no matter the value of\n # init=.\n\n @dataclass\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(3).x, 6)\n\n @dataclass(init=True)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(4).x, 8)\n\n @dataclass(init=False)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(5).x, 10)\n\n def test_inherit_from_protocol(self):\n # Dataclasses inheriting from protocol should preserve their own `__init__`.\n # See bpo-45081.\n\n class P(Protocol):\n a: int\n\n @dataclass\n class C(P):\n a: int\n\n self.assertEqual(C(5).a, 5)\n\n @dataclass\n class D(P):\n def __init__(self, a):\n self.a = a * 2\n\n self.assertEqual(D(5).a, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestInit","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_20.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestRepr(unittest.TestCase):\n def test_repr(self):\n @dataclass\n class B:\n x: int\n\n @dataclass\n class C(B):\n y: int = 10\n\n o = C(4)\n self.assertEqual(repr(o), 'TestRepr.test_repr..C(x=4, y=10)')\n\n @dataclass\n class D(C):\n x: int = 20\n self.assertEqual(repr(D()), 'TestRepr.test_repr..D(x=20, y=10)')\n\n @dataclass\n class C:\n @dataclass\n class D:\n i: int\n @dataclass\n class E:\n pass\n self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr..C.D(i=0)')\n self.assertEqual(repr(C.E()), 'TestRepr.test_repr..C.E()')\n\n def test_no_repr(self):\n # Test a class with no __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n self.assertIn(f'{__name__}.TestRepr.test_no_repr..C object at',\n repr(C(3)))\n\n # Test a class with a __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'C-class'\n self.assertEqual(repr(C(3)), 'C-class')\n\n def test_overwriting_repr(self):\n # If the class has __repr__, use it no matter the value of\n # repr=.\n\n @dataclass\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=True)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestRepr","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_21.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestEq(unittest.TestCase):\n def test_no_eq(self):\n # Test a class with no __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n self.assertNotEqual(C(0), C(0))\n c = C(3)\n self.assertEqual(c, c)\n\n # Test a class with an __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 10\n self.assertEqual(C(3), 10)\n\n def test_overwriting_eq(self):\n # If the class has __eq__, use it no matter the value of\n # eq=.\n\n @dataclass\n class C:\n x: int\n def __eq__(self, other):\n return other == 3\n self.assertEqual(C(1), 3)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=True)\n class C:\n x: int\n def __eq__(self, other):\n return other == 4\n self.assertEqual(C(1), 4)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 5\n self.assertEqual(C(1), 5)\n self.assertNotEqual(C(1), 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestEq","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_22.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestOrdering(unittest.TestCase):\n def test_functools_total_ordering(self):\n # Test that functools.total_ordering works with this class.\n @total_ordering\n @dataclass\n class C:\n x: int\n def __lt__(self, other):\n # Perform the test \"backward\", just to make\n # sure this is being called.\n return self.x >= other\n\n self.assertLess(C(0), -1)\n self.assertLessEqual(C(0), -1)\n self.assertGreater(C(0), 1)\n self.assertGreaterEqual(C(0), 1)\n\n def test_no_order(self):\n # Test that no ordering functions are added by default.\n @dataclass(order=False)\n class C:\n x: int\n # Make sure no order methods are added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__lt__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n # Test that __lt__ is still called\n @dataclass(order=False)\n class C:\n x: int\n def __lt__(self, other):\n return False\n # Make sure other methods aren't added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n def test_overwriting_order(self):\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __lt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __lt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __le__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __le__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __gt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __gt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __ge__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __ge__(self):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestOrdering","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_23.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestHash(unittest.TestCase):\n def test_unsafe_hash(self):\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n y: str\n self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))\n\n def test_hash_rules(self):\n def non_bool(value):\n # Map to something else that's True, but not a bool.\n if value is None:\n return None\n if value:\n return (3,)\n return 0\n\n def test(case, unsafe_hash, eq, frozen, with_hash, result):\n with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,\n frozen=frozen):\n if result != 'exception':\n if with_hash:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n else:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n pass\n\n # See if the result matches what's expected.\n if result == 'fn':\n # __hash__ contains the function we generated.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNotNone(C.__dict__['__hash__'])\n\n elif result == '':\n # __hash__ is not present in our class.\n if not with_hash:\n self.assertNotIn('__hash__', C.__dict__)\n\n elif result == 'none':\n # __hash__ is set to None.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNone(C.__dict__['__hash__'])\n\n elif result == 'exception':\n # Creating the class should cause an exception.\n # This only happens with with_hash==True.\n assert(with_hash)\n with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n\n else:\n assert False, f'unknown result {result!r}'\n\n # There are 8 cases of:\n # unsafe_hash=True/False\n # eq=True/False\n # frozen=True/False\n # And for each of these, a different result if\n # __hash__ is defined or not.\n for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([\n (False, False, False, '', ''),\n (False, False, True, '', ''),\n (False, True, False, 'none', ''),\n (False, True, True, 'fn', ''),\n (True, False, False, 'fn', 'exception'),\n (True, False, True, 'fn', 'exception'),\n (True, True, False, 'fn', 'exception'),\n (True, True, True, 'fn', 'exception'),\n ], 1):\n test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)\n test(case, unsafe_hash, eq, frozen, True, res_defined_hash)\n\n # Test non-bool truth values, too. This is just to\n # make sure the data-driven table in the decorator\n # handles non-bool values.\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)\n\n\n def test_eq_only(self):\n # If a class defines __eq__, __hash__ is automatically added\n # and set to None. This is normal Python behavior, not\n # related to dataclasses. Make sure we don't interfere with\n # that (see bpo=32546).\n\n @dataclass\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1))\n self.assertNotEqual(C(1), C(4))\n\n # And make sure things work in this case if we specify\n # unsafe_hash=True.\n @dataclass(unsafe_hash=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1.0))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n # And check that the classes __eq__ is being used, despite\n # specifying eq=True.\n @dataclass(unsafe_hash=True, eq=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == 3 and self.i == other.i\n self.assertEqual(C(3), C(3))\n self.assertNotEqual(C(1), C(1))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n def test_0_field_hash(self):\n @dataclass(frozen=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n @dataclass(unsafe_hash=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n def test_1_field_hash(self):\n @dataclass(frozen=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n def test_hash_no_args(self):\n # Test dataclasses with no hash= argument. This exists to\n # make sure that if the @dataclass parameter name is changed\n # or the non-default hashing behavior changes, the default\n # hashability keeps working the same way.\n\n class Base:\n def __hash__(self):\n return 301\n\n # If frozen or eq is None, then use the default value (do not\n # specify any value in the decorator).\n for frozen, eq, base, expected in [\n (None, None, object, 'unhashable'),\n (None, None, Base, 'unhashable'),\n (None, False, object, 'object'),\n (None, False, Base, 'base'),\n (None, True, object, 'unhashable'),\n (None, True, Base, 'unhashable'),\n (False, None, object, 'unhashable'),\n (False, None, Base, 'unhashable'),\n (False, False, object, 'object'),\n (False, False, Base, 'base'),\n (False, True, object, 'unhashable'),\n (False, True, Base, 'unhashable'),\n (True, None, object, 'tuple'),\n (True, None, Base, 'tuple'),\n (True, False, object, 'object'),\n (True, False, Base, 'base'),\n (True, True, object, 'tuple'),\n (True, True, Base, 'tuple'),\n ]:\n\n with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):\n # First, create the class.\n if frozen is None and eq is None:\n @dataclass\n class C(base):\n i: int\n elif frozen is None:\n @dataclass(eq=eq)\n class C(base):\n i: int\n elif eq is None:\n @dataclass(frozen=frozen)\n class C(base):\n i: int\n else:\n @dataclass(frozen=frozen, eq=eq)\n class C(base):\n i: int\n\n # Now, make sure it hashes as expected.\n if expected == 'unhashable':\n c = C(10)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(c)\n\n elif expected == 'base':\n self.assertEqual(hash(C(10)), 301)\n\n elif expected == 'object':\n # I'm not sure what test to use here. object's\n # hash isn't based on id(), so calling hash()\n # won't tell us much. So, just check the\n # function used is object's.\n self.assertIs(C.__hash__, object.__hash__)\n\n elif expected == 'tuple':\n self.assertEqual(hash(C(42)), hash((42,)))\n\n else:\n assert False, f'unknown value for expected={expected!r}'\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestHash","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_24.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFrozen(unittest.TestCase):\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n c = C(10)\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertEqual(c.i, 10)\n\n def test_inherit(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n @dataclass(frozen=True)\n class D(C):\n j: int\n\n d = D(0, 10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n with self.assertRaises(FrozenInstanceError):\n d.j = 6\n self.assertEqual(d.i, 0)\n self.assertEqual(d.j, 10)\n\n def test_inherit_nonfrozen_from_empty_frozen(self):\n @dataclass(frozen=True)\n class C:\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(C):\n j: int\n\n def test_inherit_nonfrozen_from_empty(self):\n @dataclass\n class C:\n pass\n\n @dataclass\n class D(C):\n j: int\n\n d = D(3)\n self.assertEqual(d.j, 3)\n self.assertIsInstance(d, C)\n\n # Test both ways: with an intermediate normal (non-dataclass)\n # class and without an intermediate class.\n def test_inherit_nonfrozen_from_frozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass(frozen=True)\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(I):\n pass\n\n def test_inherit_frozen_from_nonfrozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one'):\n @dataclass(frozen=True)\n class D(I):\n pass\n\n def test_inherit_from_normal_class(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n class C:\n pass\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n @dataclass(frozen=True)\n class D(I):\n i: int\n\n d = D(10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n\n def test_non_frozen_normal_derived(self):\n # See bpo-32953.\n\n @dataclass(frozen=True)\n class D:\n x: int\n y: int = 10\n\n class S(D):\n pass\n\n s = S(3)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n s.cached = True\n\n # But can't change the frozen attributes.\n with self.assertRaises(FrozenInstanceError):\n s.x = 5\n with self.assertRaises(FrozenInstanceError):\n s.y = 5\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.cached, True)\n\n def test_overwriting_frozen(self):\n # frozen uses __setattr__ and __delattr__.\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __setattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __setattr__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __delattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __delattr__(self):\n pass\n\n @dataclass(frozen=False)\n class C:\n x: int\n def __setattr__(self, name, value):\n self.__dict__['x'] = value * 2\n self.assertEqual(C(10).x, 20)\n\n def test_frozen_hash(self):\n @dataclass(frozen=True)\n class C:\n x: Any\n\n # If x is immutable, we can compute the hash. No exception is\n # raised.\n hash(C(3))\n\n # If x is mutable, computing the hash is an error.\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(C({}))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFrozen","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_25.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestSlots(unittest.TestCase):\n def test_simple(self):\n @dataclass\n class C:\n __slots__ = ('x',)\n x: Any\n\n # There was a bug where a variable in a slot was assumed to\n # also have a default value (of type\n # types.MemberDescriptorType).\n with self.assertRaisesRegex(TypeError,\n r\"__init__\\(\\) missing 1 required positional argument: 'x'\"):\n C()\n\n # We can create an instance, and assign to x.\n c = C(10)\n self.assertEqual(c.x, 10)\n c.x = 5\n self.assertEqual(c.x, 5)\n\n # We can't assign to anything else.\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'y'\"):\n c.y = 5\n\n def test_derived_added_field(self):\n # See bpo-33100.\n @dataclass\n class Base:\n __slots__ = ('x',)\n x: Any\n\n @dataclass\n class Derived(Base):\n x: int\n y: int\n\n d = Derived(1, 2)\n self.assertEqual((d.x, d.y), (1, 2))\n\n # We can add a new field to the derived instance.\n d.z = 10\n\n def test_generated_slots(self):\n @dataclass(slots=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n self.assertEqual((c.x, c.y), (1, 2))\n\n c.x = 3\n c.y = 4\n self.assertEqual((c.x, c.y), (3, 4))\n\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'z'\"):\n c.z = 5\n\n def test_add_slots_when_slots_exists(self):\n with self.assertRaisesRegex(TypeError, '^C already specifies __slots__$'):\n @dataclass(slots=True)\n class C:\n __slots__ = ('x',)\n x: int\n\n def test_generated_slots_value(self):\n\n class Root:\n __slots__ = {'x'}\n\n class Root2(Root):\n __slots__ = {'k': '...', 'j': ''}\n\n class Root3(Root2):\n __slots__ = ['h']\n\n class Root4(Root3):\n __slots__ = 'aa'\n\n @dataclass(slots=True)\n class Base(Root4):\n y: int\n j: str\n h: str\n\n self.assertEqual(Base.__slots__, ('y', ))\n\n @dataclass(slots=True)\n class Derived(Base):\n aa: float\n x: str\n z: int\n k: str\n h: str\n\n self.assertEqual(Derived.__slots__, ('z', ))\n\n @dataclass\n class AnotherDerived(Base):\n z: int\n\n self.assertNotIn('__slots__', AnotherDerived.__dict__)\n\n def test_cant_inherit_from_iterator_slots(self):\n\n class Root:\n __slots__ = iter(['a'])\n\n class Root2(Root):\n __slots__ = ('b', )\n\n with self.assertRaisesRegex(\n TypeError,\n \"^Slots of 'Root' cannot be determined\"\n ):\n @dataclass(slots=True)\n class C(Root2):\n x: int\n\n def test_returns_new_class(self):\n class A:\n x: int\n\n B = dataclass(A, slots=True)\n self.assertIsNot(A, B)\n\n self.assertFalse(hasattr(A, \"__slots__\"))\n self.assertTrue(hasattr(B, \"__slots__\"))\n\n # Can't be local to test_frozen_pickle.\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsClass:\n foo: str\n bar: int\n\n @dataclass(frozen=True)\n class FrozenWithoutSlotsClass:\n foo: str\n bar: int\n\n def test_frozen_pickle(self):\n # bpo-43999\n\n self.assertEqual(self.FrozenSlotsClass.__slots__, (\"foo\", \"bar\"))\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n obj = self.FrozenWithoutSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n def test_slots_with_default_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default='b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_with_default_factory_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default_factory=lambda:'b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_no_weakref(self):\n @dataclass(slots=True)\n class A:\n # No weakref.\n pass\n\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A()\n with self.assertRaisesRegex(TypeError,\n \"cannot create weak reference\"):\n weakref.ref(a)\n\n def test_slots_weakref(self):\n @dataclass(slots=True, weakref_slot=True)\n class A:\n a: int\n\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_slots_weakref_base_str(self):\n class Base:\n __slots__ = '__weakref__'\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_slots_weakref_base_tuple(self):\n # Same as test_slots_weakref_base, but use a tuple instead of a string\n # in the base class.\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still\n # weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_weakref_slot_without_slot(self):\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n @dataclass(weakref_slot=True)\n class A:\n a: int\n\n def test_weakref_slot_make_dataclass(self):\n A = make_dataclass('A', [('a', int),], slots=True, weakref_slot=True)\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n # And make sure if raises if slots=True is not given.\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n B = make_dataclass('B', [('a', int),], weakref_slot=True)\n\n def test_weakref_slot_subclass_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n # A *can* also specify weakref_slot=True if it wants to (gh-93521)\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. But an instance of A\n # is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_weakref_slot_subclass_no_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n @dataclass(slots=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. Even though A doesn't\n # specify weakref_slot, it should still be weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_weakref_slot_normal_base_weakref_slot(self):\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n field: int\n\n # __weakref__ is in the base class, not A. But an instance of\n # A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestSlots","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_26.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDescriptors(unittest.TestCase):\n def test_set_name(self):\n # See bpo-33141.\n\n # Create a descriptor.\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n def __get__(self, instance, owner):\n if instance is not None:\n return 1\n return self\n\n # This is the case of just normal descriptor behavior, no\n # dataclass code is involved in initializing the descriptor.\n @dataclass\n class C:\n c: int=D()\n self.assertEqual(C.c.name, 'cx')\n\n # Now test with a default value and init=False, which is the\n # only time this is really meaningful. If not using\n # init=False, then the descriptor will be overwritten, anyway.\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n self.assertEqual(C().c, 1)\n\n def test_non_descriptor(self):\n # PEP 487 says __set_name__ should work on non-descriptors.\n # Create a descriptor.\n\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n\n def test_lookup_on_instance(self):\n # See bpo-33175.\n class D:\n pass\n\n d = D()\n # Create an attribute on the instance, not type.\n d.__set_name__ = Mock()\n\n # Make sure d.__set_name__ is not called.\n @dataclass\n class C:\n i: int=field(default=d, init=False)\n\n self.assertEqual(d.__set_name__.call_count, 0)\n\n def test_lookup_on_class(self):\n # See bpo-33175.\n class D:\n pass\n D.__set_name__ = Mock()\n\n # Make sure D.__set_name__ is called.\n @dataclass\n class C:\n i: int=field(default=D(), init=False)\n\n self.assertEqual(D.__set_name__.call_count, 1)\n\n def test_init_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_getting_field_calls_get(self):\n class D:\n pass\n\n D.__set__ = Mock()\n D.__get__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__get__ is called.\n D.__get__.reset_mock()\n value = c.i\n self.assertEqual(D.__get__.call_count, 1)\n\n def test_setting_field_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c.i = 10\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_setting_uninitialized_descriptor_field(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D\n\n # D.__set__ is not called because there's no D instance to call it on\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 0)\n\n # D.__set__ still isn't called after setting i to an instance of D\n # because descriptors don't behave like that when stored as instance vars\n c.i = D()\n c.i = 5\n self.assertEqual(D.__set__.call_count, 0)\n\n def test_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n return 100\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n c = C()\n self.assertEqual(c.i, 100)\n\n c = C(5)\n self.assertEqual(c.i, 5)\n\n def test_no_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n raise AttributeError()\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):\n c = C()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDescriptors","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_27.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestMakeDataclass(unittest.TestCase):\n def test_simple(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace={'add_one': lambda self: self.x + 1})\n c = C(10)\n self.assertEqual((c.x, c.y), (10, 5))\n self.assertEqual(c.add_one(), 11)\n\n\n def test_no_mutate_namespace(self):\n # Make sure a provided namespace isn't mutated.\n ns = {}\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace=ns)\n self.assertEqual(ns, {})\n\n def test_base(self):\n class Base1:\n pass\n class Base2:\n pass\n C = make_dataclass('C',\n [('x', int)],\n bases=(Base1, Base2))\n c = C(2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n def test_base_dataclass(self):\n @dataclass\n class Base1:\n x: int\n class Base2:\n pass\n C = make_dataclass('C',\n [('y', int)],\n bases=(Base1, Base2))\n with self.assertRaisesRegex(TypeError, 'required positional'):\n c = C(2)\n c = C(1, 2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n self.assertEqual((c.x, c.y), (1, 2))\n\n def test_init_var(self):\n def post_init(self, y):\n self.x *= y\n\n C = make_dataclass('C',\n [('x', int),\n ('y', InitVar[int]),\n ],\n namespace={'__post_init__': post_init},\n )\n c = C(2, 3)\n self.assertEqual(vars(c), {'x': 6})\n self.assertEqual(len(fields(c)), 1)\n\n def test_class_var(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ])\n c = C(1)\n self.assertEqual(vars(c), {'x': 1})\n self.assertEqual(len(fields(c)), 1)\n self.assertEqual(C.y, 10)\n self.assertEqual(C.z, 20)\n\n def test_other_params(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ],\n init=False)\n # Make sure we have a repr, but no init.\n self.assertNotIn('__init__', vars(C))\n self.assertIn('__repr__', vars(C))\n\n # Make sure random other params don't work.\n with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):\n C = make_dataclass('C',\n [],\n xxinit=False)\n\n def test_no_types(self):\n C = make_dataclass('Point', ['x', 'y', 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': 'typing.Any',\n 'z': 'typing.Any'})\n\n C = make_dataclass('Point', ['x', ('y', int), 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': int,\n 'z': 'typing.Any'})\n\n def test_invalid_type_specification(self):\n for bad_field in [(),\n (1, 2, 3, 4),\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'Invalid field: '):\n make_dataclass('C', ['a', bad_field])\n\n # And test for things with no len().\n for bad_field in [float,\n lambda x:x,\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'has no len\\(\\)'):\n make_dataclass('C', ['a', bad_field])\n\n def test_duplicate_field_names(self):\n for field in ['a', 'ab']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'Field name duplicated'):\n make_dataclass('C', [field, 'a', field])\n\n def test_keyword_field_names(self):\n for field in ['for', 'async', 'await', 'as']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field, 'a'])\n\n def test_non_identifier_field_names(self):\n for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field, 'a'])\n\n def test_underscore_field_names(self):\n # Unlike namedtuple, it's okay if dataclass field names have\n # an underscore.\n make_dataclass('C', ['_', '_a', 'a_a', 'a_'])\n\n def test_funny_class_names_names(self):\n # No reason to prevent weird class names, since\n # types.new_class allows them.\n for classname in ['()', 'x,y', '*', '2@3', '']:\n with self.subTest(classname=classname):\n C = make_dataclass(classname, ['a', 'b'])\n self.assertEqual(C.__name__, classname)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestMakeDataclass","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_28.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestReplace(unittest.TestCase):\n def test(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n z: int = field(init=False, default=10)\n t: int = field(init=False, default=100)\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))\n self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))\n\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=3, z=20, t=50)\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, z=20)\n replace(c, x=3, z=20, t=50)\n\n # Make sure the result is still frozen.\n with self.assertRaisesRegex(FrozenInstanceError, \"cannot assign to field 'x'\"):\n c1.x = 3\n\n # Make sure we can't replace an attribute that doesn't exist,\n # if we're also replacing one that does exist. Test this\n # here, because setting attributes on frozen instances is\n # handled slightly differently from non-frozen ones.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'a'\"):\n c1 = replace(c, x=20, a=5)\n\n def test_invalid_field_name(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'z'\"):\n c1 = replace(c, z=3)\n\n def test_invalid_object(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(C, x=3)\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(0, x=3)\n\n def test_no_init(self):\n @dataclass\n class C:\n x: int\n y: int = field(init=False, default=10)\n\n c = C(1)\n c.y = 20\n\n # Make sure y gets the default value.\n c1 = replace(c, x=5)\n self.assertEqual((c1.x, c1.y), (5, 10))\n\n # Trying to replace y is an error.\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=2, y=30)\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, y=30)\n\n def test_classvar(self):\n @dataclass\n class C:\n x: int\n y: ClassVar[int] = 1000\n\n c = C(1)\n d = C(2)\n\n self.assertIs(c.y, d.y)\n self.assertEqual(c.y, 1000)\n\n # Trying to replace y is an error: can't replace ClassVars.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an \"\n \"unexpected keyword argument 'y'\"):\n replace(c, y=30)\n\n replace(c, x=5)\n\n def test_initvar_is_specified(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int]\n\n def __post_init__(self, y):\n self.x *= y\n\n c = C(1, 10)\n self.assertEqual(c.x, 10)\n with self.assertRaisesRegex(ValueError, r\"InitVar 'y' must be \"\n \"specified with replace()\"):\n replace(c, x=3)\n c = replace(c, x=3, y=5)\n self.assertEqual(c.x, 15)\n\n def test_initvar_with_default_value(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int] = None\n z: InitVar[int] = 42\n\n def __post_init__(self, y, z):\n if y is not None:\n self.x += y\n if z is not None:\n self.x += z\n\n c = C(x=1, y=10, z=1)\n self.assertEqual(replace(c), C(x=12))\n self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42))\n self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1))\n\n def test_recursive_repr(self):\n @dataclass\n class C:\n f: \"C\"\n\n c = C(None)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr..C(f=...)\")\n\n def test_recursive_repr_two_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: \"C\"\n\n c = C(None, None)\n c.f = c\n c.g = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_two_attrs\"\n \"..C(f=..., g=...)\")\n\n def test_recursive_repr_indirection(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n c.f = d\n d.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection\"\n \"..C(f=TestReplace.test_recursive_repr_indirection\"\n \"..D(f=...))\")\n\n def test_recursive_repr_indirection_two(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"E\"\n\n @dataclass\n class E:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n e = E(None)\n c.f = d\n d.f = e\n e.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection_two\"\n \"..C(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..D(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..E(f=...)))\")\n\n def test_recursive_repr_misc_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: int\n\n c = C(None, 1)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_misc_attrs\"\n \"..C(f=..., g=1)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestReplace","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_29.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestAbstract(unittest.TestCase):\n def test_abc_implementation(self):\n class Ordered(abc.ABC):\n @abc.abstractmethod\n def __lt__(self, other):\n pass\n\n @abc.abstractmethod\n def __le__(self, other):\n pass\n\n @dataclass(order=True)\n class Date(Ordered):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertFalse(inspect.isabstract(Date))\n self.assertGreater(Date(2020,12,25), Date(2020,8,31))\n\n def test_maintain_abc(self):\n class A(abc.ABC):\n @abc.abstractmethod\n def foo(self):\n pass\n\n @dataclass\n class Date(A):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertTrue(inspect.isabstract(Date))\n msg = 'class Date with abstract method foo'\n self.assertRaisesRegex(TypeError, msg, Date)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestAbstract","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_30.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestMatchArgs(unittest.TestCase):\n def test_match_args(self):\n @dataclass\n class C:\n a: int\n self.assertEqual(C(42).__match_args__, ('a',))\n\n def test_explicit_match_args(self):\n ma = ()\n @dataclass\n class C:\n a: int\n __match_args__ = ma\n self.assertIs(C(42).__match_args__, ma)\n\n def test_bpo_43764(self):\n @dataclass(repr=False, eq=False, init=False)\n class X:\n a: int\n b: int\n c: int\n self.assertEqual(X.__match_args__, (\"a\", \"b\", \"c\"))\n\n def test_match_args_argument(self):\n @dataclass(match_args=False)\n class X:\n a: int\n self.assertNotIn('__match_args__', X.__dict__)\n\n @dataclass(match_args=False)\n class Y:\n a: int\n __match_args__ = ('b',)\n self.assertEqual(Y.__match_args__, ('b',))\n\n @dataclass(match_args=False)\n class Z(Y):\n z: int\n self.assertEqual(Z.__match_args__, ('b',))\n\n # Ensure parent dataclass __match_args__ is seen, if child class\n # specifies match_args=False.\n @dataclass\n class A:\n a: int\n z: int\n @dataclass(match_args=False)\n class B(A):\n b: int\n self.assertEqual(B.__match_args__, ('a', 'z'))\n\n def test_make_dataclasses(self):\n C = make_dataclass('C', [('x', int), ('y', int)])\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=True)\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=False)\n self.assertNotIn('__match__args__', C.__dict__)\n\n C = make_dataclass('C', [('x', int), ('y', int)], namespace={'__match_args__': ('z',)})\n self.assertEqual(C.__match_args__, ('z',))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestMatchArgs","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_31.py","code":"from dataclasses import *\nimport abc\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestKeywordArgs(unittest.TestCase):\n def test_no_classvar_kwarg(self):\n msg = 'field a is a ClassVar but specifies kw_only'\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=True)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass(kw_only=True)\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n def test_field_marked_as_kwonly(self):\n #######################\n # Using dataclass(kw_only=True)\n @dataclass(kw_only=True)\n class A:\n a: int\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Using dataclass(kw_only=False)\n @dataclass(kw_only=False)\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Not specifying dataclass(kw_only)\n @dataclass\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n def test_match_args(self):\n # kw fields don't show up in __match_args__.\n @dataclass(kw_only=True)\n class C:\n a: int\n self.assertEqual(C(a=42).__match_args__, ())\n\n @dataclass\n class C:\n a: int\n b: int = field(kw_only=True)\n self.assertEqual(C(42, b=10).__match_args__, ('a',))\n\n def test_KW_ONLY(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n\n @dataclass(kw_only=True)\n class B:\n a: int\n _: KW_ONLY\n b: int\n c: int\n B(a=3, b=4, c=5)\n msg = \"takes 1 positional argument but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n B(3, 4, 5)\n\n # Explicitly make a field that follows KW_ONLY be non-keyword-only.\n @dataclass\n class C:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=False)\n c = C(1, 2, b=3)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(c=2, b=3, a=1)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n\n def test_KW_ONLY_as_string(self):\n @dataclass\n class A:\n a: int\n _: 'dataclasses.KW_ONLY'\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n def test_KW_ONLY_twice(self):\n msg = \"'Y' is KW_ONLY, but KW_ONLY has already been specified\"\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n Y: KW_ONLY\n b: int\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n Y: KW_ONLY\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n c: int\n Y: KW_ONLY\n\n # But this usage is okay, since it's not using KW_ONLY.\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=True)\n\n # And if inheriting, it's okay.\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n _: KW_ONLY\n d: int\n\n # Make sure the error is raised in a derived class.\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n X: KW_ONLY\n d: int\n Y: KW_ONLY\n\n\n def test_post_init(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n raise CustomError(f'{b=} {d=}')\n with self.assertRaisesRegex(CustomError, 'b=3 d=4'):\n A(1, c=2, b=3, d=4)\n\n @dataclass\n class B:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n self.a = b\n self.c = d\n b = B(1, c=2, b=3, d=4)\n self.assertEqual(asdict(b), {'a': 3, 'c': 4})\n\n def test_defaults(self):\n # For kwargs, make sure we can have defaults after non-defaults.\n @dataclass\n class A:\n a: int = 0\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n a = A(d=4, b=3)\n self.assertEqual(a.a, 0)\n self.assertEqual(a.b, 3)\n self.assertEqual(a.c, 1)\n self.assertEqual(a.d, 4)\n\n # Make sure we still check for non-kwarg non-defaults not following\n # defaults.\n err_regex = \"non-default argument 'z' follows default argument\"\n with self.assertRaisesRegex(TypeError, err_regex):\n @dataclass\n class A:\n a: int = 0\n z: int\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n def test_make_dataclass(self):\n A = make_dataclass(\"A\", ['a'], kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n B = make_dataclass(\"B\",\n ['a', ('b', int, field(kw_only=False))],\n kw_only=True)\n self.assertTrue(fields(B)[0].kw_only)\n self.assertFalse(fields(B)[1].kw_only)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestKeywordArgs","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"dict-union","pep":"584","introduced_in":"3.9","form":"modern","file":"dict-union/modern_01.py","code":"import collections\nimport collections.abc\nimport gc\nimport pickle\nimport random\nimport string\nimport sys\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import import_helper\nfrom test import mapping_tests\n\n\ndef test_merge_operator(self):\n\n a = {0: 0, 1: 1, 2: 1}\n b = {1: 1, 2: 2, 3: 3}\n\n c = a.copy()\n c |= b\n\n self.assertEqual(a | b, {0: 0, 1: 1, 2: 2, 3: 3})\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n c = b.copy()\n c |= a\n\n self.assertEqual(b | a, {1: 1, 2: 1, 3: 3, 0: 0})\n self.assertEqual(c, {1: 1, 2: 1, 3: 3, 0: 0})\n\n c = a.copy()\n c |= [(1, 1), (2, 2), (3, 3)]\n\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n self.assertIs(a.__or__(None), NotImplemented)\n self.assertIs(a.__or__(()), NotImplemented)\n self.assertIs(a.__or__(\"BAD\"), NotImplemented)\n self.assertIs(a.__or__(\"\"), NotImplemented)\n\n self.assertRaises(TypeError, a.__ior__, None)\n self.assertEqual(a.__ior__(()), {0: 0, 1: 1, 2: 1})\n self.assertRaises(ValueError, a.__ior__, \"BAD\")\n self.assertEqual(a.__ior__(\"\"), {0: 0, 1: 1, 2: 1})\n","source":"cpython_tests","origin":"Lib/test/test_dict.py::DictTest.test_merge_operator","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"exception-notes","pep":"678","introduced_in":"3.11","form":"modern","file":"exception-notes/modern_01.py","code":"import copy\nimport gc\nimport os\nimport sys\nimport unittest\nimport pickle\nimport weakref\nimport errno\nfrom textwrap import dedent\nfrom test.support import (captured_stderr, check_impl_detail,\n cpython_only, gc_collect,\n no_tracing, script_helper,\n SuppressCrashReport)\nfrom test.support.import_helper import import_module\nfrom test.support.os_helper import TESTFN, unlink\nfrom test.support.warnings_helper import check_warnings\nfrom test import support\n\n\ndef test_notes(self):\n for e in [BaseException(1), Exception(2), ValueError(3)]:\n with self.subTest(e=e):\n self.assertFalse(hasattr(e, '__notes__'))\n e.add_note(\"My Note\")\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n with self.assertRaises(TypeError):\n e.add_note(42)\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n e.add_note(\"Your Note\")\n self.assertEqual(e.__notes__, [\"My Note\", \"Your Note\"])\n\n del e.__notes__\n self.assertFalse(hasattr(e, '__notes__'))\n\n e.add_note(\"Our Note\")\n self.assertEqual(e.__notes__, [\"Our Note\"])\n\n e.__notes__ = 42\n self.assertEqual(e.__notes__, 42)\n\n with self.assertRaises(TypeError):\n e.add_note(\"will not work\")\n self.assertEqual(e.__notes__, 42)\n","source":"cpython_tests","origin":"Lib/test/test_exceptions.py::ExceptionTests.test_notes","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"numeric-underscores","pep":"515","introduced_in":"3.6","form":"modern","file":"numeric-underscores/modern_01.py","code":"import sys\nimport time\nimport unittest\nfrom test import support\nfrom test.test_grammar import (VALID_UNDERSCORE_LITERALS,\n INVALID_UNDERSCORE_LITERALS)\n\n\nclass IntStrDigitLimitsTests(unittest.TestCase):\n\n int_class = int # Override this in subclasses to reuse the suite.\n\n def setUp(self):\n super().setUp()\n self._previous_limit = sys.get_int_max_str_digits()\n sys.set_int_max_str_digits(2048)\n\n def tearDown(self):\n sys.set_int_max_str_digits(self._previous_limit)\n super().tearDown()\n\n def test_disabled_limit(self):\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n self.assertLess(sys.get_int_max_str_digits(), 20_000)\n with support.adjust_int_max_str_digits(0):\n self.assertEqual(sys.get_int_max_str_digits(), 0)\n i = self.int_class('1' * 20_000)\n str(i)\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n\n def test_max_str_digits_edge_cases(self):\n \"\"\"Ignore the +/- sign and space padding.\"\"\"\n int_class = self.int_class\n maxdigits = sys.get_int_max_str_digits()\n\n int_class('1' * maxdigits)\n int_class(' ' + '1' * maxdigits)\n int_class('1' * maxdigits + ' ')\n int_class('+' + '1' * maxdigits)\n int_class('-' + '1' * maxdigits)\n self.assertEqual(len(str(10 ** (maxdigits - 1))), maxdigits)\n\n def check(self, i, base=None):\n with self.assertRaises(ValueError):\n if base is None:\n self.int_class(i)\n else:\n self.int_class(i, base)\n\n def test_max_str_digits(self):\n maxdigits = sys.get_int_max_str_digits()\n\n self.check('1' * (maxdigits + 1))\n self.check(' ' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1) + ' ')\n self.check('+' + '1' * (maxdigits + 1))\n self.check('-' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1))\n\n i = 10 ** maxdigits\n with self.assertRaises(ValueError):\n str(i)\n\n def test_denial_of_service_prevented_int_to_str(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 50_000, maxdigits # A test prerequisite.\n get_time = time.process_time\n if get_time() <= 0: # some platforms like WASM lack process_time()\n get_time = time.monotonic\n\n huge_int = int(f'0x{\"c\"*65_000}', base=16) # 78268 decimal digits.\n digits = 78_268\n with support.adjust_int_max_str_digits(digits):\n start = get_time()\n huge_decimal = str(huge_int)\n seconds_to_convert = get_time() - start\n self.assertEqual(len(huge_decimal), digits)\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if seconds_to_convert < 1/64:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{seconds_to_convert} seconds.')\n\n # We test with the limit almost at the size needed to check performance.\n # The performant limit check is slightly fuzzy, give it a some room.\n with support.adjust_int_max_str_digits(int(.995 * digits)):\n with self.assertRaises(ValueError) as err:\n start = get_time()\n str(huge_int)\n seconds_to_fail_huge = get_time() - start\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(seconds_to_fail_huge, seconds_to_convert/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge_int = int(f'0x{\"c\"*500_000}', base=16) # 602060 digits.\n with self.assertRaises(ValueError) as err:\n start = get_time()\n # If not limited, 8 seconds said Zen based cloud VM.\n str(extra_huge_int)\n seconds_to_fail_extra_huge = get_time() - start\n self.assertIn('conversion', str(err.exception))\n self.assertLess(seconds_to_fail_extra_huge, seconds_to_convert/2)\n\n def test_denial_of_service_prevented_str_to_int(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 100_000, maxdigits # A test prerequisite.\n get_time = time.process_time\n if get_time() <= 0: # some platforms like WASM lack process_time()\n get_time = time.monotonic\n\n digits = 133700\n huge = '8'*digits\n with support.adjust_int_max_str_digits(digits):\n start = get_time()\n int(huge)\n seconds_to_convert = get_time() - start\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if seconds_to_convert < 1/64:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{seconds_to_convert} seconds.')\n\n with support.adjust_int_max_str_digits(digits - 1):\n with self.assertRaises(ValueError) as err:\n start = get_time()\n int(huge)\n seconds_to_fail_huge = get_time() - start\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(seconds_to_fail_huge, seconds_to_convert/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge = '7'*1_200_000\n with self.assertRaises(ValueError) as err:\n start = get_time()\n # If not limited, 8 seconds in the Zen based cloud VM.\n int(extra_huge)\n seconds_to_fail_extra_huge = get_time() - start\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(seconds_to_fail_extra_huge, seconds_to_convert/2)\n\n def test_power_of_two_bases_unlimited(self):\n \"\"\"The limit does not apply to power of 2 bases.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n\n for base in (2, 4, 8, 16, 32):\n with self.subTest(base=base):\n self.int_class('1' * (maxdigits + 1), base)\n assert maxdigits < 100_000\n self.int_class('1' * 100_000, base)\n\n def test_underscores_ignored(self):\n maxdigits = sys.get_int_max_str_digits()\n\n triples = maxdigits // 3\n s = '111' * triples\n s_ = '1_11' * triples\n self.int_class(s) # succeeds\n self.int_class(s_) # succeeds\n self.check(f'{s}111')\n self.check(f'{s_}_111')\n\n def test_sign_not_counted(self):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '5' * max_digits\n i = int_class(s)\n pos_i = int_class(f'+{s}')\n assert i == pos_i\n neg_i = int_class(f'-{s}')\n assert -pos_i == neg_i\n str(pos_i)\n str(neg_i)\n\n def _other_base_helper(self, base):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '2' * max_digits\n i = int_class(s, base)\n if base > 10:\n with self.assertRaises(ValueError):\n str(i)\n elif base < 10:\n str(i)\n with self.assertRaises(ValueError) as err:\n int_class(f'{s}1', base)\n\n def test_int_from_other_bases(self):\n base = 3\n with self.subTest(base=base):\n self._other_base_helper(base)\n base = 36\n with self.subTest(base=base):\n self._other_base_helper(base)\n","source":"cpython_tests","origin":"Lib/test/test_int.py::IntStrDigitLimitsTests","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_01.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass ZoneInfoCacheTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n def setUp(self):\n self.klass.clear_cache()\n super().setUp()\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @property\n def tzpath(self):\n return [self.zoneinfo_data.tzpath]\n\n def test_ephemeral_zones(self):\n self.assertIs(\n self.klass(\"America/Los_Angeles\"), self.klass(\"America/Los_Angeles\")\n )\n\n def test_strong_refs(self):\n tz0 = self.klass(\"Australia/Sydney\")\n tz1 = self.klass(\"Australia/Sydney\")\n\n self.assertIs(tz0, tz1)\n\n def test_no_cache(self):\n\n tz0 = self.klass(\"Europe/Lisbon\")\n tz1 = self.klass.no_cache(\"Europe/Lisbon\")\n\n self.assertIsNot(tz0, tz1)\n\n def test_cache_reset_tzpath(self):\n \"\"\"Test that the cache persists when tzpath has been changed.\n\n The PEP specifies that as long as a reference exists to one zone\n with a given key, the primary constructor must continue to return\n the same object.\n \"\"\"\n zi0 = self.klass(\"America/Los_Angeles\")\n with self.tzpath_context([]):\n zi1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIs(zi0, zi1)\n\n def test_clear_cache_explicit_none(self):\n la0 = self.klass(\"America/Los_Angeles\")\n self.klass.clear_cache(only_keys=None)\n la1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIsNot(la0, la1)\n\n def test_clear_cache_one_key(self):\n \"\"\"Tests that you can clear a single key from the cache.\"\"\"\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n\n self.klass.clear_cache(only_keys=[\"America/Los_Angeles\"])\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n\n self.assertIsNot(la0, la1)\n self.assertIs(dub0, dub1)\n\n def test_clear_cache_two_keys(self):\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n tok0 = self.klass(\"Asia/Tokyo\")\n\n self.klass.clear_cache(\n only_keys=[\"America/Los_Angeles\", \"Europe/Dublin\"]\n )\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n tok1 = self.klass(\"Asia/Tokyo\")\n\n self.assertIsNot(la0, la1)\n self.assertIsNot(dub0, dub1)\n self.assertIs(tok0, tok1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ZoneInfoCacheTest","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_02.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass TzPathTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n @staticmethod\n @contextlib.contextmanager\n def python_tzpath_context(value):\n path_var = \"PYTHONTZPATH\"\n try:\n with OS_ENV_LOCK:\n old_env = os.environ.get(path_var, None)\n os.environ[path_var] = value\n yield\n finally:\n if old_env is None:\n del os.environ[path_var]\n else:\n os.environ[path_var] = old_env # pragma: nocover\n\n def test_env_variable(self):\n \"\"\"Tests that the environment variable works with reset_tzpath.\"\"\"\n new_paths = [\n (\"\", []),\n (\"/etc/zoneinfo\", [\"/etc/zoneinfo\"]),\n (f\"/a/b/c{os.pathsep}/d/e/f\", [\"/a/b/c\", \"/d/e/f\"]),\n ]\n\n for new_path_var, expected_result in new_paths:\n with self.python_tzpath_context(new_path_var):\n with self.subTest(tzpath=new_path_var):\n self.module.reset_tzpath()\n tzpath = self.module.TZPATH\n self.assertSequenceEqual(tzpath, expected_result)\n\n def test_env_variable_relative_paths(self):\n test_cases = [\n [(\"path/to/somewhere\",), ()],\n [\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\",),\n ],\n [(\"../relative/path\",), ()],\n [\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\",),\n ],\n [(\"path/to/somewhere\", \"../relative/path\",), ()],\n [\n (\n \"/usr/share/zoneinfo\",\n \"path/to/somewhere\",\n \"../relative/path\",\n ),\n (\"/usr/share/zoneinfo\",),\n ],\n ]\n\n for input_paths, expected_paths in test_cases:\n path_var = os.pathsep.join(input_paths)\n with self.python_tzpath_context(path_var):\n with self.subTest(\"warning\", path_var=path_var):\n # Note: Per PEP 615 the warning is implementation-defined\n # behavior, other implementations need not warn.\n with self.assertWarns(self.module.InvalidTZPathWarning):\n self.module.reset_tzpath()\n\n tzpath = self.module.TZPATH\n with self.subTest(\"filtered\", path_var=path_var):\n self.assertSequenceEqual(tzpath, expected_paths)\n\n def test_reset_tzpath_kwarg(self):\n self.module.reset_tzpath(to=[\"/a/b/c\"])\n\n self.assertSequenceEqual(self.module.TZPATH, (\"/a/b/c\",))\n\n def test_reset_tzpath_relative_paths(self):\n bad_values = [\n (\"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"path/to/somewhere\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\", \"../relative/path\",),\n ]\n for input_paths in bad_values:\n with self.subTest(input_paths=input_paths):\n with self.assertRaises(ValueError):\n self.module.reset_tzpath(to=input_paths)\n\n def test_tzpath_type_error(self):\n bad_values = [\n \"/etc/zoneinfo:/usr/share/zoneinfo\",\n b\"/etc/zoneinfo:/usr/share/zoneinfo\",\n 0,\n ]\n\n for bad_value in bad_values:\n with self.subTest(value=bad_value):\n with self.assertRaises(TypeError):\n self.module.reset_tzpath(bad_value)\n\n def test_tzpath_attribute(self):\n tzpath_0 = [\"/one\", \"/two\"]\n tzpath_1 = [\"/three\"]\n\n with self.tzpath_context(tzpath_0):\n query_0 = self.module.TZPATH\n\n with self.tzpath_context(tzpath_1):\n query_1 = self.module.TZPATH\n\n self.assertSequenceEqual(tzpath_0, query_0)\n self.assertSequenceEqual(tzpath_1, query_1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TzPathTest","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_03.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass TestModule(ZoneInfoTestBase):\n module = py_zoneinfo\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @cached_property\n def _UTC_bytes(self):\n zone_file = self.zoneinfo_data.path_from_key(\"UTC\")\n with open(zone_file, \"rb\") as f:\n return f.read()\n\n def touch_zone(self, key, tz_root):\n \"\"\"Creates a valid TZif file at key under the zoneinfo root tz_root.\n\n tz_root must exist, but all folders below that will be created.\n \"\"\"\n if not os.path.exists(tz_root):\n raise FileNotFoundError(f\"{tz_root} does not exist.\")\n\n root_dir, *tail = key.rsplit(\"/\", 1)\n if tail: # If there's no tail, then the first component isn't a dir\n os.makedirs(os.path.join(tz_root, root_dir), exist_ok=True)\n\n zonefile_path = os.path.join(tz_root, key)\n with open(zonefile_path, \"wb\") as f:\n f.write(self._UTC_bytes)\n\n def test_getattr_error(self):\n with self.assertRaises(AttributeError):\n self.module.NOATTRIBUTE\n\n def test_dir_contains_all(self):\n \"\"\"dir(self.module) should at least contain everything in __all__.\"\"\"\n module_all_set = set(self.module.__all__)\n module_dir_set = set(dir(self.module))\n\n difference = module_all_set - module_dir_set\n\n self.assertFalse(difference)\n\n def test_dir_unique(self):\n \"\"\"Test that there are no duplicates in dir(self.module)\"\"\"\n module_dir = dir(self.module)\n module_unique = set(module_dir)\n\n self.assertCountEqual(module_dir, module_unique)\n\n def test_available_timezones(self):\n with self.tzpath_context([self.zoneinfo_data.tzpath]):\n self.assertTrue(self.zoneinfo_data.keys) # Sanity check\n\n available_keys = self.module.available_timezones()\n zoneinfo_keys = set(self.zoneinfo_data.keys)\n\n # If tzdata is not present, zoneinfo_keys == available_keys,\n # otherwise it should be a subset.\n union = zoneinfo_keys & available_keys\n self.assertEqual(zoneinfo_keys, union)\n\n def test_available_timezones_weirdzone(self):\n with tempfile.TemporaryDirectory() as td:\n # Make a fictional zone at \"Mars/Olympus_Mons\"\n self.touch_zone(\"Mars/Olympus_Mons\", td)\n\n with self.tzpath_context([td]):\n available_keys = self.module.available_timezones()\n self.assertIn(\"Mars/Olympus_Mons\", available_keys)\n\n def test_folder_exclusions(self):\n expected = {\n \"America/Los_Angeles\",\n \"America/Santiago\",\n \"America/Indiana/Indianapolis\",\n \"UTC\",\n \"Europe/Paris\",\n \"Europe/London\",\n \"Asia/Tokyo\",\n \"Australia/Sydney\",\n }\n\n base_tree = list(expected)\n posix_tree = [f\"posix/{x}\" for x in base_tree]\n right_tree = [f\"right/{x}\" for x in base_tree]\n\n cases = [\n (\"base_tree\", base_tree),\n (\"base_and_posix\", base_tree + posix_tree),\n (\"base_and_right\", base_tree + right_tree),\n (\"all_trees\", base_tree + right_tree + posix_tree),\n ]\n\n with tempfile.TemporaryDirectory() as td:\n for case_name, tree in cases:\n tz_root = os.path.join(td, case_name)\n os.mkdir(tz_root)\n\n for key in tree:\n self.touch_zone(key, tz_root)\n\n with self.tzpath_context([tz_root]):\n with self.subTest(case_name):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n\n def test_exclude_posixrules(self):\n expected = {\n \"America/New_York\",\n \"Europe/London\",\n }\n\n tree = list(expected) + [\"posixrules\"]\n\n with tempfile.TemporaryDirectory() as td:\n for key in tree:\n self.touch_zone(key, td)\n\n with self.tzpath_context([td]):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TestModule","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.11","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_04.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass ExtensionBuiltTest(unittest.TestCase):\n \"\"\"Smoke test to ensure that the C and Python extensions are both tested.\n\n Because the intention is for the Python and C versions of ZoneInfo to\n behave identically, these tests necessarily rely on implementation details,\n so the tests may need to be adjusted if the implementations change. Do not\n rely on these tests as an indication of stable properties of these classes.\n \"\"\"\n\n def test_cache_location(self):\n # The pure Python version stores caches on attributes, but the C\n # extension stores them in C globals (at least for now)\n self.assertFalse(hasattr(c_zoneinfo.ZoneInfo, \"_weak_cache\"))\n self.assertTrue(hasattr(py_zoneinfo.ZoneInfo, \"_weak_cache\"))\n\n def test_gc_tracked(self):\n # The pure Python version is tracked by the GC but (for now) the C\n # version is not.\n import gc\n\n self.assertTrue(gc.is_tracked(py_zoneinfo.ZoneInfo))\n self.assertFalse(gc.is_tracked(c_zoneinfo.ZoneInfo))\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ExtensionBuiltTest","origin_revision":"v3.11.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_01.py","code":"from typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_02.py","code":"import typing\nx: typing.List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_03.py","code":"from typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: List[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> List[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_01.py","code":"from typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_02.py","code":"import typing\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_03.py","code":"from typing import List\nSomeAlias = list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: list[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> list[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_01.py","code":"x = lambda foo: None","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[lambdas do not have type annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_02.py","code":"from __future__ import annotations\nfrom typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_03.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not a PEP 585 type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_01.py","code":"open(\"foo\", encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop_before_315","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_02.py","code":"open(\"foo\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_03.py","code":"open(\"foo\", encoding=\"latin1\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"latin1\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_04.py","code":"open(\"foo\", encoding=\"us-ascii\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"us-ascii\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_05.py","code":"open(\"foo\", \"r\", \"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", \"r\", \"utf-8\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_06.py","code":"open(\"foo\", encoding=\"utf-8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[simple case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_07.py","code":"open(\"foo\", encoding=\"UTF8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[alternative spelling]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_08.py","code":"open(*args, encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_18.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"async def c(): return f'{await 1+foo()}'","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_18.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_01.py","code":"if s.startswith(\"foo\"):\n s = s[len(\"foo\"):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_02.py","code":"if s.startswith(S):\n s = s[len(S):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_03.py","code":"if s.endswith(\"foo\"):\n s = s[:-1 * len(\"foo\")]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_04.py","code":"if s.endswith(S):\n s = s[:-1 * len(S)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_05.py","code":"if s.startswith(x):\n s = s[len(x):] # TODO: removeprefix\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_06.py","code":"if True:\n if s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_07.py","code":"if True:\n something_else()\n if s.startswith(x):\n s = s[len(x):]\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_08.py","code":"if (\n x.startswith(y)\n):\n x = x[len(y):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_01.py","code":"s = s.removeprefix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_02.py","code":"s = s.removeprefix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_03.py","code":"s = s.removesuffix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_04.py","code":"s = s.removesuffix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_05.py","code":"s = s.removeprefix(x)\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_06.py","code":"if True:\n s = s.removeprefix(x)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_07.py","code":"if True:\n something_else()\n s = s.removeprefix(x)\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_08.py","code":"x = x.removeprefix(y)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_01.py","code":"if x.startswith(S):\n x = x[len(S):]\nelif x.endswith(T):\n x = x[:-1 * len(T)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop_before_39","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_02.py","code":"if s.startswith(\"a\"):\n s = s.lstrip(\"a\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[unrelated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_03.py","code":"if s.startswith(x):\n s = s[2:]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[cannot prove x is 2]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_04.py","code":"if s.startswith(x):\n s = s[len(x):]\nelse:\n print(\"no!)\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has else]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_05.py","code":"if something:\n print(\"something!\")\nelif s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has elif]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_01.py","code":"from typing import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_02.py","code":"import typing\nD = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": typing.Literal[\"b\", b\"c\"]})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_05.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {\n # first comment\n \"a\": int, # inline comment\n # second comment\n \"b\": str,\n # third comment\n}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_07.py","code":"from typing_extensions import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_08.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_09.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int}, total=True)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nFoo = TypedDict(\"Foo\", {\"lsts\": List[List[int]]})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_11.py","code":"import typing\nif True:\n if False:\n pass\n D = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_12.py","code":"from typing import TypedDict\nFoo = TypedDict(\"Foo\", {\"union\": str | int | None})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_01.py","code":"from typing import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_02.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_03.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_04.py","code":"import typing\nclass D(typing.TypedDict):\n a: typing.Literal['b', b'c']\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_05.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_06.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n # first comment\n a: int # inline comment\n # second comment\n b: str\n # third comment\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_07.py","code":"from typing_extensions import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_08.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_09.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict, total=True):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nclass Foo(TypedDict):\n lsts: List[List[int]]","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_11.py","code":"import typing\nif True:\n if False:\n pass\n class D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_12.py","code":"from typing import TypedDict\nclass Foo(TypedDict):\n union: str | int | None","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_01.py","code":"from wat import TypedDict\nQ = TypedDict(\"Q\")\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[from imported from elsewhere]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_02.py","code":"import typing\nD = typing.TypedDict(\"D\")","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {}, a=int)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[both]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_05.py","code":"import typing\nD = typing.TypedDict(\"D\", 1)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[not a dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {1: str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not a string]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_07.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a-b\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not an identifier]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_08.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"class\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is a keyword]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_09.py","code":"import typing\nD = typing.TypedDict(\"D\", {**d, \"a\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[dictionary splat operator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_10.py","code":"import typing\nC = typing.TypedDict(\"C\", *types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_11.py","code":"import typing\nD = typing.TypedDict(\"D\", **types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starstarkwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_12.py","code":"import typing\nD = typing.TypedDict(\"D\", x=int, total=False)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[kw_typed_dict with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_01.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_02.py","code":"import typing\nx: typing.Union[int]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_03.py","code":"import typing\nx: typing.Union[Foo[str, int], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_04.py","code":"import typing\nx: typing.Union[typing.List[str], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_05.py","code":"import typing\nx: typing.Union[int, str,]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_06.py","code":"import typing\nx: typing.Union[(int, str)]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_07.py","code":"import typing\nx: typing.Union[\n int,\n str\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_08.py","code":"import typing\nx: typing.Union[\n int,\n str,\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_09.py","code":"from typing import Optional\nx: Optional[str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_10.py","code":"import typing\nx: typing.Optional[\n ComplicatedLongType[int]\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: Optional[\"str\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_12.py","code":"from typing import Union, Sequence\ndef f(x: Union[Union[A, B], Sequence[Union[C, D]]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_13.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_14.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_15.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_16.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> Union[int, str]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_01.py","code":"from typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_02.py","code":"x: int\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_03.py","code":"x: Foo[str, int] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_04.py","code":"x: list[str] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_05.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_06.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_07.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_08.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_09.py","code":"from typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_10.py","code":"x: None | (\n ComplicatedLongType[int]\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_12.py","code":"from typing import Union\nfrom collections.abc import Sequence\ndef f(x: A | B | Sequence[C | D]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_13.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x})\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_14.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x}(\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_15.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x}(\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_16.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x})\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: int | str) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> int | str: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_01.py","code":"from __future__ import annotations\nfrom typing import Union\nSomeAlias = Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[<3.9 not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_02.py","code":"from typing import Union\ndef f() -> Union[()]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ empty Union]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_03.py","code":"from typing import Optional\ndef f() -> Optional[\"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Optional of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_04.py","code":"from typing import Union\ndef f() -> Union[int, \"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Union of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_05.py","code":"from typing import Union\ndef f() -> Union[1:2]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[invalid Union slicing]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack[Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack [Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_03.py","code":"from typing import Unpack\ndef f(*args: Unpack[tuple[int, ...]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_03.py","code":"from typing import Unpack\ndef f(*args: *tuple[int, ...]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_01.py","code":"from typing import Unpack\nfoo(Unpack())","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_02.py","code":"from typing import TypeVarTuple, Unpack\nShape = TypeVarTuple(\"Shape\")\nclass Foo(Unpack[Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not inside a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_03.py","code":"from typing import Unpack\nfrom typing import TypedDict\nclass D(TypedDict):\n x: int\ndef f(**kwargs: Unpack[D]) -> None: pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[3.12 TypedDict for kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_01.py","code":"from contextvars import ContextVar\nfrom types import MappingProxyType\nimport re\nimport collections\nimport time\n\n# Okay\nContextVar(\"cv\")\nContextVar(\"cv\", default=())\nContextVar(\"cv\", default=(1, 2, 3))\nContextVar(\"cv\", default=\"foo\")\nContextVar(\"cv\", default=tuple())\nContextVar(\"cv\", default=frozenset())\nContextVar(\"cv\", default=MappingProxyType({}))\nContextVar(\"cv\", default=re.compile(\"foo\"))\nContextVar(\"cv\", default=float(1))\nContextVar(\"cv\", default=frozenset[str]())\nContextVar[frozenset[str]](\"cv\", default=frozenset[str]())\n\n# Bad\nContextVar(\"cv\", default=[])\nContextVar(\"cv\", default={})\nContextVar(\"cv\", default=list())\nContextVar(\"cv\", default=set())\nContextVar(\"cv\", default=dict())\nContextVar(\"cv\", default=[char for char in \"foo\"])\nContextVar(\"cv\", default={char for char in \"foo\"})\nContextVar(\"cv\", default={char: idx for idx, char in enumerate(\"foo\")})\nContextVar(\"cv\", default=collections.deque())\nContextVar(\"cv\", default=set[str]())\nContextVar[set[str]](\"cv\", default=set[str]())\n\ndef bar() -> list[int]:\n return [1, 2, 3]\n\nContextVar(\"cv\", default=bar())\nContextVar(\"cv\", default=time.time())\n\ndef baz(): ...\nContextVar(\"cv\", default=baz())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_02.py","code":"from contextvars import ContextVar\n\nfrom fastapi import Query\nContextVar(\"cv\", default=Query(None))\n\nfrom something_else import Depends\nContextVar(\"cv\", default=Depends())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039_extended.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_01.py","code":"import typing\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, Sequence\n\nKNOWINGLY_MUTABLE_DEFAULT = []\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = []\n immutable_annotation: typing.Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: typing.ClassVar[list[int]] = []\n\n\n@dataclass\nclass B:\n mutable_default: list[int] = []\n immutable_annotation: Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: ClassVar[list[int]] = []\n\n# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n@dataclass\nclass AWithQuotes:\n mutable_default: 'list[int]' = []\n immutable_annotation: 'typing.Sequence[int]' = []\n without_annotation = []\n correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: 'list[int]' = field(default_factory=list)\n class_variable: 'typing.ClassVar[list[int]]'= []\n\n\n# Mutable defaults wrapped in field() calls\n@dataclass\nclass C:\n mutable_default: list[int] = field(default=[]) # RUF008\n mutable_default2: dict[str, int] = field(default={}) # RUF008\n mutable_default3: set[int] = field(default=set()) # RUF008\n mutable_default4: dict[str, int] = field(default=dict()) # RUF008\n correct_factory: list[int] = field(default_factory=list) # okay\n immutable_default: tuple[int, ...] = field(default=()) # okay\n immutable_default2: str = field(default=\"hello\") # okay\n immutable_default3: int = field(default=1) # okay\n non_mutable_var: list[int] = field(default=KNOWINGLY_MUTABLE_DEFAULT) # okay\n class_variable: ClassVar[list[int]] = field(default=[]) # okay\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_02.py","code":"# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n\nfrom __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Example():\n \"\"\"Class that uses ClassVar.\"\"\"\n\n options: ClassVar[dict[str, str]] = {}\n\n\nif typing.TYPE_CHECKING:\n from typing import ClassVar\n\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_03.py","code":"import datetime\nimport re\nimport typing\nfrom dataclasses import dataclass, field\nfrom fractions import Fraction\nfrom pathlib import Path\nfrom typing import ClassVar, NamedTuple\n\n\ndef default_function() -> list[int]:\n return []\n\n\nclass ImmutableType(NamedTuple):\n something: int = 8\n\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\n fine_path: Path = Path()\n fine_date: datetime.date = datetime.date(2042, 1, 1)\n fine_timedelta: datetime.timedelta = datetime.timedelta(hours=7)\n fine_tuple: tuple[int] = tuple([1])\n fine_regex: re.Pattern = re.compile(r\".*\")\n fine_float: float = float(\"-inf\")\n fine_int: int = int(12)\n fine_complex: complex = complex(1, 2)\n fine_str: str = str(\"foo\")\n fine_bool: bool = bool(\"foo\")\n fine_fraction: Fraction = Fraction(1, 2)\n\n\nDEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES = ImmutableType(40)\nDEFAULT_A_FOR_ALL_DATACLASSES = A([1, 2, 3])\n\n\n@dataclass\nclass B:\n hidden_mutable_default: list[int] = default_function()\n another_dataclass: A = A()\n not_optimal: ImmutableType = ImmutableType(20)\n good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES\n okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES\n\n fine_dataclass_function: list[int] = field(default_factory=list)\n\n\nclass IntConversionDescriptor:\n def __init__(self, *, default):\n self._default = default\n\n def __set_name__(self, owner, name):\n self._name = \"_\" + name\n\n def __get__(self, obj, type):\n if obj is None:\n return self._default\n\n return getattr(obj, self._name, self._default)\n\n def __set__(self, obj, value):\n setattr(obj, self._name, int(value))\n\n\n@dataclass\nclass InventoryItem:\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\n\n\n# Regression tests for:\n# https://github.com/astral-sh/ruff/issues/6447\nfrom typing import NewType\n\nListOfStrings = NewType(\"ListOfStrs\", list[str])\nStringsToInts = NewType(\"IntsToStrings\", dict[str, int])\n\nSpecialString = NewType(name=\"SpecialString\", tp=str)\nNegativeInteger = NewType(\"NegInt\", tp=int)\n\nInvalid1 = NewType(*Foo)\nInvalid2 = NewType(\"Invalid2\", name=Foo)\nInvalid3 = NewType(\"Invalid3\", name=Foo, lorem=\"ipsum\")\n\n@dataclass\nclass DataclassWithNewTypeFields:\n # Errors\n a: ListOfStrings = ListOfStrings([])\n b: StringsToInts = StringsToInts()\n c: Invalid1 = Invalid1()\n d: Invalid2 = Invalid2()\n e: Invalid3 = Invalid3()\n\n # No errors\n e: SpecialString = SpecialString(\"Lorem ipsum\")\n f: NegativeInteger = NegativeInteger(-110)\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/15772\ndef f() -> int:\n return 0\n\n@dataclass\nclass ShouldMatchB008RuleOfImmutableTypeAnnotationIgnored:\n this_is_not_fine: list[int] = default_function()\n # ignored\n this_is_fine: int = f()\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/17424\n@dataclass(frozen=True)\nclass C:\n foo: int = 1\n\n\n@dataclass\nclass D:\n c: C = C()\n\n\n@dataclass\nclass E:\n c: C = C()\n\n# https://github.com/astral-sh/ruff/issues/20266\n@dataclass(frozen=True)\nclass C:\n @dataclass(frozen=True)\n class D:\n foo: int = 1\n\n d: D = D() # OK","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_04.py","code":"from dataclasses import dataclass \nfrom typing import TYPE_CHECKING\n\n\ndef default_function() ->list[int]:\n return []\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\nif TYPE_CHECKING:\n from typing import ClassVar\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_05.py","code":"from dataclasses import InitVar, KW_ONLY, MISSING, dataclass, field\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n # Errors\n no_annotation = r\"foo\"\n missing = MISSING\n field = field()\n\n # No errors\n __slots__ = (\"foo\", \"bar\")\n __radd__ = __add__\n _private_attr = 100\n\n with_annotation: str\n with_annotation_and_default: int = 42\n with_annotation_and_field_specifier: bytes = field()\n\n class_var_no_arguments: ClassVar = 42\n class_var_with_arguments: ClassVar[int] = 42\n\n init_var_no_arguments: InitVar = \"lorem\"\n init_var_with_arguments: InitVar[str] = \"ipsum\"\n\n kw_only: KW_ONLY\n tu, ple, [unp, ack, ing] = (0, 1, 2, [3, 4, 5])\n mul, [ti, ple] = (a, ssign), ment = {1: b\"3\", \"2\": 4}, [6j, 5]\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_06.py","code":"from dataclasses import dataclass\nfrom enum import Enum, Flag, IntEnum, IntFlag, StrEnum, ReprEnum\n\nimport attr\nimport attrs\n\n\n## Errors\n\n@dataclass\nclass E(Enum): ...\n\n\n@dataclass # Foobar\nclass E(Flag): ...\n\n\n@dataclass()\nclass E(IntEnum): ...\n\n\n@dataclass() # Foobar\nclass E(IntFlag): ...\n\n\n@dataclass(\n frozen=True\n)\nclass E(StrEnum): ...\n\n\n@dataclass( # Foobar\n frozen=True\n)\nclass E(ReprEnum): ...\n\n\n@dataclass(\n frozen=True\n) # Foobar\nclass E(Enum): ...\n\n\n## No errors\n\n@attrs.define\nclass E(Enum): ...\n\n\n@attrs.frozen\nclass E(Enum): ...\n\n\n@attrs.mutable\nclass E(Enum): ...\n\n\n@attr.s\nclass E(Enum): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_01.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ntry: ...\nexcept* ValueError: ...\nexcept* KeyError: ...\nexcept * Error: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/except_star_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ntry: ...\nexcept* ValueError: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/except_star_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_01.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf'Magic wand: { bag['wand'] }' # nested quotes\nf\"{'\\n'.join(a)}\" # escape sequence\nf'''A complex trick: {\n bag['bag'] # comment\n}'''\nf\"{f\"{f\"{f\"{f\"{f\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nf\"{f'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nf\"{\n 1\n}\"\nf\"test {a \\\n } more\" # line continuation\nf\"\"\"{f\"\"\"{x}\"\"\"}\"\"\" # mark the whole triple quote\nf\"{'\\n'.join(['\\t', '\\v', '\\r'])}\" # multiple escape sequences, multiple errors\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/pep701_f_string_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\n# nested interpolations also need to be checked\nf'{1: abcd \"{'aa'}\" }'\nf'{1: abcd \"{\"\\n\"}\" }'\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/pep701_nested_interpolation_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_03.py","code":"# parse_options: {\"target-version\": \"3.12\"}\nf'Magic wand: { bag['wand'] }' # nested quotes\nf\"{'\\n'.join(a)}\" # escape sequence\nf'''A complex trick: {\n bag['bag'] # comment\n}'''\nf\"{f\"{f\"{f\"{f\"{f\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nf\"{f'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nf\"{\n 1\n}\"\nf\"test {a \\\n } more\" # line continuation\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep701_f_string_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_04.py","code":"# Empty f-strings\nf\"\"\nF\"\"\nf''\nf\"\"\"\"\"\"\nf''''''\n\nf\"{\" f\"}\"\nf\"{foo!s}\"\nf\"{3,}\"\nf\"{3!=4:}\"\nf'{3:{\"}\"}>10}'\nf'{3:{\"{\"}>10}'\nf\"{ foo = }\"\nf\"{ foo = :.3f }\"\nf\"{ foo = !s }\"\nf\"{ 1, 2 = }\"\nf'{f\"{3.1415=:.1f}\":*^20}'\n\n{\"foo \" f\"bar {x + y} \" \"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nf\"\\{foo}\\{bar:\\}\"\nf\"\\\\{{foo\\\\}}\"\nf\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nf\"{ ( foo ) = }\"\n\nf\"normal {foo} {{another}} {bar} {{{three}}}\"\nf\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nf\"normal {x:y + 2}\"\nf\"{x:{{1}.pop()}}\"\nf\"{(lambda x:{x})}\"\nf\"{x =}\"\nf\"{ x = }\"\nf\"{x=!a}\"\nf\"{x:.3f!r =}\"\nf\"{x = !r :.3f}\"\nf\"{x:.3f=!r}\"\n\"hello\" f\"{x}\"\nf\"{x}\" f\"{y}\"\nf\"{x}\" \"world\"\nf\"Invalid args in command: {command, *args}\"\n\"foo\" f\"{x}\" \"bar\"\n(\n f\"a\"\n F\"b\"\n \"c\"\n rf\"d\"\n fr\"e\"\n)\n\n# With unicode strings\nu\"foo\" f\"{bar}\" \"baz\" \" some\"\n\"foo\" f\"{bar}\" u\"baz\" \" some\"\n\"foo\" f\"{bar}\" \"baz\" u\" some\"\nu\"foo\" f\"bar {baz} really\" u\"bar\" \"no\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/f_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_01.py","code":"f\"hello {x:} world\"\nf\"hello {x:.3f} world\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/fstring_format_spec_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf\"{1:''}\" # but this is okay on all versions\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_nested_quote_in_format_spec_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_03.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf\"outer {'# not a comment'}\"\nf'outer {x:{\"# not a comment\"} }'\nf\"\"\"{f'''{f'{\"# not a comment\"}'}'''}\"\"\"\nf\"\"\"{f'''# before expression {f'# aro{f\"#{1+1}#\"}und #'}'''} # after expression\"\"\"\nf\"\"\"{\n 1\n}\"\"\"\nf\"escape outside of \\t {expr}\\n\"\nf\"test\\\"abcd\"\nf\"{1:\\x64}\" # escapes are valid in the format spec\nf\"{1:\\\"d\\\"}\" # this also means that escaped outer quotes are valid\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep701_f_string_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_01.py","code":"import typing\nimport typing_extensions\nfrom typing import Literal\n\n# Shouldn't affect non-union field types.\nfield1: Literal[1] # OK\n\n# Should emit for duplicate field types.\nfield2: Literal[1] | Literal[2] # Error\n\n# Should emit for union types in arguments.\ndef func1(arg1: Literal[1] | Literal[2]): # Error\n print(arg1)\n\n\n# Should emit for unions in return types.\ndef func2() -> Literal[1] | Literal[2]: # Error\n return \"my Literal[1]ing\"\n\n\n# Should emit in longer unions, even if not directly adjacent.\nfield3: Literal[1] | Literal[2] | str # Error\nfield4: str | Literal[1] | Literal[2] # Error\nfield5: Literal[1] | str | Literal[2] # Error\nfield6: Literal[1] | bool | Literal[2] | str # Error\n\n# Should emit for non-type unions.\nfield7 = Literal[1] | Literal[2] # Error\n\n# Should emit for parenthesized unions.\nfield8: Literal[1] | (Literal[2] | str) # Error\n\n# Should handle user parentheses when fixing.\nfield9: Literal[1] | (Literal[2] | str) # Error\nfield10: (Literal[1] | str) | Literal[2] # Error\n\n# Should emit for union in generic parent type.\nfield11: dict[Literal[1] | Literal[2], str] # Error\n\n# Should emit for unions with more than two cases\nfield12: Literal[1] | Literal[2] | Literal[3] # Error\nfield13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error\n\n# Should emit for unions with more than two cases, even if not directly adjacent\nfield14: Literal[1] | Literal[2] | str | Literal[3] # Error\n\n# Should emit for unions with mixed literal internal types\nfield15: Literal[1] | Literal[\"foo\"] | Literal[True] # Error\n\n# Shouldn't emit for duplicate field types with same value; covered by Y016\nfield16: Literal[1] | Literal[1] # OK\n\n# Shouldn't emit if in new parent type\nfield17: Literal[1] | dict[Literal[2], str] # OK\n\n# Shouldn't emit if not in a union parent\nfield18: dict[Literal[1], Literal[2]] # OK\n\n# Should respect name of literal type used\nfield19: typing.Literal[1] | typing.Literal[2] # Error\n\n# Should emit in cases with newlines\nfield20: typing.Union[\n Literal[\n 1 # test\n ],\n Literal[2],\n] # Error, newline and comment will not be emitted in message\n\n# Should handle multiple unions with multiple members\nfield21: Literal[1, 2] | Literal[3, 4] # Error\n\n# Should emit in cases with `typing.Union` instead of `|`\nfield22: typing.Union[Literal[1], Literal[2]] # Error\n\n# Should emit in cases with `typing_extensions.Literal`\nfield23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error\n\n# Should emit in cases with nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error\n\n# Should emit in cases with mixed `typing.Union` and `|`\nfield25: typing.Union[Literal[1], Literal[2] | str] # Error\n\n# Should emit only once in cases with multiple nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error\n\n# Should use the first literal subscript attribute when fixing\nfield25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error\n\nfrom typing import IO, Literal\n\nInlineOption = Literal[\"a\"] | Literal[\"b\"] | IO[str]\n\n# Should use unsafe fix when comments are deleted\nfield26: (\n # First comment\n Literal[\"a\", \"b\"]\n # Second comment\n | Literal[\"c\", \"d\"]\n)\nfield27: (\n Literal[\"a\", \"b\"] # First comment\n | Literal[\"c\", \"d\"] # Second comment\n)\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI030.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_02.py","code":"import typing\nfrom typing import Literal, TypeAlias, Union\n\nA: str | Literal[\"foo\"]\nB: TypeAlias = typing.Union[Literal[b\"bar\", b\"foo\"], bytes, str]\nC: TypeAlias = typing.Union[Literal[5], int, typing.Union[Literal[\"foo\"], str]]\nD: TypeAlias = typing.Union[Literal[b\"str_bytes\", 42], bytes, int]\nE: TypeAlias = typing.Union[typing.Union[typing.Union[typing.Union[Literal[\"foo\"], str]]]]\nF: TypeAlias = typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\nG: typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\n\ndef func(x: complex | Literal[1J], y: Union[Literal[3.14], float]): ...\n\n# OK\nA: Literal[\"foo\"]\nB: TypeAlias = Literal[b\"bar\", b\"foo\"]\nC: TypeAlias = typing.Union[Literal[5], Literal[\"foo\"]]\nD: TypeAlias = Literal[b\"str_bytes\", 42]\n\ndef func(x: Literal[1J], y: Literal[3.14]): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI051.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_03.py","code":"from typing import Literal\nimport typing as t\nimport typing_extensions\n\nx: Literal[True, False, True, False] # PYI062 twice here\n\ny: Literal[1, print(\"hello\"), 3, Literal[4, 1]] # PYI062 on the last 1\n\nz: Literal[{1, 3, 5}, \"foobar\", {1,3,5}] # PYI062 on the set literal\n\nLiteral[1, Literal[1]] # once\nLiteral[1, 2, Literal[1, 2]] # twice\nLiteral[1, Literal[1], Literal[1]] # twice\nLiteral[1, Literal[2], Literal[2]] # once\nt.Literal[1, t.Literal[2, t.Literal[1]]] # once\ntyping_extensions.Literal[1, 1, 1] # twice\nLiteral[\n 1, # comment\n Literal[ # another comment\n 1\n ]\n] # once\n\n# Ensure issue is only raised once, even on nested literals\nMyType = Literal[\"foo\", Literal[True, False, True], \"bar\"] # PYI062\n\nn: Literal[\"No\", \"duplicates\", \"here\", 1, \"1\"]\n\n\n# nested literals, all equivalent to `Literal[1]`\nLiteral[Literal[1]] # no duplicate\nLiteral[Literal[Literal[1], Literal[1]]] # once\nLiteral[Literal[1], Literal[Literal[Literal[1]]]] # once\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI062.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_01.py","code":"# parse_options: { \"target-version\": \"3.9\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/match_before_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_02.py","code":"match 2:\n case Class(x=x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_keyword_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_03.py","code":"match x:\n case [a] | [a]: ...\n case (x, y) | (x, y): ...\n case (x, (y | y)): ...\n case [a, _] | [a, _]: ...\n case [a] | [C(a)]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/different_match_pattern_bindings.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_04.py","code":"match x:\n case {x.a: 1, x.a: 2}: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/duplicate_match_key_attr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_05.py","code":"match x:\n case 2: ...\n case var: ...\nmatch x:\n case 2: ...\n case _: ...\nmatch x:\n case var if True: ... # don't try to refute a guarded pattern\n case 2: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/irrefutable_case_pattern_at_end.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_06.py","code":"# parse_options: { \"target-version\": \"3.10\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_after_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_07.py","code":"match foo:\n case foo_bar: ...\nmatch foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_08.py","code":"match foo:\n case case: ...\nmatch foo:\n case match: ...\nmatch foo:\n case type: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_09.py","code":"match foo:\n case match.bar: ...\n case case.bar: ...\n case type.bar: ...\n case match.case.type.bar.type.case.match: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_attr_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_10.py","code":"match foo:\n case _: ...\nmatch 1:\n case _: ...\nmatch 1.0:\n case _: ...\nmatch 1j:\n case _: ...\nmatch \"foo\":\n case _: ...\nmatch f\"foo {x}\":\n case _: ...\nmatch {1, 2}:\n case _: ...\nmatch ~foo:\n case _: ...\nmatch ...:\n case _: ...\nmatch not foo:\n case _: ...\nmatch await foo():\n case _: ...\nmatch lambda foo: foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_11.py","code":"match match:\n case _: ...\nmatch case:\n case _: ...\nmatch type:\n case _: ...\nmatch None:\n case _: ...\nmatch True:\n case _: ...\nmatch False:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_12.py","code":"match (1, 2) # Identifier\nmatch (1, 2): # Keyword\n case _: ...\nmatch [1:] # Identifier\nmatch [1, 2]: # Keyword\n case _: ...\nmatch * foo # Identifier\nmatch - foo # Identifier\nmatch -foo: # Keyword\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_or_identifier.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_13.py","code":"match subject:\n case [a, b]: ...\n case (a, b): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_parentheses_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_14.py","code":"match subject:\n case a if x: ...\n case a, b: ...\n case a, b if x: ...\n case a: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_15.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_16.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_17.py","code":"match 2:\n case Class(x) | [x] | x: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/multiple_assignment_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_18.py","code":"match ruff:\n case {\"lint\": {\"select\": x} | {\"extend-select\": x}} | {\"select\": x}:\n ...\nmatch 42:\n case [[x] | [x]] | x: ...\nmatch 42:\n case [[x | x] | [x]] | x: ...\nmatch 42:\n case ast.Subscript(n, ast.Constant() | ast.Slice()) | ast.Attribute(n): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/nested_alternative_patterns.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_19.py","code":"# Empty f-strings\nf\"\"\nF\"\"\nf''\nf\"\"\"\"\"\"\nf''''''\n\nf\"{\" f\"}\"\nf\"{foo!s}\"\nf\"{3,}\"\nf\"{3!=4:}\"\nf'{3:{\"}\"}>10}'\nf'{3:{\"{\"}>10}'\nf\"{ foo = }\"\nf\"{ foo = :.3f }\"\nf\"{ foo = !s }\"\nf\"{ 1, 2 = }\"\nf'{f\"{3.1415=:.1f}\":*^20}'\n\n{\"foo \" f\"bar {x + y} \" \"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nf\"\\{foo}\\{bar:\\}\"\nf\"\\\\{{foo\\\\}}\"\nf\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nf\"{ ( foo ) = }\"\n\nf\"normal {foo} {{another}} {bar} {{{three}}}\"\nf\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nf\"normal {x:y + 2}\"\nf\"{x:{{1}.pop()}}\"\nf\"{(lambda x:{x})}\"\nf\"{x =}\"\nf\"{ x = }\"\nf\"{x=!a}\"\nf\"{x:.3f!r =}\"\nf\"{x = !r :.3f}\"\nf\"{x:.3f=!r}\"\n\"hello\" f\"{x}\"\nf\"{x}\" f\"{y}\"\nf\"{x}\" \"world\"\nf\"Invalid args in command: {command, *args}\"\n\"foo\" f\"{x}\" \"bar\"\n(\n f\"a\"\n F\"b\"\n \"c\"\n rf\"d\"\n fr\"e\"\n)\n\n# With unicode strings\nu\"foo\" f\"{bar}\" \"baz\" \" some\"\n\"foo\" f\"{bar}\" u\"baz\" \" some\"\n\"foo\" f\"{bar}\" \"baz\" u\" some\"\nu\"foo\" f\"bar {baz} really\" u\"bar\" \"no\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/f_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_20.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_01.py","code":"match[0]: int\nmatch [x, y, z]: dict\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_annotated_assignment.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_02.py","code":"match not in case\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_03.py","code":"match\nmatch != foo\n(foo, match)\n[foo, match]\n{foo, match}\nmatch;\nmatch: int\nmatch,\nmatch.foo\nmatch / foo\nmatch << foo\nmatch and foo\nmatch is not foo\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_04.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_01.py","code":"# parse_options: {\"target-version\": \"3.8\"}\ndef foo(a, /): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pos_only_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_02.py","code":"lambda: a\nlambda: 1\nlambda x: 1\nlambda x, y: ...\nlambda a, b, c: 1\nlambda a, b=20, c=30: 1\nlambda x, y: x * y\nlambda y, z=1: z * y\nlambda *a: a\nlambda *a, z, x=0: ...\nlambda *, a, b, c: 1\nlambda *, a, b=20, c=30: 1\nlambda a, b, c, *, d, e: 0\nlambda **kwargs: f()\nlambda *args, **kwargs: f() + 1\nlambda *args, a, b=1, **kwargs: f() + 1\nlambda a, /: ...\nlambda a, /, b: ...\nlambda a=1, /,: ...\nlambda a, b, /, *, c: ...\nlambda kw=1, *, a: ...\nlambda a, b=20, /, c=30: 1\nlambda a, b, /, c, *, d, e: 0\nlambda a, b, /, c, *d, e, **f: 0","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/lambda.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_03.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_01.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ntype x = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_stmt_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_02.py","code":"# parse_options: {\"target-version\": \"3.12\"}\nclass Foo[S: (str, bytes), T: float, *Ts, **P]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_type_params_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_03.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ndef foo[T](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/function_type_params_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_04.py","code":"return; import a; from x import y; z; type T = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/simple_stmts_with_semicolons.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_05.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype x = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_stmt_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_06.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"unchanged","file":"type-param-syntax/unchanged_01.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/param_with_star_annotation_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_05.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_06.py","code":"def foo(*args: *int | str): ...\ndef foo(*args: *(int or str)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_07.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_08.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/star_index_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_09.py","code":"*a\n*(a + 1)\n*x.attr\n\narray_slice = array[0, *indexes, -1]\narray[0, *indexes, -1] = array_slice\narray[*indexes_to_select, *indexes_to_select]\narray[3:5, *indexes_to_select]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/starred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_10.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_11.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nout[(*(slice(None) for _ in range(2)), *ind)] = 1\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_01.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/decorator_named_expression_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_03.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_function_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_04.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_05.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_comp_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_06.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{x := 1, 2, 3}\n{1, x := 2, 3}\n{1, 2, x := 3}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_literal_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_07.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/walrus_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_08.py","code":"# parse_options: { \"target-version\": \"3.9\" }\n@buttons[0].clicked.connect\ndef spam(): ...\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/decorator_expression_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_09.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_10.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_11.py","code":"[a := 0 for x in range(0)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_rebound_comprehension_variable.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_12.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[(x:=1)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_13.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{(x := 1), 2, 3}\n{(last := x) for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_14.py","code":"# parse_options: {\"target-version\": \"3.9\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_index_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_15.py","code":"# parse_options: {\"target-version\": \"3.9\"}\n{x := 1, 2, 3}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_16.py","code":"class F(y := list): ...\ndef f():\n class G((yield 1)): ...\n class H((yield from 1)): ...\nasync def f():\n class G((await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_17.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_function_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_18.py","code":"# parse_options: {\"target-version\": \"3.13\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_19.py","code":"# parse_options: { \"target-version\": \"3.8\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/walrus_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_20.py","code":"# This only tests the call arguments and not the expression before the opening parenthesis.\n\n# Simple\ncall()\ncall(x, y)\ncall(x, y,) # Trailing comma\ncall(x=1, y=2)\ncall(*x)\ncall(**x)\n\n# Order\ncall(x, y=1)\ncall(x, *y)\ncall(x, **y)\ncall(x=1, *y)\ncall(x=1, **y)\ncall(*x, **y)\ncall(*x, y, z)\ncall(**x, y=1, z=2)\ncall(*x1, *x2, **y1, **y2)\ncall(x=1, **y, z=1)\n\n# Keyword expression\ncall(x=1 if True else 2)\ncall(x=await y)\ncall(x=lambda y: y)\ncall(x=(y := 1))\n\n# Yield expression\ncall((yield x))\ncall((yield from x))\n\n# Named expression\ncall(x := 1)\ncall(x := 1 for i in iter)\n\n# Starred expressions\ncall(*x and y)\ncall(*x | y)\ncall(*await x)\ncall(*lambda x: x)\ncall(*x if True else y)\n\n# Double starred\ncall(**x)\ncall(**x and y)\ncall(**await x)\ncall(**x if True else y)\ncall(**(yield x))\ncall(**lambda x: x)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/arguments.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_21.py","code":"# Simple\n{}\n{1: 2}\n{1: 2, a: 1, b: 'hello'}\n\n# Mixed indentations\n{\n}\n{\n 1:\n 2,\n 3\n :4\n}\n\n# Nested\n{{1: 2}: {3: {4: 5}}}\n\n# Lambda expressions\n{lambda x: x: 1}\n{'A': lambda p: None, 'B': C,}\n\n# Named expressions\n{(x := 1): y}\n{(x := 1): (y := 2)}\n\n# Double star unpacking\n{**d}\n{a: b, **d}\n{**a, **b}\n{\"a\": \"b\", **c, \"d\": \"e\"}\n{1: 2, **{'nested': 'dict'}}\n{x * 1: y ** 2, **call()}\n# Here, `not` isn't allowed but parentheses resets the precedence\n{**(not x)}\n\n# Random expressions\n{1: x if True else y}\n{x if True else y: y for x in range(10) for y in range(10)}\n{{1, 2}: 3, x: {1: 2,},}\n{(x): (y), (z): (a)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/dictionary.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_22.py","code":"(x for target in iter)\n(x async for target in iter)\n(x for target in iter if x in y if a and b if c)\n(x for target1 in iter1 if x and y for target2 in iter2 if a > b)\n(x for target1 in iter1 if x and y async for target2 in iter2 if a > b)\n\n# Named expression\n(x := y + 1 for y in z)\n\n# If expression\n(x if y else y for y in z)\n\n# Arguments\n\" \".join(\n sql\n for sql in (\n \"LIMIT %d\" % limit if limit else None,\n (\"OFFSET %d\" % offset) if offset else None,\n )\n)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/generator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_23.py","code":"# Simple lists\n[]\n[1]\n[1,]\n[1, 2, 3]\n[1, 2, 3,]\n\n# Mixed with indentations\n[\n]\n[\n 1\n]\n[\n 1,\n 2,\n]\n\n# Nested\n[[[1]]]\n[[1, 2], [3, 4]]\n\n# Named expression\n[x := 2]\n[x := 2,]\n[1, x := 2, 3]\n\n# Star expression\n[1, *x, 3]\n[1, *x | y, 3]\n\n# Random expressions\n[1 + 2, [1, 2, 3, 4], (a, b + c, d), {a, b, c}, {a: 1}, x := 2]\n[call1(call2(value.attr()) for element in iter)]\n[item in xs]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/list.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_24.py","code":"(name := 0)\n(name := (x * y))\n(name := 1 + 1)\n(name := (*x, y))\n(name := x if True else y)\n(name := lambda x: x)\n(name := (yield x))\n(name := (yield from x))","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/named.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_25.py","code":"(expr)\n(expr)()\n(expr)()()()\n\n(a and b or c)\n(lambda x: x)\n(x := 2)\n(yield x)\n(yield from x)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/parenthesized.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_26.py","code":"# Simple sets\n{}\n{1}\n{1,}\n{1, 2, 3}\n{1, 2, 3,}\n\n# Mixed with indentations\n{\n}\n{\n 1\n}\n{\n 1,\n 2,\n}\n\n# Nested\n{{1}}\n{{1, 2}, {3, 4}}\n\n# Named expression\n{x := 2}\n{1, x := 2, 3}\n{1, (x := 2),}\n\n# Star expression\n{1, *x, 3}\n{1, *x | y, 3}\n\n# Random expressions\n{1 + 2, (a, b), {1, 2, 3}, {a: b, **d}}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/set.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_27.py","code":"# Various combinations\nx[:]\nx[1:]\nx[:2]\nx[1:2]\nx[::]\nx[1::]\nx[:2:]\nx[1:2:]\nx[::3]\nx[1::3]\nx[:2:3]\nx[1:2:3]\n\n# Named expression\nx[y := 2]\nx[(y := 2):]\nx[y := 2,]\n\n# These are two separate slice elements\nx[1,:2,]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/slice.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_28.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_29.py","code":"# With parentheses\n()\n(())\n((()), ())\n(a,)\n(a, b)\n(a, b,)\n((a, b))\n\n# Without parentheses\na,\na, b\na, b,\n\n# Starred expression\n*a,\na, *b\n*a | b, *await x, (), *()\n(*a,)\n(a, *b)\n(*a | b, *await x, (), *())\n\n# Named expression\n(x := 1,)\n(x, y := 2)\n(x, y := 2, z)\nx, (y := 2), z\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_30.py","code":"# Simple\n-1\n+1\n~1\nnot x\n\n# Multiple\n---1\n-+~1\nnot-+~1\nnot not x\n\n# Precedence check\n- await 1\n+ await 1 ** -2\n~(1, 2)\n-1 + 2\n\n# Precedence check for `not` operator because it is higher than other unary operators\nnot a and b or not c | d and not e\nnot (x := 1)\nnot a | (not b)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/unary_op.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_31.py","code":"yield\nyield x\nyield x + 1\nyield x and y\nyield call()\nyield [1, 2]\nyield {3, 4}\nyield {x: 5}\nyield x, y\nyield (x, y)\nyield x == y\nyield (x := 1)\nyield x, *y\nyield *x,\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_32.py","code":"yield from x\nyield from x + 1\nyield from x and y\nyield from call()\nyield from [1, 2]\nyield from {3, 4}\nyield from {x: 5}\nyield from (x, y)\nyield from x == y\nyield from (x := 1)\nyield from (x, *x | y)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield_from.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_33.py","code":"@function_decorator\ndef test():\n pass\n\n\n@class_decorator\nclass Test:\n pass\n\n\n@decorator\ndef f(): ...\n\n\n@a.b.c\ndef f(): ...\n\n\n@a\n@a.b.c\ndef f(): ...\n\n\n@a\n@1 | 2\n@a.b.c\nclass T: ...\n\n\n@x := 1\n@x if True else y\n@lambda x: x\n@x and y\n@(yield x)\n@(*x, *y)\ndef f(): ...\n\n\n# This is not multiple decorators on the same line but rather a binary (`@`) expression\n@x @y\ndef foo(): ...\n\n\n@x\n\n\n@y\n\n\ndef foo(): ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/other/decorator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_34.py","code":"# These test cases specifically tests out parsing a list of with items that start with a\n# left parenthesis. This makes parsing ambiguous as to whether the left parenthesis is to\n# parenthesize the with items or part of a parenthesized expression. It's not to test the\n# with statement itself.\n\n# The following sections basically separates between which node does the\n# start parenthesis belongs to.\n\n# Parenthesized with items\n# ------------------------\n#\n# - The opening parenthesis belongs to the with statement.\n# - The range of the first with item shouldn't include the parenthesis.\nwith (item): ...\nwith (item,): ... # with a trailing comma\nwith (((item))): ...\nwith (item1, item2): ...\nwith (item1, item2,): ... # with a trailing comma\nwith ((item1), (item2), item3 as f, (item4)): ...\nwith ((item1, item2), item3): ...\nwith ((x, y) as f): ...\nwith (item1 as f1, item2 as f2): ...\nwith (item1 as f1, item2 as f2,): ... # with a trailing comma\nwith (item == 10,): ...\nwith ((item := 10)): ...\nwith ((item := 10,)): ...\nwith ((*item,)): ...\nwith ((item1 := 10), item2): ...\nwith (item1 as f, (item2 := 10)): ...\nwith (foo()): ...\nwith (foo(),): ...\nwith (foo() as f): ...\nwith (f\"{item := 42}\"): ...\nwith (f\"{(item := 42)}\"): ...\nwith ((x for x in range(10)), item): ...\nwith (item, (x for x in range(10))): ...\nwith (item, (x for x in range(10)), item): ...\nwith (data[1:2]): ...\nwith (data[1:2] as f): ...\nwith ((x for x in iter) as y): ...\n\n# Parenthesized expression\n# ------------------------\n#\n# - The opening parenthesis belongs to the context expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (item) as f: ...\nwith (item := 10): ...\nwith (item := 10) as f: ...\nwith ( item := 1 ): ...\nwith (item1 := 42), item2: ...\nwith (root + filename).read(): ... # Postfix expression\nwith (root + filename).read() as f: ... # Postfix expression\nwith (foo)(): ... # Postfix expression\nwith (foo)() as f: ... # Postfix expression\nwith (foo()) as f: ...\nwith (data[1:2]) as f: ...\nwith (1, 2, 3)[0]: ... # Postfix expression\nwith (1, 2, 3)[0] as f: ... # Postfix expression\nwith (item1), (item2): ...\nwith (open('a.py')), (open('b.py')): ...\nwith (yield x): ...\nwith ((yield x)): ...\nwith (yield from x): ...\nwith ((yield from x)): ...\nwith (yield x) as f: ...\nwith (yield x,) as f: ...\n\n\n# Tuple expression\n# ----------------\n#\n# - This is a sub-case of the parenthesized expression and requires transforming the list of\n# with items from the speculative parsing to a single with item containing a tuple expression.\n# - The opening parenthesis belongs to the tuple expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (): ...\nwith () as f: ...\nwith (item := 42,): ...\nwith (1, item := 2): ...\nwith (item1 := 10, item2): ...\nwith (item1, item2 := 2, item3) as f: ...\nwith (item,) as f: ...\nwith (*item,): ...\nwith (*item,) as f: ...\nwith (item1, item2) as f: ...\nwith (item1, item2,) as f: ...\nwith (item1, item2), item3: ...\nwith ((item1, item2), item3) as f: ...\nwith (item1,), item2, (item3, item4) as f: ...\nwith (item1, item2) as f1, item3 as f2: ...\nwith (item1, *item2): ...\nwith (item1, *item2) as f: ...\nwith (item1 := 10, *item2): ...\nwith ((item1 := 10), *item2): ...\n\n\n# Parenthesized generator expression\n# ----------------------------------\n#\n# - The opening parenthesis belongs to the generator expression\n# - The range of the with item should include the parenthesis\nwith (x for x in range(10)): ...\nwith (x async for x in range(10)): ...\nwith (x for x in range(10)), item: ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/ambiguous_lpar_with_items.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_35.py","code":"if 1: 10\nelif 2: 20\nelse: 30\n\nif True:\n 1\n ...\nif x < 1:\n ...\nelse:\n pass\n\nif a:\n pass\nelif b:\n ...\n\nif a and b:\n ...\nelif True:\n ...\nelif c:\n ...\nelif d:\n ...\nelse:\n f()\n\n# Valid test expression\nif a := b: ...\nelif a := b: ...\nif lambda x: x: ...\nelif lambda x: x: ...\nif await x: ...\nelif await x: ...\nif (yield x): ...\nelif (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/if.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_36.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_37.py","code":"return\nreturn x\nreturn *x, *y\nreturn (x := 1)\nreturn None\nreturn x and y\nreturn 1 < 2\nreturn 1, 2,\nreturn call()\nreturn attr.value()\nreturn await x\nreturn lambda x: y\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/return.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_38.py","code":"while x:\n ...\n\nwhile (x > 1) and y:\n pass\nelse:\n ...\n\nwhile x and y:\n ...\n print('Hello World!')\n\nelse:\n print('Olá, Mundo!')\n ...\n\nwhile a := b: ...\nwhile (a := b) and c: ...\nwhile lambda x: x: ...\nwhile await x: ...\n\nif True:\n while x:\n pass\n else:\n pass\nelse:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/while.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.12","idiom_id":"annotated","pep":"593","introduced_in":"3.9","form":"modern","file":"annotated/modern_01.py","code":"\"\"\"\nTests the typing.Annotated special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#annotated\n\n# > The first argument to Annotated must be a valid type\n\nfrom dataclasses import InitVar, dataclass\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Literal,\n NotRequired,\n Required,\n TypeAlias,\n TypeVar,\n TypedDict,\n Union,\n)\n\nT = TypeVar(\"T\")\n\n\nGood1: Annotated[Union[int, str], \"\"]\nGood2: Annotated[int | None, \"\"]\nGood3: Annotated[list[int], \"\"]\nGood4: Annotated[Any, \"\"]\nGood5: Annotated[tuple[int, ...] | list[int], \"\"]\nGood6: Annotated[Callable[..., int], \"\"]\nGood7: Annotated[\"int | str\", \"\"]\nGood8: Annotated[list[\"int | str\"], \"\"]\n\n\nBad1: Annotated[[int, str], \"\"] # E: invalid type expression\nBad2: Annotated[((int, str),), \"\"] # E: invalid type expression\nBad3: Annotated[[int for i in range(1)], \"\"] # E: invalid type expression\nBad4: Annotated[{\"a\": \"b\"}, \"\"] # E: invalid type expression\nBad5: Annotated[(lambda: int)(), \"\"] # E: invalid type expression\nBad6: Annotated[[int][0], \"\"] # E: invalid type expression\nBad7: Annotated[int if 1 < 3 else str, \"\"] # E: invalid type expression\nBad8: Annotated[var1, \"\"] # E: invalid type expression\nBad9: Annotated[True, \"\"] # E: invalid type expression\nBad10: Annotated[1, \"\"] # E: invalid type expression\nBad11: Annotated[list or set, \"\"] # E: invalid type expression\nBad12: Annotated[f\"{'int'}\", \"\"] # E: invalid type expression\n\n\n# > Multiple type annotations are supported (Annotated supports variadic arguments):\n\nMulti1: Annotated[int | str, 3, \"\"]\nMulti2: Annotated[int | str, 3, \"\", lambda x: x, max(1, 2)]\n\n# > Annotated must be called with at least two arguments ( Annotated[int] is not valid)\n\nBad13: Annotated[int] # E: requires at least two arguments\n\n\n# > Annotated types can be nested\n\nNested1: list[Annotated[dict[str, Annotated[str, \"\"]], \"\"]]\nNested2: Annotated[list[Annotated[dict[str, Annotated[Literal[1, 2, 3], \"\"]], \"\"]], \"\"]\n\n\n# > Annotated is not type compatible with type or type[T]\nSmallInt: TypeAlias = Annotated[int, \"\"]\n\nnot_type1: type[Any] = Annotated[int, \"\"] # E\nnot_type2: type[Any] = SmallInt # E\n\n\ndef func4(x: type[T]) -> T:\n return x()\n\n\nfunc4(Annotated[str, \"\"]) # E\nfunc4(SmallInt) # E\n\n\n# > An attempt to call Annotated (whether parameterized or not) should be\n# > treated as a type error by type checkers.\n\nAnnotated() # E\nAnnotated[int, \"\"]() # E\nSmallInt(1) # E\n\n\nclass ClassA:\n a: ClassVar[Annotated[int, \"\"]] = 1\n b: Annotated[ClassVar[int], \"\"] = 1\n c: Final[Annotated[int, \"\"]] = 1\n d: Annotated[Final[int], \"\"] = 1\n\n\n@dataclass\nclass ClassB:\n a: InitVar[Annotated[int, \"\"]]\n b: Annotated[InitVar[int], \"\"]\n\n\nclass ClassC(TypedDict):\n a: Annotated[Required[int], \"\"]\n b: Required[Annotated[int, \"\"]]\n c: Annotated[NotRequired[int], \"\"]\n d: NotRequired[Annotated[int, \"\"]]\n\n\nTA1: TypeAlias = Annotated[int | str, \"\"]\nTA2 = Annotated[Literal[1, 2], \"\"]\nTA3 = Annotated[T, \"\"]\n","source":"typing_tests","origin":"conformance/tests/qualifiers_annotated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_07.py","code":"\"\"\"\nTests the handling of builtins.type[T].\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#type\n\n\nfrom typing import Any, Callable, Generic, Type, TypeAlias, TypeVar, assert_type\n\n\nclass User:\n ...\n\n\nclass BasicUser(User):\n ...\n\n\nclass ProUser(User):\n ...\n\n\nclass TeamUser(User):\n ...\n\n\ndef func1(user_class: type) -> User:\n return user_class()\n\n\ndef func2(user_class: type[User]) -> User:\n return user_class()\n\n\nU = TypeVar(\"U\", bound=User)\n\n\ndef func3(user_class: type[U]) -> U:\n return user_class()\n\n\nassert_type(func1(TeamUser), User)\nassert_type(func2(TeamUser), User)\nassert_type(func3(TeamUser), TeamUser)\n\n\n# > Note that it is legal to use a union of classes as the parameter for type[].\n\n\ndef func4(user_class: type[BasicUser | ProUser]) -> User:\n return user_class()\n\n\nassert_type(func4(BasicUser), User)\nassert_type(func4(ProUser), User)\nfunc4(TeamUser) # E\n\n\n# > Any other special constructs like Callable are not allowed as an argument to type.\n\nT = TypeVar(\"T\")\n\n\ndef func5(x: type[T]) -> None:\n pass\n\n\nfunc5(User) # OK\nfunc5(tuple) # OK\nfunc5(Callable) # E\n\n\n# > When type is parameterized it requires exactly one parameter. Plain type\n# > without brackets, the root of Python’s metaclass hierarchy, is equivalent to type[Any].\n\nbad_type1: type[int, str] # E\n\n\nclass MyMetaA(type):\n ...\n\n\ndef func6(a: type, b: type[Any]):\n assert_type(a, type[Any])\n a = b # OK\n b = a # OK\n a = type # OK\n b = type # OK\n\n\n# > Regarding the behavior of type[Any] (or type), accessing attributes of a\n# > variable with this type only provides attributes and methods defined by\n# > type (for example, __repr__() and __mro__). Such a variable can be called\n# > with arbitrary arguments, and the return type is Any.\n\n\ndef func7(a: type, b: type[Any], c: Type, d: Type[Any]):\n assert_type(a.__mro__, tuple[type, ...])\n assert_type(a.unknown, Any)\n assert_type(a.unknown(), Any)\n\n assert_type(b.__mro__, tuple[type, ...])\n assert_type(b.unknown, Any)\n assert_type(b.unknown(), Any)\n\n assert_type(c.__mro__, tuple[type, ...])\n assert_type(c.unknown, Any)\n assert_type(c.unknown(), Any)\n\n assert_type(d.__mro__, tuple[type, ...])\n assert_type(d.unknown, Any)\n assert_type(d.unknown(), Any)\n\n\ndef func8(a: type[object], b: Type[object]):\n assert_type(a.__name__, str)\n a.unknown # E\n\n assert_type(b.__name__, str)\n b.unknown # E\n\n\n# > type is covariant in its parameter, because type[Derived] is a subtype of type[Base]:\n\n\ndef func9(pro_user_class: type[ProUser]):\n assert_type(func3(pro_user_class), ProUser)\n\n\nTA1: TypeAlias = Type\nTA2: TypeAlias = Type[Any]\nTA3: TypeAlias = type\nTA4: TypeAlias = type[Any]\n\n\ndef func10(a: TA1, b: TA2, c: TA3, d: TA4):\n assert_type(a, type[Any])\n assert_type(b, type[Any])\n assert_type(c, type[Any])\n assert_type(d, type[Any])\n\n\nTA1.unknown # E\nTA2.unknown # E\nTA3.unknown # E\nTA4.unknown # E\n\nTA7: TypeAlias = type[T]\nTA8: TypeAlias = Type[T]\n\n\ndef func11(t1: TA7[T]) -> T:\n return t1()\n\n\ndef func12(t1: TA8[T]) -> T:\n return t1()\n\n\nassert_type(func11(int), int)\nassert_type(func12(int), int)\n\n\ndef func13(v: type):\n x1: Callable[..., Any] = v # OK\n x2: Callable[[int, int], int] = v # OK\n x3: object = v # OK\n x4: type = v # OK\n x5: type[int] = v # OK\n x6: type[Any] = v # OK\n\n\nclass ClassA(Generic[T]):\n def method1(self, v: type) -> type[T]:\n return v # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_type.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_08.py","code":"\"\"\"\nTests the handling of builtins.tuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#tuple-type-form\n\n# > The type of a tuple can be expressed by listing the element types.\nfrom typing import Literal\n\n\nt1: tuple[int] = (1,) # OK\nt1 = (1, 2) # E\nt2: tuple[int, int] = (1, 2) # OK\nt2 = (1,) # E\nt2 = (1, \"\") # E\n\n\ndef func1() -> tuple[Literal[1], Literal[2]]:\n return (1, 2)\n\n\n# > The empty tuple can be typed as tuple[()].\n\nt10: tuple[()] = () # OK\nt10 = (1,) # E\n\n\ndef func2() -> list[tuple[()]]:\n return [(), (), ()]\n\n\n# > Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis.\nt20: tuple[int, ...] = () # OK\nt20 = (1,) # OK\nt20 = (1, 2, 3, 4) # OK\nt20 = (1, 2, 3, \"\") # E\n\n\nt30: tuple[int, ...] # OK\nt31: tuple[int, int, ...] # E\nt32: tuple[...] # E\nt33: tuple[..., int] # E\nt34: tuple[int, ..., int] # E\nt35: tuple[*tuple[str], ...] # E\nt36: tuple[*tuple[str, ...], ...] # E\n","source":"typing_tests","origin":"conformance/tests/tuples_type_form.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_01.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a base class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Generic, TypeVar, dataclass_transform\n\nT = TypeVar(\"T\")\n\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelBase:\n not_a_field: str\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n def __init__(self, not_a_field: str) -> None:\n self.not_a_field = not_a_field\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen dataclass cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass GenericModelBase(Generic[T]):\n not_a_field: T\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass GenericCustomer(GenericModelBase[int]):\n id: int = model_field()\n\n\ngc_1 = GenericCustomer(id=3)\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelBaseFrozen:\n not_a_field: str\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_02.py","code":"\"\"\"\nTests the dataclass_transform mechanism supports the \"converter\" parameter\nin a field specifier class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#converters\n\nfrom typing import (\n Any,\n Callable,\n TypeVar,\n dataclass_transform,\n overload,\n)\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n\ndef model_field(\n *,\n converter: Callable[[S], T],\n default: S | None = None,\n default_factory: Callable[[], S] | None = None,\n) -> T:\n raise NotImplementedError\n\n\n@dataclass_transform(field_specifiers=(model_field,))\nclass ModelBase:\n ...\n\n\n# > The converter must be a callable that must accept a single positional\n# > argument (but may accept other optional arguments, which are ignored for\n# > typing purposes).\n\n\ndef bad_converter1() -> int:\n return 0\n\n\ndef bad_converter2(*, x: int) -> int:\n return 0\n\n\nclass DC1(ModelBase):\n field1: int = model_field(converter=bad_converter1) # E\n field2: int = model_field(converter=bad_converter2) # E\n\n\n# > The type of the first positional parameter provides the type of the\n# > synthesized __init__ parameter for the field.\n\n# > The return type of the callable must be assignable to the field’s\n# > declared type.\n\n\ndef converter_simple(s: str) -> int:\n return int(s)\n\n\ndef converter_with_param_before_args(s: str, *args: int, **kwargs: int) -> int:\n return int(s)\n\n\ndef converter_with_args(*args: str) -> int:\n return int(args[0])\n\n\n@overload\ndef overloaded_converter(s: str) -> int:\n ...\n\n\n@overload\ndef overloaded_converter(s: list[str]) -> int:\n ...\n\n\ndef overloaded_converter(s: str | list[str], *args: str) -> int | str:\n return 0\n\n\nclass ConverterClass:\n @overload\n def __init__(self, val: str) -> None:\n ...\n\n @overload\n def __init__(self, val: bytes) -> None:\n ...\n\n def __init__(self, val: str | bytes) -> None:\n pass\n\n\nclass DC2(ModelBase):\n field0: int = model_field(converter=converter_simple)\n field1: int = model_field(converter=converter_with_param_before_args)\n field2: int = model_field(converter=converter_with_args)\n field3: ConverterClass = model_field(converter=ConverterClass)\n field4: int = model_field(converter=overloaded_converter)\n field5: dict[str, str] = model_field(converter=dict, default=())\n\n\nDC2(1, \"f1\", \"f2\", b\"f3\", []) # E\nDC2(\"f0\", \"f1\", \"f2\", 1, []) # E\nDC2(\"f0\", \"f1\", \"f2\", \"f3\", 3j) # E\n\n\ndc1 = DC2(\"f0\", \"f1\", \"f2\", b\"f6\", [])\n\ndc1.field0 = \"f1\"\ndc1.field3 = \"f6\"\ndc1.field3 = b\"f6\"\n\ndc1.field0 = 1 # E\ndc1.field3 = 1 # E\n\ndc2 = DC2(\"f0\", \"f1\", \"f2\", \"f6\", \"1\", ((\"a\", \"1\"), (\"b\", \"2\")))\n\n\n# > If default or default_factory are provided, the type of the default value\n# > should be assignable to the first positional parameter of the converter.\n\n\nclass DC3(ModelBase):\n field0: int = model_field(converter=converter_simple, default=\"\")\n field1: int = model_field(converter=converter_simple, default=1) # E\n\n field2: int = model_field(converter=converter_simple, default_factory=str)\n field3: int = model_field(converter=converter_simple, default_factory=int) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_converter.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_03.py","code":"\"\"\"\nTests the dataclass_transform mechanism honors implicit default values\nin field parameters.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#field-specifier-parameters\n\nfrom typing import Any, Callable, Literal, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n# > Field specifier functions can use overloads that implicitly specify the\n# > value of init using a literal bool value type (Literal[False] or Literal[True]).\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any],\n init: Literal[False] = False,\n) -> Any:\n ...\n\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: None = None,\n init: Literal[True] = True,\n) -> Any:\n ...\n\n\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any] | None = None,\n init: bool = True,\n) -> Any:\n ...\n\n\ndef field2(*, init: bool = False, kw_only: bool = True) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(kw_only_default=True, field_specifiers=(field1, field2))\ndef create_model(*, init: bool = True) -> Callable[[type[T]], type[T]]:\n raise NotImplementedError\n\n\n@create_model()\nclass CustomerModel1:\n id: int = field1(resolver=lambda: 0)\n name: str = field1(default=\"Voldemort\")\n\n\nCustomerModel1()\nCustomerModel1(name=\"hi\")\n\n# This should generate an error because \"id\" is not\n# supposed to be part of the init function.\nCustomerModel1(id=1, name=\"hi\") # E\n\n\n@create_model()\nclass CustomerModel2:\n id: int = field2()\n name: str = field2(init=True)\n\n\n# This should generate an error because kw_only is True\n# by default for field2.\nCustomerModel2(1) # E\n\nCustomerModel2(name=\"Fred\")\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_field.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_04.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a decorator function.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Callable, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n\n@overload\n@dataclass_transform(kw_only_default=True, order_default=True)\ndef create_model(cls: T) -> T:\n ...\n\n\n@overload\ndef create_model(\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n) -> Callable[[T], T]:\n ...\n\n\ndef create_model(*args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n\n@create_model(kw_only=False, order=False)\nclass Customer1:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2Subclass(Customer2):\n salary: float\n\n\nc1_1 = Customer1(id=3, name=\"Sue\")\nc1_1.id = 4\n\nc1_2 = Customer1(3, \"Sue\")\nc1_2.name = \"Susan\"\n\n# This should generate an error because of a type mismatch.\nc1_2.name = 3 # E\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\n# This should generate an error because salary is not\n# a defined field.\nc1_3 = Customer1(id=3, name=\"Sue\", salary=40000) # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_2 = Customer2(0, \"John\") # E\n\nv2 = c2_1 < c2_2\n\n\n@dataclass_transform(kw_only_default=True, order_default=True, frozen_default=True)\ndef create_model_frozen(cls: T) -> T:\n raise NotImplementedError\n\n\n@create_model_frozen\nclass Customer3:\n id: int\n name: str\n\n\n# This should generate an error because a non-frozen class\n# cannot inherit from a frozen class.\n@create_model # E[Customer3Subclass]\nclass Customer3Subclass(Customer3): # E[Customer3Subclass]\n age: int\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_func.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_05.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a metaclass.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\n\nfrom typing import Any, dataclass_transform\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelMeta(type):\n not_a_field: str\n\n def __init__(self, *args, **kwargs) -> None:\n self.not_a_field: str = \"not a field\"\n\n\nclass ModelBase(metaclass=ModelMeta):\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen class cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1, frozen=False): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\n# OK (other_name is optional).\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelMetaFrozen(type):\n pass\n\n\nclass ModelBaseFrozen(metaclass=ModelMetaFrozen):\n ...\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_meta.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_07.py","code":"\"\"\"\nTests the handling of descriptors within a dataclass.\n\"\"\"\n\n# This portion of the dataclass spec is under-specified in the documentation,\n# but its behavior can be determined from the runtime implementation.\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, TypeVar, assert_type, overload\n\nT = TypeVar(\"T\")\n\n\nclass Desc1:\n @overload\n def __get__(self, __obj: None, __owner: Any) -> \"Desc1\":\n ...\n\n @overload\n def __get__(self, __obj: object, __owner: Any) -> int:\n ...\n\n def __get__(self, __obj: object | None, __owner: Any) -> \"int | Desc1\":\n raise NotImplementedError\n\n def __set__(self, __obj: object, __value: int) -> None:\n ...\n\n\n@dataclass\nclass DC1:\n y: Desc1 = Desc1()\n\n\ndc1 = DC1(3)\n\nassert_type(dc1.y, int)\nassert_type(DC1.y, Desc1)\n\n\nclass Desc2(Generic[T]):\n @overload\n def __get__(self, instance: None, owner: Any) -> list[T]:\n ...\n\n @overload\n def __get__(self, instance: object, owner: Any) -> T:\n ...\n\n def __get__(self, instance: object | None, owner: Any) -> list[T] | T:\n raise NotImplementedError\n\n\n@dataclass\nclass DC2:\n x: Desc2[int]\n y: Desc2[str]\n z: Desc2[str] = Desc2()\n\n\nassert_type(DC2.x, list[int])\nassert_type(DC2.y, list[str])\nassert_type(DC2.z, list[str])\n\ndc2 = DC2(Desc2(), Desc2(), Desc2())\nassert_type(dc2.x, int)\nassert_type(dc2.y, str)\nassert_type(dc2.z, str)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_descriptors.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_08.py","code":"\"\"\"\nTests validation of frozen dataclass instances.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#frozen-instances\n\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass DC1:\n a: float\n b: str\n\ndc1 = DC1(1, \"\")\n\ndc1.a = 1 # E: dataclass is frozen\ndc1.b = \"\" # E: dataclass is frozen\n\n\n# This should generate an error because a non-frozen dataclass\n# cannot inherit from a frozen dataclass.\n@dataclass # E[DC2]\nclass DC2(DC1): # E[DC2]\n pass\n\n@dataclass\nclass DC3:\n a: int\n\n# This should generate an error because a frozen dataclass\n# cannot inherit from a non-frozen dataclass.\n@dataclass(frozen=True) # E[DC4]\nclass DC4(DC3): # E[DC4]\n pass\n\n\n@dataclass(frozen=True)\nclass DC1Child(DC1):\n # This should be allowed because attributes within a frozen\n # dataclass are covariant rather than invariant.\n a: int\n","source":"typing_tests","origin":"conformance/tests/dataclasses_frozen.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_09.py","code":"\"\"\"\nTests the synthesis of the __hash__ method in a dataclass.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Callable, Hashable, assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n\n\nassert_type(DC1.__hash__, None)\n\n# These should generate errors because DC1 isn't hashable.\nDC1(0).__hash__() # E\nv1: Hashable = DC1(0) # E\n\n\n@dataclass(eq=True, frozen=True)\nclass DC2:\n a: int\n\n\ndc2_hash: Callable[..., int] = DC2.__hash__ # OK\nDC2(0).__hash__() # OK\nv2: Hashable = DC2(0) # OK\n\n\n@dataclass(eq=True)\nclass DC3:\n a: int\n\n\nassert_type(DC3.__hash__, None)\n\n# These should generate errors because DC3 isn't hashable.\nDC3(0).__hash__() # E\nv3: Hashable = DC3(0) # E\n\n\n@dataclass(frozen=True)\nclass DC4:\n a: int\n\n\ndc4_hash: Callable[..., int] = DC4.__hash__ # OK\nDC4(0).__hash__() # OK\nv4: Hashable = DC4(0) # OK\n\n\n@dataclass(eq=True, unsafe_hash=True)\nclass DC5:\n a: int\n\n\ndc5_hash: Callable[..., int] = DC5.__hash__ # OK\nDC5(0).__hash__() # OK\nv5: Hashable = DC5(0) # OK\n\n\n@dataclass(eq=True)\nclass DC6:\n a: int\n\n def __hash__(self) -> int:\n return 0\n\n\ndc6_hash: Callable[..., int] = DC6.__hash__ # OK\nDC6(0).__hash__() # OK\nv6: Hashable = DC6(0) # OK\n\n\n@dataclass(frozen=True)\nclass DC7:\n a: int\n\n def __eq__(self, other) -> bool:\n return self.a == other.a\n\n\ndc7_hash: Callable[..., int] = DC7.__hash__ # OK\nDC7(0).__hash__() # OK\nv7: Hashable = DC7(0) # OK\n","source":"typing_tests","origin":"conformance/tests/dataclasses_hash.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_10.py","code":"\"\"\"\nTests inheritance rules for dataclasses.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#inheritance\n\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar\n\n\n@dataclass\nclass DC1:\n a: int\n b: str = \"\"\n\n\n@dataclass\nclass DC2(DC1):\n b: str = \"\"\n a: int = 1\n\n\ndc2_1 = DC2(1, \"\")\n\ndc2_2 = DC2()\n\n\n@dataclass\nclass DC3:\n x: float = 15.0\n y: str = \"\"\n\n\n@dataclass\nclass DC4(DC3):\n z: tuple[int] = (10,)\n x: float = 15\n\n\ndc4_1 = DC4(0.0, \"\", (1,))\n\n\n@dataclass\nclass DC5:\n # While this generates an error at runtime for the stdlib dataclass,\n # other libraries that use dataclass_transform don't have similar\n # restrictions. It is therefore not required that a type checker\n # report an error here.\n x: list[int] = [] # E?\n\n\n@dataclass\nclass DC6:\n x: int\n y: ClassVar[int] = 1\n\n\n@dataclass\nclass DC7(DC6):\n # This should generate an error because a ClassVar cannot override\n # an instance variable of the same name.\n x: ClassVar[int] # E\n\n # This should generate an error because an instance variable cannot\n # override a class variable of the same name.\n y: int # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_11.py","code":"\"\"\"\nTests the keyword-only feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY, field\n\n\n@dataclass\nclass DC1:\n a: str\n _: KW_ONLY\n b: int = 0\n\n\nDC1(\"hi\")\nDC1(a=\"hi\")\nDC1(a=\"hi\", b=1)\nDC1(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC1(\"hi\", 1) # E\n\n\n@dataclass\nclass DC2:\n b: int = field(kw_only=True, default=3)\n a: str\n\n\nDC2(\"hi\")\nDC2(a=\"hi\")\nDC2(a=\"hi\", b=1)\nDC2(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC2(\"hi\", 1) # E\n\n\n@dataclass(kw_only=True)\nclass DC3:\n a: str = field(kw_only=False)\n b: int = 0\n\n\nDC3(\"hi\")\nDC3(a=\"hi\")\nDC3(a=\"hi\", b=1)\nDC3(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC3(\"hi\", 1) # E\n\n\n@dataclass\nclass DC4(DC3):\n c: float\n\n\nDC4(\"\", 0.2, b=3)\nDC4(a=\"\", b=3, c=0.2)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_kwonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_12.py","code":"\"\"\"\nTests the match_args feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY\nfrom typing import assert_type, Literal\n\n# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method\n\n@dataclass(match_args=True)\nclass DC1:\n x: int\n _: KW_ONLY\n y: str\n\nassert_type(DC1.__match_args__, tuple[Literal['x']])\n\n# The match_args default is True\n\n@dataclass\nclass DC2:\n x: int\n\nassert_type(DC2.__match_args__, tuple[Literal['x']])\n\n# __match_args__ is created even if __init__() is not generated\n\n@dataclass(match_args=True, init=False)\nclass DC3:\n x: int = 0\n\nassert_type(DC3.__match_args__, tuple[Literal['x']])\n\n# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.\n\n@dataclass(match_args=False)\nclass DC4:\n x: int\n\nDC4.__match_args__ # E\n\n@dataclass(match_args=True)\nclass DC5:\n __match_args__ = ()\n x: int\n\nassert_type(DC5.__match_args__, tuple[()])\n","source":"typing_tests","origin":"conformance/tests/dataclasses_match_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_13.py","code":"\"\"\"\nTests the synthesized comparison methods for dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass DC1:\n a: str\n b: int\n\n\n@dataclass(order=True)\nclass DC2:\n a: str\n b: int\n\n\ndc1_1 = DC1(\"\", 0)\ndc1_2 = DC1(\"\", 0)\n\nif dc1_1 < dc1_2:\n pass\n\nif dc1_1 <= dc1_2:\n pass\n\nif dc1_1 > dc1_2:\n pass\n\nif dc1_1 >= dc1_2:\n pass\n\nif dc1_1 == dc1_2:\n pass\n\nif dc1_1 != dc1_2:\n pass\n\nif dc1_1 == None:\n pass\n\nif dc1_1 != None:\n pass\n\ndc2_1 = DC2(\"hi\", 2)\n\n# This should generate an error because the types are\n# incompatible.\nif dc1_1 < dc2_1: # E:\n pass\n\nif dc1_1 != dc2_1:\n pass\n","source":"typing_tests","origin":"conformance/tests/dataclasses_order.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_14.py","code":"\"\"\"\nTests type checking of the __post_init__ method in a dataclass.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#post-init-processing\n\nfrom dataclasses import InitVar, dataclass, field, replace\nfrom typing import assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n b: int\n x: InitVar[int]\n c: int\n y: InitVar[str]\n\n def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y\n pass\n\n\ndc1 = DC1(1, 2, 3, 4, \"\")\n\nassert_type(dc1.a, int)\nassert_type(dc1.b, int)\nassert_type(dc1.c, int)\nprint(dc1.x) # E: cannot access InitVar\nprint(dc1.y) # E: cannot access InitVar\n\n@dataclass\nclass DC2:\n x: InitVar[int]\n y: InitVar[str]\n\n def __post_init__(self, x: int) -> None: # E: missing y\n pass\n\n\n@dataclass\nclass DC3:\n _name: InitVar[str] = field()\n name: str = field(init=False)\n\n def __post_init__(self, _name: str):\n ...\n\n\n@dataclass\nclass DC4(DC3):\n _age: InitVar[int] = field()\n age: int = field(init=False)\n\n def __post_init__(self, _name: str, _age: int):\n ...\n","source":"typing_tests","origin":"conformance/tests/dataclasses_postinit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_15.py","code":"\"\"\"\nTests the slots functionality of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass\n\n# This should generate an error because __slots__ is already defined.\n@dataclass(slots=True) # E[DC1]\nclass DC1: # E[DC1]\n x: int\n\n __slots__ = ()\n\n\n@dataclass(slots=True)\nclass DC2:\n x: int\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass(slots=False)\nclass DC3:\n x: int\n\n __slots__ = (\"x\",)\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass\nclass DC4:\n __slots__ = (\"y\", \"x\")\n x: int\n y: str\n\n\nDC4(1, \"bar\")\n\n\n@dataclass(slots=True)\nclass DC5:\n a: int\n\n\nDC5.__slots__\nDC5(1).__slots__\n\n\n@dataclass\nclass DC6:\n a: int\n\n\n# This should generate an error because __slots__ is not defined.\nDC6.__slots__ # E\n\n# This should generate an error because __slots__ is not defined.\nDC6(1).__slots__ # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_slots.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_16.py","code":"\"\"\"\nTests basic handling of the dataclass factory.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html\n# Also, see https://peps.python.org/pep-0557/\n\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar, assert_type\nimport sys\n\nT = TypeVar(\"T\")\n\n\n@dataclass(order=True)\nclass InventoryItem:\n x = 0\n name: str\n unit_price: float\n quantity_on_hand: int = 0\n\n def total_cost(self) -> float:\n return self.unit_price * self.quantity_on_hand\n\n\nv1 = InventoryItem(\"soap\", 2.3)\n\n\nclass InventoryItemInitProto(Protocol):\n def __call__(\n self, name: str, unit_price: float, quantity_on_hand: int = ...\n ) -> None: ...\n\n\n# Validate the type of the synthesized __init__ method.\nx1: InventoryItemInitProto = v1.__init__\n\n# Make sure the following additional methods were synthesized.\nprint(v1.__repr__)\nprint(v1.__eq__)\nprint(v1.__ne__)\nprint(v1.__lt__)\nprint(v1.__le__)\nprint(v1.__gt__)\nprint(v1.__ge__)\n\nassert_type(v1.name, str)\nassert_type(v1.unit_price, float)\nassert_type(v1.quantity_on_hand, int)\n\nv2 = InventoryItem(\"name\") # E: missing unit_price\nv3 = InventoryItem(\"name\", \"price\") # E: incorrect type for unit_price\nv4 = InventoryItem(\"name\", 3.1, 3, 4) # E: too many arguments\n\n\n# > TypeError will be raised if a field without a default value follows a\n# > field with a default value. This is true either when this occurs in a\n# > single class, or as a result of class inheritance.\n@dataclass # E[DC1]\nclass DC1:\n a: int = 0 # E[DC1]: field with default should follow a field with no default.\n b: int # E[DC1]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC2]\nclass DC2:\n a: int = field(default=1) # E[DC2]: field with default should follow a field with no default.\n b: int # E[DC2]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC3]\nclass DC3:\n a: InitVar[int] = 0 # E[DC3]: field with default should follow a field with no default.\n b: int # E[DC3]: field with no default cannot follow field with default.\n\n\n@dataclass\nclass DC4:\n a: int = field(init=False)\n b: int\n\n\nv5 = DC4(0)\nv6 = DC4(0, 1) # E: too many parameters\n\n\n@dataclass\nclass DC5:\n a: int = field(default_factory=str) # E: type mismatch\n\n\ndef f(s: str) -> int:\n return int(s)\n\n\n@dataclass\nclass DC6:\n a: ClassVar[int] = 0\n b: str\n c: Callable[[str], int] = f\n\n\ndc6 = DC6(\"\")\nassert_type(dc6.a, int)\nassert_type(DC6.a, int)\nassert_type(dc6.b, str)\nassert_type(dc6.c, Callable[[str], int])\n\n\n@dataclass\nclass DC7:\n x: int\n\n\n@dataclass(init=False)\nclass DC8(DC7):\n y: int\n\n def __init__(self, a: DC7, y: int):\n self.__dict__ = a.__dict__\n self.y = y\n\n\na = DC7(3)\nb = DC8(a, 5)\n\n# This should generate an error because there is an extra parameter\nDC7(3, 4) # E\n\n# This should generate an error because there is one too few parameters\nDC8(a) # E\n\n\n@dataclass\nclass DC9:\n a: str = field(init=False, default=\"s\")\n b: bool = field()\n\n\n@dataclass\nclass DC10(DC9):\n a: str = field()\n b: bool = field()\n\n\n@dataclass(init=False)\nclass DC11:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC11(3)\n\n\n@dataclass(init=True)\nclass DC12:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC12(3)\n\n\n@dataclass(init=False)\nclass DC13:\n x: int\n x_squared: int\n\n\n# This should generate an error because there is no matching\n# override __init__ method and no synthesized __init__.\nDC13(3) # E\n\n\n@dataclass\nclass DC14:\n prop_1: str = field(init=False)\n prop_2: str = field(default=\"hello\")\n prop_3: str = field(default_factory=lambda: \"hello\")\n\n\n@dataclass\nclass DC15(DC14):\n prop_2: str = \"\"\n\n\ndc15 = DC15(prop_2=\"test\")\n\nassert_type(dc15.prop_1, str)\nassert_type(dc15.prop_2, str)\nassert_type(dc15.prop_3, str)\n\n\nclass DataclassProto(Protocol):\n __dataclass_fields__: ClassVar[dict[str, Any]]\n\n\nv7: DataclassProto = dc15\n\n\n@dataclass\nclass DC16(Generic[T]):\n value: T\n\n\nassert_type(DC16(1), DC16[int])\n\n\nclass DC17(DC16[str]):\n pass\n\n\nassert_type(DC17(\"\"), DC17)\n\n\n@dataclass\nclass DC18:\n x: int = field()\n # This may generate a type checker error because an unannotated field\n # will result in a runtime exception.\n y = field() # E?\n\n\n# > Dataclass fields may be conditional, via checks of the same\n# > statically-known conditions that a type-checker understands elsewhere,\n# > such as Python version:\n\n@dataclass\nclass DC19:\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nDC19(1, 2)\nDC19(1, 2, 3) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_01.py","code":"\"\"\"\nTests the handling of ClassVar and Final in dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import assert_type, ClassVar, Final\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#dataclass-semantics\n\n# > A final class variable on a dataclass must be explicitly annotated as\n# e.g. x: ClassVar[Final[int]] = 3.\n\n\n@dataclass\nclass D:\n final_no_default: Final[int]\n final_with_default: Final[str] = \"foo\"\n final_classvar: ClassVar[Final[int]] = 4\n # we don't require support for Final[ClassVar[...]] because the dataclasses\n # runtime implementation won't recognize it as a ClassVar either\n\n\n# An explicitly marked ClassVar can be accessed on the class:\nassert_type(D.final_classvar, int)\n\n# ...but not assigned to, because it's Final:\nD.final_classvar = 10 # E: can't assign to final attribute\n\n# A non-ClassVar attribute (with or without default) is a dataclass field:\nd = D(final_no_default=1, final_with_default=\"bar\")\nassert_type(d.final_no_default, int)\nassert_type(d.final_with_default, str)\n\n# ... but can't be assigned to (on the class or on an instance):\nd.final_no_default = 10 # E: can't assign to final attribute\nd.final_with_default = \"baz\" # E: can't assign to final attribute\nD.final_no_default = 10 # E: can't assign to final attribute\nD.final_with_default = \"baz\" # E: can't assign to final attribute\n","source":"typing_tests","origin":"conformance/tests/dataclasses_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_02.py","code":"\"\"\"\nTests the typing.Final special form.\n\"\"\"\n\nfrom typing import ClassVar, Final, Literal, NamedTuple, TypedDict, assert_type\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#id1\n\nID1: Final[int] = 1\n\nID2: Final = 1\nassert_type(ID2, Literal[1])\n\n# > If the right hand side is omitted, there must be an explicit type argument to Final.\n\nBAD1: Final # E: missing assignment\n\nBAD2: Final[str, int] = \"\" # E: only one type argument allowed\n\n# > There can be at most one final declaration per module or class for a given\n# > attribute.\n\n# > As self.id: Final = 1 (also optionally with a type in square brackets).\n# > This is allowed only in __init__ methods, so that the final instance\n# > attribute is assigned only once when an instance is created.\n\n\nclass ClassA:\n ID1: Final = 1\n\n # > In class bodies and stub files you can omit the right hand side and just\n # > write ID: Final[float]. If the right hand side is omitted, there must be\n # > an explicit type argument to Final.\n ID2: Final # E: missing initialization\n\n # > A final attribute declared in a class body without an initializer must\n # > be initialized in the __init__ method (except in stub files):\n ID3: Final[int] # E: missing initialization\n\n ID4: Final[int] # OK because initialized in __init__\n\n ID5: Final[int] = 0\n\n ID6: Final[int]\n\n ID7: Final[int] = 0\n\n def __init__(self, cond: bool) -> None:\n self.id1: Final = 1\n self.id2: Final[int] = 1\n\n self.ID4 = 1\n\n self.ID5 = 0 # E: Already initialized\n\n if cond:\n self.ID6 = 1\n else:\n self.ID6 = 2\n\n def method1(self) -> None:\n self.id3: Final = 1 # E: not allowed outside of __init__ method.\n self.id4: Final[int] = 1 # E: not allowed outside of __init__ method.\n\n self.ID7 = 0 # E: cannot modify Final value\n\n self.ID7 += 1 # E: cannot modify Final value\n\n\nRATE: Final = 3000\nRATE = 300 # E: Cannot redefine Final value\n\n# > There can’t be separate class-level and instance-level constants\n# > with the same name.\n\n\nclass ClassB:\n DEFAULT_ID: Final = 0\n\n\nClassB.DEFAULT_ID = 0 # E: Cannot redefined value\n\n\n# > A type checker should prevent final attributes from being overridden in a subclass:\n\n\nclass ClassC:\n BORDER_WIDTH: Final = 2.5\n\n __private: Final = 0\n\n\nclass ClassCChild(ClassC):\n BORDER_WIDTH = 2.5 # E: Cannot override Final value\n\n __private = 0 # OK\n\n\n# > Type checkers should infer a final attribute that is initialized in a class\n# > body as being a class variable. Variables should not be annotated with both\n# > ClassVar and Final. (Except in a dataclass; see dataclasses_final.py.)\n\n\nclass ClassD:\n VALUE1: Final = 1\n\n VALUE2: ClassVar[Final] = 1 # E: Final cannot be used with ClassVar\n VALUE3: Final[ClassVar] = 1 # E: Final cannot be used with ClassVar\n\n\nClassD.VALUE1 # OK\n\n\n# > Final may only be used as the outermost type in assignments or variable\n# > annotations. Using it in any other position is an error. In particular,\n# > Final can’t be used in annotations for function arguments.\n\nx: list[Final[int]] = [] # E\n\n\ndef func1(x: Final[list[int]]) -> None: # E\n ...\n\n\n# > ``Final`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithFinal(TypedDict):\n a: int\n b: Final[int] # E: Final not allowed in a TypedDict\n\n\nclass NTWithFinal(NamedTuple):\n a: int\n b: Final[int] # E: Final not allowed in a NamedTuple\n\n\n# > Type checkers should treat uses of a final name that was initialized with\n# > a literal as if it was replaced by the literal. For example, the following\n# > should be allowed:\n\nX: Final = \"x\"\nY: Final = \"y\"\nN = NamedTuple(\"N\", [(X, int), (Y, int)])\n\nN(x=3, y=4) # OK\nN(a=1) # E\nN(x=\"\", y=\"\") # E\n\n\ndef func2() -> None:\n global ID1\n\n ID1 = 2 # E: cannot modify Final value\n\n x: Final = 3\n\n x += 1 # E: cannot modify Final value\n\n a = (x := 4) # E: cannot modify Final value\n\n for x in [1, 2, 3]: # E: cannot modify Final value\n pass\n\n with open(\"FileName\") as x: # E: cannot modify Final value\n pass\n\n (a, x) = (1, 2) # E: cannot modify Final value\n\n\n# > If a module declares a ``Final`` variable and another module imports that\n# > variable in an import statement by name or wildcard, the imported symbol\n# > inherits the ``Final`` type qualifier. Any attempt to assign a different value\n# > to this symbol should be flagged as an error by a type checker.\n\n\nfrom _qualifiers_final_annotation_1 import TEN\n\nTEN = 9 # E: Cannot redefine Final value\n\nfrom _qualifiers_final_annotation_2 import *\n\nPI = 3.14159 # E: Cannot redefine Final value\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_03.py","code":"\"\"\"\nTests the @final decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#final\n\nfrom typing import final, overload\nfrom _qualifiers_final_decorator import Base3, Base4\n\n# > A type checker should prohibit any class decorated with @final from being\n# > subclassed and any method decorated with @final from being overridden in a\n# > subclass. The method decorator version may be used with all of instance\n# > methods, class methods, static methods, and properties.\n\n\n@final\nclass Base1:\n ...\n\n\nclass Derived1(Base1): # E: Cannot inherit from final class \"Base\"\n ...\n\n\nclass Base2:\n @final\n def method1(self) -> None:\n pass\n\n @final\n @classmethod\n def method2(cls) -> None:\n pass\n\n @final\n @staticmethod\n def method3() -> None:\n pass\n\n # > For overloaded methods, @final should be placed on the implementation.\n\n @overload\n def method4(self, x: int) -> int:\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @final\n def method4(self, x: int | str) -> int | str:\n return 0\n\n\nclass Derived2(Base2):\n def method1(self) -> None: # E\n pass\n\n @classmethod # E[method2]\n def method2(cls) -> None: # E[method2]\n pass\n\n @staticmethod # E[method3]\n def method3() -> None: # E[method3]\n pass\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n def method4(self, x: int | str) -> int | str: # E[method4]\n return 0\n\n\nclass Derived3(Base3):\n @overload # E[Derived3]\n def method(self, x: int) -> int: # E[Derived3]\n ...\n\n @overload # E[Derived3-2]\n @final # E[Derived3-2]: should be applied only to implementation\n def method(self, x: str) -> str: # E[Derived3-2]\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived3]\n return 0\n\n\nclass Derived4(Base4):\n @overload # E[Derived4]\n def method(self, x: int) -> int: # E[Derived4]\n ...\n\n @overload\n def method(self, x: str) -> str:\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived4]\n return 0\n\n\nclass Base5_1:\n ...\n\n\nclass Base5_2:\n @final\n def method(self, v: int) -> None:\n ...\n\n\n# Test multiple inheritance case.\nclass Derived5(Base5_1, Base5_2):\n def method(self) -> None: # E\n ...\n\n\n# > It is an error to use @final on a non-method function.\n\n\n@final # E[func]: not allowed on non-method function.\ndef func1() -> int: # E[func]\n return 0\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_decorator.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_04.py","code":"\"\"\"\nTests the use of Final values when used with TypedDicts.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#use-of-final-values-and-literal-types\n\nfrom typing import Final, Literal, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\n# > Type checkers should allow final names (PEP 591) with string values to be\n# > used instead of string literals in operations on TypedDict objects.\nYEAR: Final = \"year\"\n\nm: Movie = {\"name\": \"Alien\", \"year\": 1979}\nyears_since_epoch = m[YEAR] - 1970\n\n\n# > An expression with a suitable literal type (PEP 586) can be used instead of\n# > a literal value.\ndef get_value(movie: Movie, key: Literal[\"year\", \"name\"]) -> int | str:\n return movie[key]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"literal-string","pep":"675","introduced_in":"3.11","form":"modern","file":"literal-string/modern_01.py","code":"\"\"\"\nTests handling of the LiteralString special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#literalstring\n\n\nfrom typing import (\n Any,\n Generic,\n Literal,\n LiteralString,\n Sequence,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nvariable_annotation: LiteralString\n\n\ndef my_function(literal_string: LiteralString) -> LiteralString:\n raise NotImplementedError\n\n\nclass Foo:\n my_attribute: LiteralString = \"\"\n\n\ntype_argument: list[LiteralString]\n\nT = TypeVar(\"T\", bound=LiteralString)\n\n\nbad_union: Literal[\"hello\", LiteralString] # E\nbad_nesting: Literal[LiteralString] # E\n\n\ndef func1(a: Literal[\"one\"], b: Literal[\"two\"]):\n x1: LiteralString = a\n\n x2: Literal[\"\"] = b # E\n\n\ndef func2(a: LiteralString, b: LiteralString, non_literal: str):\n # > Addition: x + y is of type LiteralString if both x and y are compatible with LiteralString.\n assert_type(a + b, LiteralString)\n\n # > Joining: sep.join(xs) is of type LiteralString if sep’s type is\n # > compatible with LiteralString and xs’s type is compatible with Iterable[LiteralString].\n assert_type(\",\".join((a, b)), LiteralString)\n assert_type(\",\".join((a, non_literal)), str)\n\n # > In-place addition: If s has type LiteralString and x has type compatible with\n # > LiteralString, then s += x preserves s’s type as LiteralString.\n a += \"hello\"\n b += a\n\n # > String formatting: An f-string has type LiteralString if and only if its constituent\n # > expressions are literal strings. s.format(...) has type LiteralString if and only if\n # > s and the arguments have types compatible with LiteralString.\n assert_type(f\"{a} {b}\", LiteralString)\n\n x1: LiteralString = f\"{a} {non_literal}\" # E\n\n assert_type(a + non_literal, str)\n\n # > LiteralString is compatible with the type str\n x2: str = a\n\n # > Other literal types, such as literal integers, are not compatible with LiteralString.\n x3: LiteralString = 3 # E\n x4: LiteralString = b\"test\" # E\n\n\n# > Conditional statements and expressions work as expected.\ndef condition1() -> bool:\n raise NotImplementedError\n\n\ndef return_literal_string() -> LiteralString:\n return \"foo\" if condition1() else \"bar\" # OK\n\n\ndef return_literal_str2(literal_string: LiteralString) -> LiteralString:\n return \"foo\" if condition1() else literal_string # OK\n\n\ndef return_literal_str3() -> LiteralString:\n result: LiteralString\n if condition1():\n result = \"foo\"\n else:\n result = \"bar\"\n\n return result # OK\n\n\n# > TypeVars can be bound to LiteralString.\nTLiteral = TypeVar(\"TLiteral\", bound=LiteralString)\n\n\ndef literal_identity(s: TLiteral) -> TLiteral:\n return s\n\n\ndef func3(s: Literal[\"hello\"]):\n y = literal_identity(s)\n assert_type(y, Literal[\"hello\"])\n\n\ndef func4(s: LiteralString):\n y2 = literal_identity(s)\n assert_type(y2, LiteralString)\n\n\ndef func5(s: str):\n literal_identity(s) # E\n\n\n# > LiteralString can be used as a type argument for generic classes.\nclass Container(Generic[T]):\n def __init__(self, value: T) -> None:\n self.value = value\n\n\ndef func6(s: LiteralString):\n x: Container[LiteralString] = Container(s) # OK\n\n\ndef func7(s: str):\n x_error: Container[LiteralString] = Container(s) # E\n\n\n# > Standard containers like List work as expected.\nxs: list[LiteralString] = [\"foo\", \"bar\", \"baz\"]\n\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\n\n@overload\ndef func8(x: Literal[\"foo\"]) -> C:\n ...\n\n\n@overload\ndef func8(x: LiteralString) -> B:\n ...\n\n\n@overload\ndef func8(x: str) -> A:\n ...\n\n\ndef func8(x: Any) -> Any:\n raise NotImplementedError\n\n\ndef call_func8(x: str) -> None:\n assert_type(func8(\"foo\"), C) # First overload\n assert_type(func8(\"bar\"), B) # Second overload\n assert_type(func8(x), A) # Third overload\n\n\ndef func9(val: list[LiteralString]):\n x1: list[str] = val # E\n\n\ndef func10(val: Sequence[LiteralString]):\n x1: Sequence[str] = val # OK\n","source":"typing_tests","origin":"conformance/tests/literals_literalstring.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_04.py","code":"\"\"\"\nTests interactions between Literal types and other typing features.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#interactions-with-other-types-and-features\nfrom enum import Enum\nfrom typing import IO, Any, Final, Generic, Literal, TypeVar, LiteralString, assert_type, overload\n\n\ndef func1(v: tuple[int, str, list[bool]], a: Literal[0], b: Literal[5], c: Literal[-5]):\n assert_type(v[a], int)\n assert_type(v[2], list[bool])\n\n v[b] # E: index out of range\n v[c] # E: index out of range\n v[4] # E: index out of range\n v[-4] # E: index out of range\n\n\n_PathType = str | bytes | int\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"r\", \"w\", \"a\", \"x\", \"r+\", \"w+\", \"a+\", \"x+\"],\n) -> IO[str]:\n ...\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"rb\", \"wb\", \"ab\", \"xb\", \"r+b\", \"w+b\", \"a+b\", \"x+b\"],\n) -> IO[bytes]:\n ...\n\n\n@overload\ndef open(path: _PathType, mode: str) -> IO[Any]:\n ...\n\n\ndef open(path: _PathType, mode: Any) -> Any:\n raise NotImplementedError\n\n\nassert_type(open(\"path\", \"r\"), IO[str])\nassert_type(open(\"path\", \"wb\"), IO[bytes])\nassert_type(open(\"path\", \"other\"), IO[Any])\n\n\nA = TypeVar(\"A\", bound=int)\nB = TypeVar(\"B\", bound=int)\nC = TypeVar(\"C\", bound=int)\n\n\nclass Matrix(Generic[A, B]):\n def __add__(self, other: \"Matrix[A, B]\") -> \"Matrix[A, B]\":\n raise NotImplementedError\n\n def __matmul__(self, other: \"Matrix[B, C]\") -> \"Matrix[A, C]\":\n raise NotImplementedError\n\n def transpose(self) -> \"Matrix[B, A]\":\n raise NotImplementedError\n\n\ndef func2(a: Matrix[Literal[2], Literal[3]], b: Matrix[Literal[3], Literal[7]]):\n c = a @ b\n assert_type(c, Matrix[Literal[2], Literal[7]])\n\n\nT = TypeVar(\"T\", Literal[\"a\"], Literal[\"b\"], Literal[\"c\"])\nS = TypeVar(\"S\", bound=Literal[\"foo\"])\n\n\nclass Status(Enum):\n SUCCESS = 0\n INVALID_DATA = 1\n FATAL_ERROR = 2\n\n\ndef parse_status1(s: str | Status) -> None:\n if s is Status.SUCCESS:\n assert_type(s, Literal[Status.SUCCESS])\n elif s is Status.INVALID_DATA:\n assert_type(s, Literal[Status.INVALID_DATA])\n elif s is Status.FATAL_ERROR:\n assert_type(s, Literal[Status.FATAL_ERROR])\n else:\n assert_type(s, str)\n\n\n# > Type checkers may optionally perform additional analysis for both\n# > enum and non-enum Literal types beyond what is described in the section above.\n#\n# > For example, it may be useful to perform narrowing based on things\n# > like containment or equality checks:\n\ndef expects_bad_status(status: Literal[\"MALFORMED\", \"ABORTED\"]):\n ...\n\n\ndef expects_pending_status(status: Literal[\"PENDING\"]):\n ...\n\n\ndef parse_status2(status: LiteralString) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n\n# Narrowing `str` to `Literal` strings is unsound given the possiblity of\n# user-defined `str` subclasses that could have custom equality semantics,\n# but is explicitly listed by the spec as optional analysis that type checkers\n# may perform.\ndef parse_status3(status: str) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n\nfinal_val1: Final = 3\nassert_type(final_val1, Literal[3])\n\nfinal_val2: Final = True\nassert_type(final_val2, Literal[True])\n","source":"typing_tests","origin":"conformance/tests/literals_interactions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_05.py","code":"\"\"\"\nTests legal and illegal parameterizations of Literal.\n\"\"\"\n\n# > Literal must be parameterized with at least one type.\n\nfrom typing import Any, Literal, TypeVar\nfrom enum import Enum\n\n\nclass Color(Enum):\n RED = 0\n GREEN = 1\n BLUE = 2\n\n\ngood1: Literal[26]\ngood2: Literal[0x1A]\ngood3: Literal[-4]\ngood4: Literal[+5]\ngood5: Literal[\"hello world\"]\ngood6: Literal[b\"hello world\"]\ngood7: Literal[\"hello world\"]\ngood8: Literal[True]\ngood9: Literal[Color.RED]\ngood10: Literal[None]\n\nReadOnlyMode = Literal[\"r\", \"r+\"]\nWriteAndTruncateMode = Literal[\"w\", \"w+\", \"wt\", \"w+t\"]\nWriteNoTruncateMode = Literal[\"r+\", \"r+t\"]\nAppendMode = Literal[\"a\", \"a+\", \"at\", \"a+t\"]\n\nAllModes = Literal[ReadOnlyMode, WriteAndTruncateMode, WriteNoTruncateMode, AppendMode]\n\ngood11: Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n\nvariable = 3\nT = TypeVar(\"T\")\n\n# > Arbitrary expressions [are illegal]\nbad1: Literal[3 + 4] # E\nbad2: Literal[\"foo\".replace(\"o\", \"b\")] # E\nbad3: Literal[4 + 3j] # E\nbad4: Literal[~5] # E\nbad5: Literal[not False] # E\nbad6: Literal[(1, \"foo\", \"bar\")] # E\nbad7: Literal[{\"a\": \"b\", \"c\": \"d\"}] # E\nbad8: Literal[int] # E\nbad9: Literal[variable] # E\nbad10: Literal[T] # E\nbad11: Literal[3.14] # E\nbad12: Literal[Any] # E\nbad13: Literal[...] # E\n\n\ndef my_function(x: Literal[1 + 2]) -> int: # E\n return x * 3\n\n\nx: Literal # E\ny: Literal[my_function] = my_function # E\n\n\ndef func2(a: Literal[Color.RED]):\n x1: Literal[\"Color.RED\"] = a # E\n\n x2: \"Literal[Color.RED]\" = a # OK\n","source":"typing_tests","origin":"conformance/tests/literals_parameterizations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_06.py","code":"\"\"\"\nTests the semantics of the Literal special form.\n\"\"\"\n\nfrom typing import Literal\nfrom typing import Literal as L\n\n\nv1: Literal[3] = 3\nv2: Literal[3] = 4 # E\n\nv3: L[-3] = -3\n\n\n# > Literal[20] and Literal[0x14] are equivalent\ndef func1(a: Literal[20], b: Literal[0x14], c: Literal[0b10100]):\n x1: Literal[0x14] = a\n x2: Literal[0x14] = b\n x3: Literal[0x14] = c\n\n\n# > Literal[0] and Literal[False] are not equivalent\ndef func2(a: Literal[0], b: Literal[False]):\n x1: Literal[False] = a # E\n x2: Literal[0] = b # E\n\n\n# > Given some value v that is a member of type T, the type Literal[v] shall\n# > be treated as a subtype of T. For example, Literal[3] is a subtype of int.\ndef func3(a: L[3, 4, 5]):\n b = a.__add__(3)\n c = a + 3\n a += 3 # E\n\n\n# > When a Literal is parameterized with more than one value, it’s treated\n# > as exactly equivalent to the union of those types.\ndef func4(a: L[None, 3] | L[3, \"foo\", b\"bar\", True]):\n x1: Literal[3, b\"bar\", True, \"foo\", None] = a\n a = x1\n","source":"typing_tests","origin":"conformance/tests/literals_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"override-decorator","pep":"698","introduced_in":"3.12","form":"modern","file":"override-decorator/modern_01.py","code":"\"\"\"\nTests the typing.override decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#override\n\nfrom typing import Any, Callable, overload, override\n\n\ndef wrapper(func: Callable[..., Any], /) -> Any:\n def wrapped(*args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n return wrapped\n\n\nclass ParentA:\n def method1(self) -> int:\n return 1\n\n @overload\n def method2(self, x: int) -> int:\n ...\n\n @overload\n def method2(self, x: str) -> str:\n ...\n\n def method2(self, x: int | str) -> int | str:\n return 0\n\n def method5(self):\n pass\n\n\nclass ChildA(ParentA):\n @override\n def method1(self) -> int: # OK\n return 2\n\n @overload\n def method2(self, x: int) -> int:\n ...\n\n @overload\n def method2(self, x: str) -> str:\n ...\n\n def method2(self, x: int | str) -> int | str: # OK\n return 0\n\n @override # E[method3]\n def method3(self) -> int: # E[method3]: no matching signature in ancestor\n return 1\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @override # E[method4]\n def method4(self, x: int | str) -> int | str: # E[method4]: no matching signature in ancestor\n return 0\n\n @override\n @wrapper\n def method5(self): # OK\n pass\n\n # > The @override decorator should be permitted anywhere a type checker\n # > considers a method to be a valid override, which typically includes not\n # > only normal methods but also @property, @staticmethod, and @classmethod.\n\n @staticmethod\n @override # E[static_method1]\n def static_method1() -> int: # E[static_method1]: no matching signature in ancestor\n return 1\n\n @classmethod\n @override # E[class_method1]\n def class_method1(cls) -> int: # E[class_method1]: no matching signature in ancestor\n return 1\n\n @property\n @override # E[property1]\n def property1(self) -> int: # E[property1]: no matching signature in ancestor\n return 1\n\n\n# Test the case where the parent derives from Any\n\nclass ParentB(Any):\n pass\n\n\nclass ChildB(ParentB):\n @override\n def method1(self) -> None: # OK\n pass\n\n\n# > When type checkers encounter a method decorated with @typing.override they\n# > should treat it as a type error unless that method is overriding a method or\n# > attribute in some ancestor class, and the type of the overriding method is\n# > assignable to the type of the overridden method.\n\n# ``__init__`` and ``__new__`` are normally exempt from override compatibility\n# checks, since constructors are not subject to the Liskov substitution\n# principle. However, when they are explicitly decorated with ``@override`` the\n# decorator's assignability check should still be honored.\n# See https://github.com/python/typing/issues/2222\n\n\nclass ParentC:\n def __init__(self, x: int) -> None: ...\n\n def __new__(cls, x: int) -> \"ParentC\":\n raise NotImplementedError\n\n\nclass ChildC1(ParentC):\n @override\n def __init__(self, x: int) -> None: ... # OK\n\n @override\n def __new__(cls, x: int) -> \"ChildC1\": # OK\n raise NotImplementedError\n\n\nclass ChildC2(ParentC):\n @override # E[init]\n def __init__(self, x: str) -> None: ... # E[init]: not assignable to \"ParentC.__init__\"\n\n @override # E[new]\n def __new__(cls, x: str) -> \"ChildC2\": # E[new]: not assignable to \"ParentC.__new__\"\n raise NotImplementedError\n\n\n# Without ``@override`` an incompatible constructor signature is allowed, since\n# ``__init__`` and ``__new__`` are exempt from the usual override checks.\n\n\nclass ChildC3(ParentC):\n def __init__(self, x: str) -> None: ... # OK\n\n def __new__(cls, x: str) -> \"ChildC3\": # OK\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/classes_override.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_01.py","code":"\"\"\"\nTests basic usage of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#paramspec-variables\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeAlias\n\nP = ParamSpec(\"P\") # OK\nWrongName = ParamSpec(\"NotIt\") # E: name inconsistency\n\n\n# > Valid use locations\n\nTA1: TypeAlias = P # E\n\nTA2: TypeAlias = Callable[P, None] # OK\nTA3: TypeAlias = Callable[Concatenate[int, P], None] # OK\nTA4: TypeAlias = Callable[..., None] # OK\nTA5: TypeAlias = Callable[..., None] # OK\n\n\ndef func1(x: P) -> P: # E\n raise NotImplementedError\n\n\ndef func2(x: Concatenate[int, P]) -> int: # E\n raise NotImplementedError\n\n\ndef func3(x: list[P]) -> None: # E\n ...\n\n\ndef func4(x: Callable[[int, str], P]) -> None: # E\n ...\n\n\ndef func5(*args: P, **kwargs: P) -> None: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_02.py","code":"\"\"\"\nTests the usage of a ParamSpec and its components (P.args, P.kwargs).\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#the-components-of-a-paramspec\n\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef puts_p_into_scope1(f: Callable[P, int]) -> None:\n def inner(*args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def mixed_up(*args: P.kwargs, **kwargs: P.args) -> None: # E\n pass\n\n def misplaced1(x: P.args) -> None: # E\n pass\n\n def bad_kwargs1(*args: P.args, **kwargs: P.args) -> None: # E\n pass\n\n def bad_kwargs2(*args: P.args, **kwargs: Any) -> None: # E\n pass\n\n\ndef out_of_scope(*args: P.args, **kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef puts_p_into_scope2(f: Callable[P, int]) -> None:\n stored_args: P.args # E\n stored_kwargs: P.kwargs # E\n\n def just_args(*args: P.args) -> None: # E\n pass\n\n def just_kwargs(**kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef decorator(f: Callable[P, int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n assert_type(f(*args, **kwargs), int) # OK\n\n f(*kwargs, **args) # E\n\n f(1, *args, **kwargs) # E\n\n return foo # OK\n\n\ndef add(f: Callable[P, int]) -> Callable[Concatenate[str, P], None]:\n def foo(s: str, *args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def bar(*args: P.args, s: str, **kwargs: P.kwargs) -> None: # E\n pass\n\n return foo # OK\n\n\ndef remove(f: Callable[Concatenate[int, P], int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n f(1, *args, **kwargs) # OK\n\n f(*args, 1, **kwargs) # E\n\n f(*args, **kwargs) # E\n\n return foo # OK\n\n\ndef outer(f: Callable[P, None]) -> Callable[P, None]:\n def foo(x: int, *args: P.args, **kwargs: P.kwargs) -> None:\n f(*args, **kwargs)\n\n def bar(*args: P.args, **kwargs: P.kwargs) -> None:\n foo(1, *args, **kwargs) # OK\n foo(x=1, *args, **kwargs) # E\n\n return bar\n\n\ndef twice(f: Callable[P, int], *args: P.args, **kwargs: P.kwargs) -> int:\n return f(*args, **kwargs) + f(*args, **kwargs)\n\n\ndef a_int_b_str(a: int, b: str) -> int:\n return 0\n\n\ntwice(a_int_b_str, 1, \"A\") # OK\ntwice(a_int_b_str, b=\"A\", a=1) # OK\ntwice(a_int_b_str, \"A\", 1) # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_components.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_03.py","code":"\"\"\"\nTests semantics of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#semantics\n\n\nfrom typing import Callable, Concatenate, Generic, ParamSpec, TypeVar, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef changes_return_type_to_str(x: Callable[P, int]) -> Callable[P, str]:\n raise NotImplementedError\n\n\ndef returns_int(a: str, b: bool, /) -> int:\n raise NotImplementedError\n\n\nf1 = changes_return_type_to_str(returns_int)\nassert_type(f1, Callable[[str, bool], str])\n\nv1 = f1(\"A\", True) # OK\nassert_type(v1, str)\nf1(a=\"A\", b=True) # E: positional-only\nf1(\"A\", \"A\") # E: wrong type\n\n\ndef func1(x: Callable[P, int], y: Callable[P, int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\ndef x_y(x: int, y: str) -> int:\n raise NotImplementedError\n\n\ndef y_x(y: int, x: str) -> int:\n raise NotImplementedError\n\n\nf2 = func1(x_y, x_y)\nassert_type(f2(1, \"\"), bool)\nassert_type(f2(y=\"\", x=1), bool)\n\nf3 = func1(x_y, y_x) # E?: Could return (a: int, b: str, /) -> bool\n# (a callable with two positional-only parameters)\n# This works because both callables have types that are\n# behavioral subtypes of Callable[[int, str], int]\n# Also OK for type checkers to reject this.\n\n\ndef keyword_only_x(*, x: int) -> int:\n raise NotImplementedError\n\n\ndef keyword_only_y(*, y: int) -> int:\n raise NotImplementedError\n\n\nfunc1(keyword_only_x, keyword_only_y) # E\n\n\nU = TypeVar(\"U\")\n\n\nclass Y(Generic[U, P]):\n f: Callable[P, str]\n prop: U\n\n def __init__(self, f: Callable[P, str], prop: U) -> None:\n self.f = f\n self.prop = prop\n\n\ndef callback_a(q: int, /) -> str:\n raise NotImplementedError\n\n\ndef func(x: int) -> None:\n y1 = Y(callback_a, x)\n assert_type(y1, Y[int, [int]])\n y2 = y1.f\n assert_type(y2, Callable[[int], str])\n\n\ndef bar(x: int, *args: bool) -> int:\n raise NotImplementedError\n\n\ndef add(x: Callable[P, int]) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\na1 = add(bar) # Should return (a: str, /, x: int, *args: bool) -> bool\nassert_type(a1(\"\", 1, False, True), bool)\nassert_type(a1(\"\", x=1), bool)\na1(1, x=1) # E\n\n\ndef remove(x: Callable[Concatenate[int, P], int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\nr1 = remove(bar) # Should return (*args: bool) -> bool\nassert_type(r1(False, True, True), bool)\nassert_type(r1(), bool)\nr1(1) # E\n\n\ndef transform(\n x: Callable[Concatenate[int, P], int]\n) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\nt1 = transform(bar) # Should return (a: str, /, *args: bool) -> bool\nassert_type(t1(\"\", True, False, True), bool)\nassert_type(t1(\"\"), bool)\nt1(1) # E\n\n\ndef expects_int_first(x: Callable[Concatenate[int, P], int]) -> None:\n ...\n\n\n@expects_int_first # E\ndef one(x: str) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef two(*, x: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef three(**kwargs: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # OK\ndef four(*args: int) -> int:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_04.py","code":"\"\"\"\nTests the handling of a ParamSpec specialization.\n\"\"\"\n\nfrom typing import Any, Callable, Concatenate, Generic, ParamSpec, TypeVar, cast\n\n\nT = TypeVar(\"T\")\nP1 = ParamSpec(\"P1\")\nP2 = ParamSpec(\"P2\")\n\n\nclass ClassA(Generic[T, P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\nclass ClassB(ClassA[T, P1], Generic[T, P1, P2]):\n f1: Callable[P1, int] = cast(Any, \"\")\n f2: Callable[P2, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\ndef func20(x: ClassA[int, P2]) -> str: # OK\n return \"\"\n\n\ndef func21(x: ClassA[int, Concatenate[int, P2]]) -> str: # OK\n return \"\"\n\n\ndef func22(x: ClassB[int, [int, bool], ...]) -> str: # OK\n return \"\"\n\n\ndef func23(x: ClassA[int, ...]) -> str: # OK\n return \"\"\n\n\ndef func24(x: ClassB[int, [], []]) -> str: # OK\n return \"\"\n\n\ndef func25(x: ClassA[int, int]) -> str: # E\n return \"\"\n\n\nclass ClassC(Generic[P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n\n\ndef func30(x: ClassC[[int, str, bool]]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n\n\ndef func31(x: ClassC[int, str, bool]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_05.py","code":"\"\"\"\nTests variance of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance-inference\n\n\nfrom typing import Callable, Generic, ParamSpec\n\n\nclass InvariantParamSpec[**InOutP]:\n a: Callable[InOutP, None]\n\nin_out_obj: InvariantParamSpec[object] = InvariantParamSpec[int]() # E\nin_out_int: InvariantParamSpec[int] = InvariantParamSpec[object]() # E\n\n\nclass ContravariantParamSpec[**InP]:\n def f(self, *args: InP.args, **kwargs: InP.kwargs): ...\n\nin_obj: ContravariantParamSpec[object] = ContravariantParamSpec[int]() # E\nin_int: ContravariantParamSpec[int] = ContravariantParamSpec[object]() # OK\n\n\nclass CovariantParamSpec[**OutP]:\n def f(self, fn: Callable[OutP, None]) -> None:\n raise NotImplementedError\n\n\nout_int: CovariantParamSpec[int] = CovariantParamSpec[object]() # E\nout_obj: CovariantParamSpec[object] = CovariantParamSpec[int]() # OK\n\n# cases involving keyword-only, positional-only parameters, parameter names, defaults and differing callable arities\nclass Box[T]:\n t: T\n\n def __init__(self, t: T): ...\n\n\ndef f(a: int): ...\ndef kw(*, a: int): ...\ndef pos(a: int, /): ...\ndef names(b: int): ...\ndef default(a: int = 1): ...\ndef arity(a: int, b: str): ...\n\n\nclass InitP[**P]: # contravariant\n def __init__(self, fn: Callable[P, None]): ...\n\n def usage(self) -> Callable[P, None]:\n \"\"\"infer contravariance\"\"\"\n raise NotImplementedError\n\n\n# `InitP` produces a `Callable[P, None]`, so a replacement is only safe if it\n# accepts every call form that `InitP[(a: int)]` accepts.\nin_box = Box(InitP(f))\n\nin_kw_p = InitP(kw)\nin_box.t = in_kw_p # E\nin_pos_p = InitP(pos)\nin_box.t = in_pos_p # E\nin_names_p = InitP(names)\nin_box.t = in_names_p # E\nin_default_p = InitP(default)\nin_box.t = in_default_p # OK\nin_arity_p = InitP(arity)\nin_box.t = in_arity_p # E\n\n\nclass OutitP[**P]: # covariant\n def __init__(self, fn: Callable[P, None]): ...\n\n def usage(self, fn: Callable[P, None]):\n \"\"\"infer covariance\"\"\"\n\n\n# `OutitP` consumes a `Callable[P, None]`, so the safe direction is reversed: a\n# replacement is only safe if `Callable[(a: int), None]` can be passed to it.\nout_box = Box(OutitP(f))\n\nout_kw_p = OutitP(kw)\nout_box.t = out_kw_p # OK\nout_pos_p = OutitP(pos)\nout_box.t = out_pos_p # OK\nout_names_p = OutitP(names)\nout_box.t = out_names_p # E\nout_default_p = OutitP(default)\nout_box.t = out_default_p # E\nout_arity_p = OutitP(arity)\nout_box.t = out_arity_p # E\n\n\n# old style\nP = ParamSpec(\"P\") # OK\nInP = ParamSpec(\"InP\", contravariant=True) # OK\nOutP = ParamSpec(\"OutP\", covariant=True) # OK\nInferP = ParamSpec(\"InferP\", infer_variance=True) # OK\nInvP1 = ParamSpec(\"InvP1\", covariant=True, contravariant=True) # E\nInvP2 = ParamSpec(\"InvP2\", covariant=True, infer_variance=True) # E\nInvP3 = ParamSpec(\"InvP3\", contravariant=True, infer_variance=True) # E\n\nclass InvariantParamSpecOld(Generic[P]):\n def f(self, fn: Callable[P, None]) -> Callable[P, None]: # OK\n raise NotImplementedError\n\nin_out_old: InvariantParamSpecOld[int]\nin_out_old = InvariantParamSpecOld[int]() # OK\nin_out_old = InvariantParamSpecOld[bool]() # E\nin_out_old = InvariantParamSpecOld[object]() # E\n\nclass ContravariantParamSpecOld(Generic[InP]):\n def in_f(self) -> Callable[InP, None]: # OK\n raise NotImplementedError\n\n def out_f(self, fn: Callable[InP, None]) -> None: # E\n raise NotImplementedError\n\n\nin_obj_old: ContravariantParamSpecOld[object] = ContravariantParamSpecOld[int]() # E\nin_int_old: ContravariantParamSpecOld[int] = ContravariantParamSpecOld[object]() # OK\n\n\nclass CovariantParamSpecOld(Generic[OutP]):\n def in_f(self) -> Callable[OutP, None]: # E\n raise NotImplementedError\n def out_f(self, fn: Callable[OutP, None]) -> None: # OK\n raise NotImplementedError\n\n\nout_int_old: CovariantParamSpecOld[int] = CovariantParamSpecOld[object]() # E\nout_obj_old: CovariantParamSpecOld[object] = CovariantParamSpecOld[int]() # OK\n\n\n# `infer_variance=True` on a traditional `ParamSpec`\nclass InferredContravariantParamSpecOld(Generic[InferP]):\n def in_f(self) -> Callable[InferP, None]: # OK\n raise NotImplementedError\n\n\ninfer_in_obj_old: InferredContravariantParamSpecOld[object] = InferredContravariantParamSpecOld[int]() # E\ninfer_in_int_old: InferredContravariantParamSpecOld[int] = InferredContravariantParamSpecOld[object]() # OK\n\n\nclass InferredCovariantParamSpecOld(Generic[InferP]):\n def out_f(self, fn: Callable[InferP, None]) -> None: # OK\n raise NotImplementedError\n\n\ninfer_out_int_old: InferredCovariantParamSpecOld[int] = InferredCovariantParamSpecOld[object]() # E\ninfer_out_obj_old: InferredCovariantParamSpecOld[object] = InferredCovariantParamSpecOld[int]() # OK\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_01.py","code":"\"\"\"\nTests handling of callback protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#callback-protocols\n\nfrom typing import Any, Callable, ParamSpec, Protocol, TypeVar, cast, overload\n\nInputT = TypeVar(\"InputT\", contravariant=True)\nOutputT = TypeVar(\"OutputT\", covariant=True)\n\n\nclass Proto1(Protocol):\n def __call__(self, *vals: bytes, max_len: int | None = None) -> list[bytes]:\n ...\n\n\ndef cb1_good1(*vals: bytes, max_len: int | None = None) -> list[bytes]:\n return []\n\n\ndef cb1_bad1(*vals: bytes, max_items: int | None) -> list[bytes]:\n return []\n\n\ndef cb1_bad2(*vals: bytes) -> list[bytes]:\n return []\n\n\ndef cb1_bad3(*vals: bytes, max_len: str | None) -> list[bytes]:\n return []\n\n\ncb1: Proto1 = cb1_good1 # OK\ncb1 = cb1_bad1 # E: different names\ncb1 = cb1_bad2 # E: parameter types\ncb1 = cb1_bad3 # E: default argument\n\n\nclass Proto2(Protocol):\n def __call__(self, *vals: bytes, **kwargs: str) -> None:\n pass\n\n\ndef cb2_good1(*a: bytes, **b: str):\n pass\n\n\ndef cb2_bad1(*a: bytes):\n pass\n\n\ndef cb2_bad2(*a: str, **b: str):\n pass\n\n\ndef cb2_bad3(*a: bytes, **b: bytes):\n pass\n\n\ndef cb2_bad4(**b: str):\n pass\n\n\ncb2: Proto2 = cb2_good1 # OK\n\ncb2 = cb2_bad1 # E: missing **kwargs\ncb2 = cb2_bad2 # E: parameter type\ncb2 = cb2_bad3 # E: parameter type\ncb2 = cb2_bad4 # E: missing parameter\n\n\nclass Proto3(Protocol):\n def __call__(self) -> None:\n pass\n\n\ncb3: Proto3 = cb2_good1 # OK\ncb3 = cb2_bad1 # OK\ncb3 = cb2_bad2 # OK\ncb3 = cb2_bad3 # OK\ncb3 = cb2_bad4 # OK\n\n\n# A callback protocol with other attributes.\nclass Proto4(Protocol):\n other_attribute: int\n\n def __call__(self, x: int) -> None:\n pass\n\n\ndef cb4_bad1(x: int) -> None:\n pass\n\n\nvar4: Proto4 = cb4_bad1 # E: missing attribute\n\n\nclass Proto5(Protocol):\n def __call__(self, *, a: int, b: str) -> int:\n ...\n\n\ndef cb5_good1(a: int, b: str) -> int:\n return 0\n\n\ncb5: Proto5 = cb5_good1 # OK\n\n\nclass NotProto6:\n def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]:\n return []\n\n\ndef cb6_bad1(*vals: bytes, max_len: int | None = None) -> list[bytes]:\n return []\n\n\ncb6: NotProto6 = cb6_bad1 # E: NotProto6 isn't a protocol class\n\n\nclass Proto7(Protocol[InputT, OutputT]):\n def __call__(self, inputs: InputT) -> OutputT:\n ...\n\n\nclass Class7_1:\n # Test for unannotated parameter.\n def __call__(self, inputs) -> int:\n return 5\n\n\ncb7_1: Proto7[int, int] = Class7_1() # OK\n\n\nclass Class7_2:\n # Test for parameter with type Any.\n def __call__(self, inputs: Any) -> int:\n return 5\n\n\ncb7_2: Proto7[int, int] = Class7_2() # OK\n\n\nclass Proto8(Protocol):\n @overload\n def __call__(self, x: int) -> int:\n ...\n\n @overload\n def __call__(self, x: str) -> str:\n ...\n\n def __call__(self, x: Any) -> Any:\n ...\n\n\ndef cb8_good1(x: Any) -> Any:\n return x\n\n\ndef cb8_bad1(x: int) -> Any:\n return x\n\n\ncb8: Proto8 = cb8_good1 # OK\ncb8 = cb8_bad1 # E: parameter type\n\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\", covariant=True)\n\n\nclass Proto9[**P, R](Protocol):\n other_attribute: int\n\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\ndef decorator1(f: Callable[P, R]) -> Proto9[P, R]:\n converted = cast(Proto9[P, R], f)\n converted.other_attribute = 1\n converted.other_attribute = \"str\" # E: incompatible type\n converted.xxx = 3 # E: unknown attribute\n return converted\n\n\n@decorator1\ndef cb9_good(x: int) -> str:\n return \"\"\n\n\nprint(cb9_good.other_attribute) # OK\nprint(cb9_good.other_attribute2) # E: unknown attribute\n\ncb9_good(x=3)\n\n\nclass Proto10(Protocol):\n __name__: str\n __module__: str\n __qualname__: str\n __annotations__: dict[str, Any]\n\n def __call__(self) -> None:\n ...\n\n\ndef cb10_good() -> None:\n pass\n\n\ncb10: Proto10 = cb10_good # OK\n\n\nclass Proto11(Protocol):\n def __call__(self, x: int, /, y: str) -> Any:\n ...\n\n\ndef cb11_good1(x: int, /, y: str, z: None = None) -> Any:\n raise NotImplementedError\n\n\ndef cb11_good2(x: int, y: str, z: None = None) -> Any:\n raise NotImplementedError\n\n\ndef cb11_bad1(x: int, y: str, /) -> Any:\n raise NotImplementedError\n\n\ncb11: Proto11 = cb11_good1 # OK\ncb11 = cb11_good2 # OK\ncb11 = cb11_bad1 # E: y is position-only\n\n\nclass Proto12(Protocol):\n def __call__(self, *args: Any, kwarg0: Any, kwarg1: Any) -> None:\n ...\n\n\ndef cb12_good1(*args: Any, kwarg0: Any, kwarg1: Any) -> None:\n pass\n\n\ndef cb12_good2(*args: Any, **kwargs: Any) -> None:\n pass\n\n\ndef cb12_bad1(*args: Any, kwarg0: Any) -> None:\n pass\n\n\ncb12: Proto12 = cb12_good1 # OK\ncb12 = cb12_good2 # OK\ncb12 = cb12_bad1 # E: missing kwarg1\n\n\nclass Proto13_Default(Protocol):\n # Callback with positional parameter with default arg value\n def __call__(self, path: str = ...) -> str:\n ...\n\n\nclass Proto13_NoDefault(Protocol):\n # Callback with positional parameter but no default arg value\n def __call__(self, path: str) -> str:\n ...\n\n\ndef cb13_default(path: str = \"\") -> str:\n return \"\"\n\n\ndef cb13_no_default(path: str) -> str:\n return \"\"\n\n\ncb13_1: Proto13_Default = cb13_default # OK\ncb13_2: Proto13_Default = cb13_no_default # E: no default\n\ncb13_3: Proto13_NoDefault = cb13_default # OK\ncb13_4: Proto13_NoDefault = cb13_no_default # OK\n\n\nclass Proto14_Default(Protocol):\n # Callback with keyword parameter with default arg value\n def __call__(self, *, path: str = ...) -> str:\n ...\n\n\nclass Proto14_NoDefault(Protocol):\n # Callback with keyword parameter with no default arg value\n def __call__(self, *, path: str) -> str:\n ...\n\n\ndef cb14_default(*, path: str = \"\") -> str:\n return \"\"\n\n\ndef cb14_no_default(*, path: str) -> str:\n return \"\"\n\n\ncb14_1: Proto14_Default = cb14_default # OK\ncb14_2: Proto14_Default = cb14_no_default # E: no default\ncb14_3: Proto14_NoDefault = cb14_default # OK\ncb14_4: Proto14_NoDefault = cb14_no_default # OK\n","source":"typing_tests","origin":"conformance/tests/callables_protocol.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_02.py","code":"\"\"\"\nTests the handling of class objects as implementations of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#type-and-class-objects-vs-protocols\n\n# > Variables and parameters annotated with Type[Proto] accept only concrete\n# (non-protocol) subtypes of Proto.\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Protocol\n\n\nclass Proto(Protocol):\n @abstractmethod\n def meth(self) -> int:\n ...\n\n\nclass Concrete:\n def meth(self) -> int:\n return 42\n\n\ndef fun(cls: type[Proto]) -> int:\n return cls().meth() # OK\n\n\nfun(Proto) # E\nfun(Concrete) # OK\n\n\nvar: type[Proto]\nvar = Proto # E\nvar = Concrete # OK\nvar().meth() # OK\n\n\n# > A class object is considered an implementation of a protocol if accessing\n# > all members on it results in types compatible with the protocol members.\n\n\nclass ProtoA1(Protocol):\n def method1(self, x: int) -> int:\n ...\n\n\nclass ProtoA2(Protocol):\n def method1(_self, self: Any, x: int) -> int:\n ...\n\n\nclass ConcreteA:\n def method1(self, x: int) -> int:\n return 0\n\n\npa1: ProtoA1 = ConcreteA # E: signatures don't match\npa2: ProtoA2 = ConcreteA # OK\n\n\nclass ProtoB1(Protocol):\n @property\n def prop1(self) -> int:\n ...\n\n\nclass ConcreteB:\n @property\n def prop1(self) -> int:\n return 0\n\n\npb1: ProtoB1 = ConcreteB # E\n\n\nclass ProtoC1(Protocol):\n attr1: ClassVar[int]\n\n\nclass ProtoC2(Protocol):\n attr1: int\n\n\nclass ConcreteC1:\n attr1: ClassVar[int] = 1\n\n\nclass ConcreteC2:\n attr1: int = 1\n\n\nclass CMeta(type):\n attr1: int\n\n def __init__(self, *args, **kwargs) -> None:\n self.attr1: int = 1\n\n\nclass ConcreteC3(metaclass=CMeta):\n pass\n\n\npc1: ProtoC1 = ConcreteC1 # E\npc2: ProtoC2 = ConcreteC1 # OK\npc3: ProtoC1 = ConcreteC2 # E\npc4: ProtoC2 = ConcreteC2 # E\npc5: ProtoC1 = ConcreteC3 # E?: Explicit ClassVar matching is unspecified\npc6: ProtoC2 = ConcreteC3 # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_class_objects.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_03.py","code":"\"\"\"\nTests the basic definition rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#defining-a-protocol\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Iterable, NamedTuple, Protocol, Sequence\nfrom dataclasses import dataclass\n\n\nclass SupportsClose(Protocol):\n def close(self) -> None:\n ...\n\n\nclass Resource:\n def close(self) -> None:\n pass\n\n\ndef close_all(things: Iterable[SupportsClose]) -> None:\n for t in things:\n t.close()\n\n\nf = open(\"foo.txt\")\nr = Resource()\nclose_all([f, r]) # OK\nclose_all([1]) # E: 'int' has no 'close' method\n\n\nclass Example(Protocol):\n def first(self) -> int: # This is a protocol member\n return 42\n\n @abstractmethod\n def second(self) -> int: # Method without a default implementation\n raise NotImplementedError\n\n # > Static methods, class methods, and properties are equally allowed in protocols.\n\n @staticmethod\n def third() -> int:\n ...\n\n @classmethod\n def fourth(cls) -> int:\n ...\n\n @property\n def fifth(self) -> int:\n ...\n\n\n# > To define a protocol variable, one can use PEP 526 variable annotations\n# > in the class body. Additional attributes only defined in the body of a\n# > method by assignment via self are not allowed.\n\n\nclass Template(Protocol):\n name: str # This is a protocol member\n value: int = 0 # This one too (with default)\n\n def method(self) -> None:\n self.name = \"name\" # OK\n self.temp: list[int] = [] # E: use of self variables not allowed\n\n\nclass Concrete:\n def __init__(self, name: str, value: int) -> None:\n self.name = name\n self.value = value\n\n def method(self) -> None:\n return\n\n\nvar: Template = Concrete(\"value\", 42) # OK\n\n\n# > To distinguish between protocol class variables and protocol instance\n# > variables, the special ClassVar annotation should be used as specified\n# > by PEP 526. By default, protocol variables as defined above are considered\n# > readable and writable. To define a read-only protocol variable, one can\n# > use an (abstract) property.\n\n\nclass Template2(Protocol):\n val1: ClassVar[Sequence[int]]\n\n\nclass Concrete2_Good1:\n val1: ClassVar[Sequence[int]] = [2]\n\n\nclass Concrete2_Bad1:\n ...\n\n\nclass Concrete2_Bad2:\n val1: Sequence[float] = [2]\n\n\nclass Concrete2_Bad3:\n val1: list[int] = [2]\n\n\nclass Concrete2_Bad4:\n val1: Sequence[int] = [2]\n\n\nv2_good1: Template2 = Concrete2_Good1() # OK\nv2_bad1: Template2 = Concrete2_Bad1() # E\nv2_bad2: Template2 = Concrete2_Bad2() # E\nv2_bad3: Template2 = Concrete2_Bad3() # E\nv2_bad4: Template2 = Concrete2_Bad4() # E?: Explicit ClassVar matching is unspecified\n\n\nclass Template3(Protocol):\n val1: Sequence[int]\n\n\nclass Concrete3_Good1:\n val1: Sequence[int] = [0]\n\n\nclass Concrete3_Good2:\n def __init__(self) -> None:\n self.val1: Sequence[int] = [0]\n\n\nclass Concrete3_Bad1:\n ...\n\n\nclass Concrete3_Bad2:\n val1: ClassVar[Sequence[int]] = [0]\n\n\nclass Concrete3_Bad3:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete3_Bad4:\n val1: Sequence[float] = [0]\n\n\nclass Concrete3_Bad5:\n val1: list[int] = [0]\n\n\nv3_good1: Template3 = Concrete3_Good1() # OK\nv3_bad1: Template3 = Concrete3_Bad1() # E\nv3_bad2: Template3 = Concrete3_Bad2() # E\nv3_bad3: Template3 = Concrete3_Bad3() # E\nv3_bad4: Template3 = Concrete3_Bad4() # E\nv3_bad5: Template3 = Concrete3_Bad5() # E\n\n\nclass Template4(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n\nclass Concrete4_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete4_Good2:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete4_Good3:\n val1: Sequence[float] = [0]\n\n\nclass Concrete4_Good4:\n val1: Sequence[int] = [0]\n\n\nclass Concrete4_Good5:\n val1: list[float] = [0]\n\n\nclass Concrete4_Good6(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete4_Good7:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete4_Bad1:\n def val1(self) -> Sequence[int]: # Not a property\n return [0]\n\n\nclass Concrete4_Bad2:\n ...\n\n\nv4_good1: Template4 = Concrete4_Good1() # OK\nv4_good2: Template4 = Concrete4_Good2() # OK\nv4_good3: Template4 = Concrete4_Good3() # OK\nv4_good4: Template4 = Concrete4_Good4() # OK\nv4_good5: Template4 = Concrete4_Good5() # OK\nv4_good6: Template4 = Concrete4_Good6() # OK\nv4_good7: Template4 = Concrete4_Good7() # OK\nv4_bad1: Template4 = Concrete4_Bad1() # E\nv4_bad2: Template4 = Concrete4_Bad2() # E\n\n\nclass Template5(Protocol):\n def method1(self, a: int, b: int) -> float:\n ...\n\n\nclass Concrete5_Good1:\n def method1(self, a: float, b: float) -> int:\n return 0\n\n\nclass Concrete5_Good2:\n def method1(self, *args: float, **kwargs: float) -> Any:\n return 0.0\n\n\nclass Concrete5_Good3:\n def method1(self, a, b) -> Any:\n return 0.0\n\n\nclass Concrete5_Good4:\n @classmethod\n def method1(cls, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Good5:\n @staticmethod\n def method1(a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad1:\n def method1(self, a, c) -> int:\n return 0\n\n\nclass Concrete5_Bad2:\n def method1(self, a: int, c: int) -> int:\n return 0\n\n\nclass Concrete5_Bad3:\n def method1(self, *, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad4:\n def method1(self, a: int, b: int, /) -> float:\n return 0\n\n\nclass Concrete5_Bad5:\n @staticmethod\n def method1(self, a: int, b: int) -> float:\n return 0\n\n\nv5_good1: Template5 = Concrete5_Good1() # OK\nv5_good2: Template5 = Concrete5_Good2() # OK\nv5_good3: Template5 = Concrete5_Good3() # OK\nv5_good4: Template5 = Concrete5_Good4() # OK\nv5_good5: Template5 = Concrete5_Good5() # OK\nv5_bad1: Template5 = Concrete5_Bad1() # E\nv5_bad2: Template5 = Concrete5_Bad2() # E\nv5_bad3: Template5 = Concrete5_Bad3() # E\nv5_bad4: Template5 = Concrete5_Bad4() # E\nv5_bad5: Template5 = Concrete5_Bad5() # E\n\n\nclass Template6(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n ...\n\n\nclass Concrete6_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n pass\n\n\nclass Concrete6_Good2:\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete6_Good3:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete6_Bad1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete6_Bad2(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=True)\nclass Concrete6_Bad3:\n val1: Sequence[float] = (0,)\n\n\nv6_good1: Template6 = Concrete6_Good1() # OK\nv6_good2: Template6 = Concrete6_Good2() # OK\nv6_good3: Template6 = Concrete6_Good3() # OK\nv6_bad1: Template6 = Concrete6_Bad1() # E\nv6_bad2: Template6 = Concrete6_Bad2() # E: named tuple is immutable\nv6_bad3: Template6 = Concrete6_Bad3() # E: dataclass is frozen\n\n\n# The specification leaves two possible interpretations of a ClassVar protocol\n# member. One interpretation requires the implementing attribute to be explicitly\n# declared with ClassVar. The other interpretation imposes only structural\n# requirements: the attribute must be readable and writable on the class object\n# and readable on instances of the class. Both interpretations therefore require\n# the following assignments to be rejected.\n\n\nclass Template7(Protocol):\n val1: ClassVar[int]\n\n\nclass Concrete7_Bad1:\n def __init__(self) -> None:\n self.val1: int = 42\n\n\nclass Concrete7Meta(type):\n val1: int = 42\n\n\nclass Concrete7_Bad2(metaclass=Concrete7Meta):\n pass\n\n\nv7_bad1: Template7 = Concrete7_Bad1() # E: val1 is not readable on the class object\nv7_bad2: Template7 = Concrete7_Bad2() # E: val1 is not readable on instances\n","source":"typing_tests","origin":"conformance/tests/protocols_definition.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_04.py","code":"\"\"\"\nTests the handling of explicit protocol classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#explicitly-declaring-implementation\n\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar, Protocol\n\n\nclass PColor(Protocol):\n @abstractmethod\n def draw(self) -> str:\n ...\n\n def complex_method(self) -> int:\n return 1\n\n\nclass NiceColor(PColor):\n def draw(self) -> str:\n return \"deep blue\"\n\n\nclass BadColor(PColor):\n def draw(self) -> str:\n return super().draw() # E: no default implementation\n\n\nclass ImplicitColor: # Note no 'PColor' base here\n def draw(self) -> str:\n return \"probably gray\"\n\n def complex_method(self) -> int:\n return 0\n\n\nv1: PColor = NiceColor() # OK\nv2: PColor = ImplicitColor() # OK\n\n\nclass RGB(Protocol):\n rgb: tuple[int, int, int]\n other: int\n\n @abstractmethod\n def intensity(self) -> int:\n return 1\n\n def transparency(self) -> int:\n ...\n\n\nclass Point(RGB):\n def __init__(self, red: int, green: int, blue: str) -> None:\n self.rgb = red, green, blue # E: 'blue' must be 'int'\n self.other = 0\n\n\np = Point(0, 0, \"\") # E: Cannot instantiate abstract class\n\n\nclass Proto1(Protocol):\n cm1: ClassVar[int]\n cm2: ClassVar[int] = 0\n\n im1: int\n im2: int = 2\n im3: int\n\n def __init__(self):\n self.im3 = 3\n\n\nclass Proto2(Protocol):\n cm10: int\n\n\nclass Proto3(Proto2, Protocol):\n cm11: int\n\n\nclass Concrete1(Proto1):\n def __init__(self):\n self.im1 = 1\n self.im3 = 3\n\n\nc1 = Concrete1() # E: cannot instantiate abstract class\n\n\nclass Concrete2(Proto1):\n cm1 = 3\n im1 = 0\n\n\nc2 = Concrete2()\n\n\nclass Concrete3(Proto1, Proto3):\n cm1 = 3\n\n def __init__(self):\n self.im1 = 0\n self.cm10 = 10\n self.cm11 = 11\n\n\nc3 = Concrete3()\n\n\nclass Concrete4(Proto1, Proto3):\n cm1 = 3\n cm10 = 3\n\n def __init__(self):\n self.im1 = 3\n self.im10 = 10\n self.cm11 = 3\n\n\nc4 = Concrete4()\n\n\nclass Proto5(Protocol):\n def method1(self) -> int:\n ...\n\n\nclass Concrete5(Proto5):\n pass\n\n\nc5 = Concrete5() # E: cannot instantiate abstract class\n\n\nclass Proto6(Protocol):\n x: int\n\n\nclass Mixin:\n x = 3\n\n\nclass Concrete6(Mixin, Proto6):\n pass\n\n\nclass Proto7(Protocol):\n @abstractmethod\n def method1(self):\n ...\n\n\nclass Mixin7(Proto7, ABC):\n def method1(self) -> None:\n pass\n\n\nclass Concrete7A(Proto7):\n pass\n\n\nc7a = Concrete7A() # E: cannot instantiate abstract class\n\n\nclass Concrete7B(Mixin7, Proto7):\n pass\n\n\nc7b = Concrete7B()\n","source":"typing_tests","origin":"conformance/tests/protocols_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_05.py","code":"\"\"\"\nTests the handling of generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\n\nfrom typing import Callable, Generic, Iterator, Protocol, Self, TypeVar, assert_type\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Iterable(Protocol[T_co]):\n def __iter__(self) -> Iterator[T_co]:\n ...\n\n\n# > Protocol[T, S, ...] is allowed as a shorthand for Protocol, Generic[T, S, ...].\n# In particular, the implicit order of type parameters is dictated by\n# the order in which they appear in the `Protocol` subscript.\n\n\nclass Proto1(Iterable[T_co], Protocol[S, T_co]):\n def method1(self, x: S) -> S:\n ...\n\n\nclass Concrete1:\n def __iter__(self) -> Iterator[int]:\n return (x for x in [1, 2, 3])\n\n def method1(self, x: str) -> str:\n return \"\"\n\n\np1: Proto1[str, int] = Concrete1() # OK\np2: Proto1[int, str] = Concrete1() # E: incompatible type\n\n\n# > It is an error to combine the shorthand with Generic[T, S, ...]\nclass Proto2(Protocol[T_co], Generic[T_co]): # E\n ...\n\n\n# > User-defined generic protocols support explicitly declared variance.\nclass Box(Protocol[T_co]):\n def content(self) -> T_co:\n ...\n\n\ndef func1(box_int: Box[int], box_float: Box[float]):\n v1: Box[float] = box_int # OK\n v2: Box[int] = box_float # E\n\n\nclass Sender(Protocol[T_contra]):\n def send(self, data: T_contra) -> int:\n return 0\n\n\ndef func2(sender_int: Sender[int], sender_float: Sender[float]):\n v1: Sender[int] = sender_float # OK\n v2: Sender[float] = sender_int # E\n\n\nclass AttrProto(Protocol[T]):\n attr: T\n\n\ndef func3(attr_int: AttrProto[int], attr_float: AttrProto[float]):\n v1: AttrProto[float] = attr_int # E\n v2: AttrProto[int] = attr_float # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n# > The self-types in protocols follow the rules for other methods.\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n# > In addition, the first argument in an instance method can be annotated\n# > with a type variable. In this case the return type may use the same\n# > type variable, thus making that method a generic function.\n\n\nT_bounded = TypeVar(\"T_bounded\", bound=\"HasParent\")\n\n\nclass HasParent(Protocol):\n def get_parent(self: T_bounded) -> T_bounded:\n ...\n\n\nGenericHasParent = TypeVar(\"GenericHasParent\", bound=HasParent)\n\n\ndef generic_get_parent(n: GenericHasParent) -> GenericHasParent:\n return n.get_parent()\n\n\nclass ConcreteHasParent:\n def get_parent(self) -> Self:\n return self\n\n\nparent = generic_get_parent(ConcreteHasParent()) # OK\nassert_type(parent, ConcreteHasParent)\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > `Self` is valid within Protocols, similar to its use in classes:\n\n\nclass HasParentProperty(Protocol):\n @property\n def parent(self) -> Self:\n ...\n\n\nclass ConcreteParentProperty:\n @property\n def parent(self) -> Self:\n return self\n\n\nclass InvalidParentProperty:\n @property\n def parent(self) -> HasParentProperty:\n return ConcreteParentProperty()\n\n\nhp1: HasParentProperty = ConcreteParentProperty() # OK\nhp2: HasParentProperty = InvalidParentProperty() # E\n\n\n\nclass HasMethod(Protocol):\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n ...\n\n\nclass ConcreteHasMethod:\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n return \"\"\n\n\nclass InvalidHasMethod:\n def m(self, item: int, callback: Callable[[int], str]) -> str:\n return \"\"\n\n\nhm1: HasMethod = ConcreteHasMethod() # OK\nhm2: HasMethod = InvalidHasMethod() # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > Checking a class for assignability to a protocol: If a protocol uses `Self`\n# > in methods or attribute annotations, then a class `Foo` is assignable\n# > to the protocol if its corresponding methods and attribute annotations use\n# > either `Self` or `Foo` or any of `Foo`'s subclasses.\n\n\nclass HasGreaterThan(Protocol):\n def __gt__(self, other: Self) -> bool:\n ...\n\n\nclass ConcreteGreaterThan1:\n def __gt__(self, other: Self) -> bool:\n return False\n\n\nclass ConcreteGreaterThan2:\n def __gt__(self, other: \"ConcreteGreaterThan2\") -> bool:\n return False\n\n\nclass InvalidGreaterThan:\n def __gt__(self, other: int) -> bool:\n return False\n\n\nhg1: HasGreaterThan = ConcreteGreaterThan1() # OK\nhg2: HasGreaterThan = ConcreteGreaterThan2() # OK\nhg3: HasGreaterThan = InvalidGreaterThan() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_generic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_06.py","code":"\"\"\"\nTests merging and extending of protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#merging-and-extending-protocols\n\nfrom abc import abstractmethod\nfrom typing import Protocol\nfrom collections.abc import Sized\n\n\nclass SizedAndClosable1(Sized, Protocol):\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable2(Protocol):\n def __len__(self) -> int:\n ...\n\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable3(SizedAndClosable1): # Note: not a protocol\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete1:\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete2:\n def close(self) -> None:\n pass\n\n\ns1: SizedAndClosable1 = SCConcrete1() # OK\ns2: SizedAndClosable2 = SCConcrete1() # OK\ns3: SizedAndClosable1 = SizedAndClosable3() # OK\ns4: SizedAndClosable2 = SizedAndClosable3() # OK\ns5: Sized = SCConcrete1() # OK\n\ns6: SizedAndClosable1 = SCConcrete2() # E: doesn't implement `__len__`\ns7: SizedAndClosable2 = SCConcrete2() # E: doesn't implement `__len__`\ns8: SizedAndClosable3 = SCConcrete2() # E: SizedAndClosable3 is not a protocol\n\n\ndef func1(s1: SizedAndClosable1, s2: SizedAndClosable2):\n # > The two definitions of SizedAndClosable are equivalent.\n v1: SizedAndClosable2 = s1\n v2: SizedAndClosable1 = s2\n\n\n# > If Protocol is included in the base class list, all the other base classes\n# > must be protocols.\n\n\nclass BadProto(SizedAndClosable3, Protocol): # E: SizedAndClosable3 is not a protocol\n ...\n\n\n# > Without this base, the class is “downgraded” to a regular ABC that\n# > cannot be used with structural subtyping.\nclass SizedAndClosable4(SizedAndClosable1):\n def __len__(self) -> int:\n return 0\n\n @abstractmethod\n def close(self) -> None:\n raise NotImplementedError\n\n\nx = SizedAndClosable4() # E: cannot instantiate abstract class\ny: SizedAndClosable4 = SCConcrete1() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_merging.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_07.py","code":"\"\"\"\nTests the handling of modules as the implementation of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#modules-as-implementations-of-protocols\n\n# > A module object is accepted where a protocol is expected if the public\n# > interface of the given module is compatible with the expected protocol.\n\nimport _protocols_modules1\nimport _protocols_modules2\nfrom typing import Protocol\n\n\nclass Options1(Protocol):\n timeout: int\n one_flag: bool\n other_flag: bool\n\n\nclass Options2(Protocol):\n timeout: str\n\n\nop1: Options1 = _protocols_modules1 # OK\nop2: Options2 = _protocols_modules1 # E\n\n\nclass Reporter1(Protocol):\n def on_error(self, x: int) -> None:\n ...\n\n def on_success(self) -> None:\n ...\n\n\nclass Reporter2(Protocol):\n def on_error(self, x: int) -> int:\n ...\n\n\nclass Reporter3(Protocol):\n def not_implemented(self, x: int) -> int:\n ...\n\n\nrp1: Reporter1 = _protocols_modules2 # OK\nrp2: Reporter2 = _protocols_modules2 # E\nrp3: Reporter3 = _protocols_modules2 # E\n","source":"typing_tests","origin":"conformance/tests/protocols_modules.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_08.py","code":"\"\"\"\nTests the handling of recursive protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#recursive-protocols\n\n\nfrom typing import Generic, Iterable, Never, Protocol, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Traversable(Protocol):\n def leaves(self) -> Iterable[\"Traversable\"]:\n ...\n\n\nclass SimpleTree:\n def leaves(self) -> list[\"SimpleTree\"]:\n return []\n\n\nroot: Traversable = SimpleTree() # OK\n\n\nclass Tree(Generic[T]):\n def leaves(self) -> list[\"Tree[T]\"]:\n return []\n\n\ndef walk(graph: Traversable) -> None:\n pass\n\n\ntree: Tree[float] = Tree()\nwalk(tree) # OK\n\n\nclass ProtoA(Protocol[T_co, T_contra]):\n def method1(self) -> \"ProtoA[T_co, T_contra]\":\n ...\n\n @classmethod\n def method2(cls, value: T_contra) -> None:\n ...\n\n\nclass ProtoB(Protocol[T_co, T_contra]):\n def method3(self) -> ProtoA[T_co, T_contra]:\n ...\n\n\nclass ImplA:\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls, value: int) -> None:\n pass\n\n\nclass ImplB:\n def method3(self) -> ImplA:\n return ImplA()\n\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls: type[ProtoB[object, T]], value: list[T]) -> None:\n pass\n\n\ndef func1(x: ProtoA[Never, T]) -> T:\n raise NotImplementedError\n\n\nv1 = func1(ImplB())\nassert_type(v1, list[int])\n","source":"typing_tests","origin":"conformance/tests/protocols_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_09.py","code":"\"\"\"\nTests the handling of the @runtime_checkable decorator for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#runtime-checkable-decorator-and-narrowing-types-by-isinstance\n\n# > A protocol can be used as a second argument in isinstance() and\n# > issubclass() only if it is explicitly opt-in by @runtime_checkable decorator.\n\nfrom typing import Any, Protocol, runtime_checkable\n\n\nclass Proto1(Protocol):\n name: str\n\n\n@runtime_checkable\nclass Proto2(Protocol):\n name: str\n\n\ndef func1(a: Any):\n if isinstance(a, Proto1): # E: not runtime_checkable\n return\n\n if isinstance(a, Proto2): # OK\n return\n\n\n# > isinstance() can be used with both data and non-data protocols, while\n# > issubclass() can be used only with non-data protocols.\n\n\n@runtime_checkable\nclass DataProtocol(Protocol):\n name: str\n\n def method1(self) -> int:\n ...\n\n\n@runtime_checkable\nclass NonDataProtocol(Protocol):\n def method1(self) -> int:\n ...\n\n\ndef func2(a: Any):\n if isinstance(a, DataProtocol): # OK\n return\n\n if isinstance(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, DataProtocol): # E\n return\n\n if issubclass(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, (NonDataProtocol, DataProtocol)): # E\n return\n\n\n# > Type checkers should reject an isinstance() or issubclass() call if there\n# > is an unsafe overlap between the type of the first argument and the protocol.\n\n\n@runtime_checkable\nclass Proto3(Protocol):\n def method1(self, a: int) -> int:\n ...\n\n\nclass Concrete3A:\n def method1(self, a: str) -> None:\n pass\n\n\nclass Concrete3B:\n method1: int = 1\n\n\ndef func3():\n if isinstance(Concrete3A(), Proto2): # OK\n pass\n\n if isinstance(Concrete3A(), Proto3): # E: unsafe overlap\n pass\n\n if isinstance(Concrete3B(), (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n\n if issubclass(Concrete3A, (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n","source":"typing_tests","origin":"conformance/tests/protocols_runtime_checkable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_10.py","code":"\"\"\"\nTests the handling of annotated \"self\" parameters in a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n\nfrom typing import Generic, Protocol, Self, TypeVar\n\n\nC = TypeVar(\"C\", bound=\"Copyable\")\n\n\nclass Copyable(Protocol):\n def copy(self: C) -> C:\n return self\n\n\nclass One:\n def copy(self) -> \"One\":\n return One()\n\n\nT = TypeVar(\"T\", bound=\"Other\")\n\n\nclass Other:\n def copy(self: T) -> T:\n return self\n\n\nc: Copyable\nc = One() # OK\nc = Other() # OK\n\n\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT2_co = TypeVar(\"T2_co\", covariant=True)\n\n\nclass P1Parent(Protocol[T2_co]):\n def f0(self, /) -> Self:\n ...\n\n\nclass P1Child(P1Parent[T2_co], Protocol[T2_co]):\n ...\n\n\nclass C1(Generic[T1_co]):\n def f0(self, /) -> Self:\n return self\n\n\na1: P1Parent[str] = C1[str]()\nb1: P1Child[str] = C1[str]()\n\n\nclass P2Parent(Protocol[T1_co]):\n def f0(self, right: Self, /) -> \"P2Parent[T1_co]\":\n return right\n\n\nclass P2Child(P2Parent[T1_co], Protocol[T1_co]):\n ...\n\n\nclass C2(Generic[T2_co]):\n def f0(self, other: Self) -> \"C2[T2_co]\":\n return other\n\n\na2: P2Parent[str] = C2[str]() # OK\nb2: P2Child[str] = C2[str]() # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_self.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_11.py","code":"\"\"\"\nTests subtyping rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#subtyping-relationships-with-other-types\n\n# > Protocols cannot be instantiated.\n\nfrom typing import Hashable, Iterable, Protocol, Sequence, TypeVar\n\n\nclass Proto1(Protocol):\n pass\n\n\np1 = Proto1() # E: protocol cannot be instantiated\n\n\n# > A protocol is never a subtype of a concrete type.\n\n# > A concrete type X is a subtype of protocol P if and only if X implements\n# > all protocol members of P with compatible types. In other words, subtyping\n# > with respect to a protocol is always structural.\n\n\nclass Proto2(Protocol):\n def method1(self) -> None:\n ...\n\n\nclass Concrete2:\n def method1(self) -> None:\n pass\n\n\ndef func1(p2: Proto2, c2: Concrete2):\n v1: Proto2 = c2 # OK\n v2: Concrete2 = p2 # E\n\n\n# > A protocol P1 is a subtype of another protocol P2 if P1 defines all\n# > protocol members of P2 with compatible types.\n\n\nclass Proto3(Protocol):\n def method1(self) -> None:\n ...\n\n def method2(self) -> None:\n ...\n\n\ndef func2(p2: Proto2, p3: Proto3):\n v1: Proto2 = p3 # OK\n v2: Proto3 = p2 # E\n\n\n# > Generic protocols follow the rules for generic abstract classes, except\n# > for using structural compatibility instead of compatibility defined by\n# > inheritance relationships.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n\nclass Proto4(Protocol[S, T]):\n def method1(self, a: S, b: T) -> tuple[S, T]:\n ...\n\n\nclass Proto5(Protocol[T]):\n def method1(self, a: T, b: T) -> tuple[T, T]:\n ...\n\n\ndef func3(p4_int: Proto4[int, int], p5_int: Proto5[int]):\n v1: Proto4[int, int] = p5_int # OK\n v2: Proto5[int] = p4_int # OK\n v3: Proto4[int, float] = p5_int # E\n v4: Proto5[float] = p4_int # E\n\n\nS_co = TypeVar(\"S_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Proto6(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\nclass Proto7(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\ndef func4(p6: Proto6[float, float]):\n v1: Proto7[object, int] = p6 # OK\n v2: Proto7[float, float] = p6 # OK\n v3: Proto7[complex, int] = p6 # OK\n\n v4: Proto7[int, float] = p6 # E\n v5: Proto7[float, object] = p6 # E\n\n\n# > Unions of protocol classes behaves the same way as for non-protocol classes.\n\n\nclass SupportsExit(Protocol):\n def exit(self) -> int:\n ...\n\n\nclass SupportsQuit(Protocol):\n def quit(self) -> int | None:\n ...\n\n\ndef finish(task: SupportsExit | SupportsQuit) -> int:\n return 0\n\n\nclass DefaultJob:\n def quit(self) -> int:\n return 0\n\n\nfinish(DefaultJob()) # OK\n\n\n# > One can use multiple inheritance to define an intersection of protocols.\n\n\nclass HashableFloats(Iterable[float], Hashable, Protocol):\n pass\n\n\ndef cached_func(args: HashableFloats) -> float:\n return 0.0\n\n\ncached_func((1, 2, 3)) # OK, tuple is both hashable and iterable\n","source":"typing_tests","origin":"conformance/tests/protocols_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_12.py","code":"\"\"\"\nTests type variable variance inference for generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\nfrom typing import Protocol, TypeVar\nfrom typing_extensions import ParamSpec\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", bound=int)\nT3 = TypeVar(\"T3\", bytes, str)\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT1_contra = TypeVar(\"T1_contra\", contravariant=True)\nP = ParamSpec(\"P\", contravariant=True)\nR = TypeVar(\"R\", covariant=True)\n\n# > Type checkers will warn if the inferred variance is different from the\n# > declared variance.\n\n\nclass AnotherBox(Protocol[T1]): # E: T should be covariant\n def content(self) -> T1:\n ...\n\n\nclass Protocol1(Protocol[T1, T2, T3]): # OK\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1 | T2:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n def m4(self) -> T3:\n ...\n\n\nclass Protocol2(Protocol[T1, T2, T3]): # E: T3 should be contravariant\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n\nclass Protocol3(Protocol[T1_co]):\n def m1(self) -> None:\n pass\n\n\nclass Protocol4(Protocol[T1]): # E: T1 should be contravariant\n def m1(self, p0: T1) -> None:\n ...\n\n\nclass Protocol5(Protocol[T1_co]): # E[covariant_in_input+]\n def m1(self, p0: T1_co) -> None: # E[covariant_in_input+]\n ...\n\n\nclass Protocol6(Protocol[T1]): # E: T1 should be covariant\n def m1(self) -> T1:\n ...\n\n\nclass Protocol7(Protocol[T1_contra]): # E[contravariant_in_output+]\n def m1(self) -> T1_contra: # E[contravariant_in_output+]\n ...\n\n\nclass Protocol8(Protocol[T1]): # OK\n def m1(self) -> T1:\n ...\n\n def m2(self, p1: T1) -> None:\n pass\n\n\nclass Callback(Protocol[P, R]): # OK\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\nclass Protocol9(Protocol[T1_co]): # OK\n @property\n def prop1(self) -> T1_co:\n ...\n\n\nclass Protocol10(Protocol[T1_co]): # OK\n def m1(self) -> type[T1_co]:\n ...\n\n\nclass Protocol11(Protocol[T1]): # OK\n x: T1 | None\n\n\nclass Protocol12(Protocol[T1]): # E: T1 should be covariant\n # __init__ method is exempt from variance calculations.\n def __init__(self, x: T1) -> None:\n ...\n\n\nclass Protocol13(Protocol[T1_contra]): # OK\n def m1(self: \"Protocol13[T1_contra]\", x: T1_contra) -> None:\n ...\n\n @classmethod\n def m2(cls: \"type[Protocol13[T1_contra]]\") -> None:\n ...\n\n\nclass Protocol14(Protocol[T1]): # OK\n def m1(self) -> list[T1]:\n ...\n","source":"typing_tests","origin":"conformance/tests/protocols_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"required-notrequired","pep":"655","introduced_in":"3.11","form":"modern","file":"required-notrequired/modern_01.py","code":"\"\"\"\nTests the Required and NotRequired special forms.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#required-and-notrequired\n\nfrom typing import Annotated, NotRequired, Required, TypedDict\n\n\n# Required and NotRequired are valid only within a TypedDict.\nclass NotTypedDict:\n x: Required[int] # E: Required not allowed in this context\n\n\ndef func1(\n x: NotRequired[int], # E: NotRequired not allowed in this context\n) -> None:\n pass\n\n\nclass TD1(TypedDict, total=False):\n a: int\n\n\nclass TD2(TD1, total=True):\n b: int\n\n\nclass TD3(TypedDict):\n a: NotRequired[int]\n b: Required[int]\n\n\nclass TD4(TypedDict, total=False):\n a: int\n b: Required[int]\n\n\nclass TD5(TypedDict, total=True):\n a: NotRequired[int]\n b: int\n\n\ntd3: TD3 = {\"b\": 0}\ntd4: TD4 = {\"b\": 0}\ntd5: TD5 = {\"b\": 0}\n\n# These are all equivalent types, so they should be\n# bidirectionally type compatible.\ntd3 = td4\ntd3 = td5\ntd4 = td3\ntd4 = td5\ntd5 = td3\ntd5 = td4\n\n\nclass TD6(TypedDict):\n a: Required[Required[int]] # E: Nesting not allowed\n b: Required[NotRequired[int]] # E: Nesting not allowed\n\n\nclass TD7(TypedDict):\n # > Required[] and NotRequired[] can be used with Annotated[], in any nesting order.\n x: Annotated[Required[int], \"\"]\n y: Required[Annotated[int, \"\"]]\n z: Annotated[Required[Annotated[int, \"\"]], \"\"]\n\n\nRecursiveMovie = TypedDict(\n \"RecursiveMovie\", {\"title\": Required[str], \"predecessor\": NotRequired[\"RecursiveMovie\"]}\n)\n\nmovie: RecursiveMovie = {\"title\": \"Beethoven 3\", \"predecessor\": {\"title\": \"Beethoven 2\"}}\n","source":"typing_tests","origin":"conformance/tests/typeddicts_required.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_01.py","code":"\"\"\"\nTests for advanced or special-case usage of the typing.Self type.\n\"\"\"\n\nfrom typing import assert_type, Self\n\n\nclass ParentA:\n # Test for property that returns Self.\n @property\n def prop1(self) -> Self:\n raise NotImplementedError\n\nclass ChildA(ParentA):\n ...\n\n\nassert_type(ParentA().prop1, ParentA)\nassert_type(ChildA().prop1, ChildA)\n\n\n# Test for a child that accesses an attribute within a parent\n# whose type is annotated using Self.\nclass ParentB:\n a: list[Self]\n\n @classmethod\n def method1(cls) -> Self:\n raise NotImplementedError\n\nclass ChildB(ParentB):\n b: int = 0\n\n def method2(self) -> None:\n assert_type(self, Self)\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = self.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(self.method1(), Self)\n\n @classmethod\n def method3(cls) -> None:\n assert_type(cls, type[Self])\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = cls.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(cls.method1(), Self)\n","source":"typing_tests","origin":"conformance/tests/generics_self_advanced.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_02.py","code":"\"\"\"\nTests for usage of the typing.Self type with attributes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-attribute-annotations\n\nfrom typing import TypeVar, Generic, Self\nfrom dataclasses import dataclass\n\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass LinkedList(Generic[T]):\n value: T\n next: Self | None = None\n\n\n@dataclass\nclass OrdinalLinkedList(LinkedList[int]):\n def ordinal_value(self) -> str:\n return str(self.value)\n\n\n# This should result in a type error.\nxs = OrdinalLinkedList(value=1, next=LinkedList[int](value=2)) # E\n\nif xs.next is not None:\n xs.next = OrdinalLinkedList(value=3, next=None) # OK\n\n # This should result in a type error.\n xs.next = LinkedList[int](value=3, next=None) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_attributes.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_03.py","code":"\"\"\"\nTests for basic usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#self.\n\nfrom typing import Callable, Generic, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n\nclass Shape:\n def set_scale(self, scale: float) -> Self:\n assert_type(self, Self)\n self.scale = scale\n return self\n\n def method2(self) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n def method3(self) -> \"Shape\":\n return self\n\n @classmethod\n def from_config(cls, config: dict[str, float]) -> Self:\n assert_type(cls, type[Self])\n return cls()\n\n @classmethod\n def cls_method2(cls) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n @classmethod\n def cls_method3(cls) -> \"Shape\":\n return cls()\n\n def difference(self, other: Self) -> float:\n assert_type(other, Self)\n return 0.0\n\n def apply(self, f: Callable[[Self], None]) -> None:\n return f(self)\n\n\nclass Circle(Shape):\n pass\n\n\nassert_type(Shape().set_scale(1.0), Shape)\nassert_type(Circle().set_scale(1.0), Circle)\n\nassert_type(Shape.from_config({}), Shape)\nassert_type(Circle.from_config({}), Circle)\n\n\nclass Container(Generic[T]):\n value: T\n\n def __init__(self, value: T) -> None:\n self.value = value\n\n def set_value(self, value: T) -> Self:\n raise NotImplementedError\n\n # This should generate an error because Self isn't subscriptable.\n def foo(self, other: Self[int]) -> None: # E\n pass\n\n\ndef object_with_concrete_type(\n int_container: Container[int], str_container: Container[str]\n) -> None:\n assert_type(int_container.set_value(42), Container[int])\n assert_type(str_container.set_value(\"hello\"), Container[str])\n\n\ndef object_with_generic_type(\n container: Container[T],\n value: T,\n) -> Container[T]:\n val = container.set_value(value)\n assert_type(val, Container[T])\n return val\n","source":"typing_tests","origin":"conformance/tests/generics_self_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_04.py","code":"\"\"\"\nTests for usage of the typing.Self type with protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n\nfrom typing import Protocol, Self, assert_type\n\n\nclass ShapeProtocol(Protocol):\n def set_scale(self, scale: float) -> Self:\n ...\n\n\nclass ReturnSelf:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> Self:\n self.scale = scale\n return self\n\n\nclass ReturnConcreteShape:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> \"ReturnConcreteShape\":\n self.scale = scale\n return self\n\n\nclass BadReturnType:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> int:\n self.scale = scale\n return 42\n\n\nclass ReturnDifferentClass:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> ReturnConcreteShape:\n return ReturnConcreteShape()\n\n\ndef accepts_shape(shape: ShapeProtocol) -> None:\n y = shape.set_scale(0.5)\n assert_type(y, ShapeProtocol)\n\n\ndef main(\n return_self_shape: ReturnSelf,\n return_concrete_shape: ReturnConcreteShape,\n bad_return_type: BadReturnType,\n return_different_class: ReturnDifferentClass,\n) -> None:\n accepts_shape(return_self_shape) # OK\n accepts_shape(return_concrete_shape) # OK\n\n # This should generate a type error.\n accepts_shape(bad_return_type) # E\n\n # Not OK because it returns a non-subclass.\n accepts_shape(return_different_class) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_protocols.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_05.py","code":"\"\"\"\nTests for valid and invalid usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#valid-locations-for-self\n\nfrom typing import Any, Callable, Generic, Self, TypeAlias, TypeVar\n\nclass ReturnsSelf:\n def foo(self) -> Self: # Accepted\n return self\n\n @classmethod\n def bar(cls) -> Self: # Accepted\n return cls(1)\n\n def __new__(cls, value: int) -> Self: # Accepted\n return cls(1)\n\n def explicitly_use_self(self: Self) -> Self: # Accepted\n return self\n\n # Accepted (Self can be nested within other types)\n def returns_list(self) -> list[Self]:\n return []\n\n # Accepted (Self can be nested within other types)\n @classmethod\n def return_cls(cls) -> type[Self]:\n return cls\n\nclass Child(ReturnsSelf):\n # Accepted (we can override a method that uses Self annotations)\n def foo(self) -> Self:\n return self\n\nclass TakesSelf:\n def foo(self, other: Self) -> bool: # Accepted\n return True\n\nclass Recursive:\n # Accepted (treated as an @property returning ``Self | None``)\n next: Self | None\n\nclass CallableAttribute:\n def foo(self) -> int:\n return 0\n\n # Accepted (treated as an @property returning the Callable type)\n bar: Callable[[Self], int] = foo\n\nclass HasNestedFunction:\n x: int = 42\n\n def foo(self) -> None:\n\n # Accepted (Self is bound to HasNestedFunction).\n def nested(z: int, inner_self: Self) -> Self:\n print(z)\n print(inner_self.x)\n return inner_self\n\n nested(42, self) # OK\n\n\nclass Outer:\n class Inner:\n def foo(self) -> Self: # Accepted (Self is bound to Inner)\n return self\n\n\n# This should generate an error.\ndef foo(bar: Self) -> Self: ... # E: not within a class\n\n# This should generate an error.\nbar: Self # E: not within a class\n\nTFoo2 = TypeVar(\"TFoo2\", bound=\"Foo2\")\n\nclass Foo2:\n # Rejected (Self is treated as unknown).\n def has_existing_self_annotation(self: TFoo2) -> Self: # E\n raise NotImplementedError\n\nclass Foo3:\n def return_concrete_type(self) -> Self:\n return Foo3() # E (see FooChild below for rationale)\n\nclass Foo3Child(Foo3):\n child_value: int = 42\n\n def child_method(self) -> None:\n y = self.return_concrete_type()\n y.child_value\n\nT = TypeVar(\"T\")\n\nclass Bar(Generic[T]):\n def bar(self) -> T:\n raise NotImplementedError\n\n# This should generate an error.\nclass Baz(Bar[Self]): ... # E\n\nclass Baz2(Self): ... # E\n\n# This should generate an error.\nTupleSelf: TypeAlias = tuple[Self] # E\n\nclass Base:\n @staticmethod\n # This should generate an error.\n def make() -> Self: # E\n raise NotImplementedError\n\n @staticmethod\n # This should generate an error.\n def return_parameter(foo: Self) -> Self: # E\n raise NotImplementedError\n\nclass MyMetaclass(type):\n # This should generate an error.\n def __new__(cls, *args: Any) -> Self: # E\n raise NotImplementedError\n\n # This should generate an error.\n def __mul__(cls, count: int) -> list[Self]: # E\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_self_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_01.py","code":"\"\"\"\nTests explicit type aliases defined with `TypeAlias`.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#typealias\n\nfrom typing import Any, Callable, Concatenate, Literal, ParamSpec, TypeVar, Union, assert_type\nfrom typing import TypeAlias as TA\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1: TA = Union[int, str]\nGoodTypeAlias2: TA = int | None\nGoodTypeAlias3: TA = list[GoodTypeAlias2]\nGoodTypeAlias4: TA = list[T]\nGoodTypeAlias5: TA = tuple[T, ...] | list[T]\nGoodTypeAlias6: TA = tuple[int, int, S, T]\nGoodTypeAlias7: TA = Callable[..., int]\nGoodTypeAlias8: TA = Callable[[int, T], T]\nGoodTypeAlias9: TA = Callable[Concatenate[int, P], R]\nGoodTypeAlias10: TA = Any\nGoodTypeAlias11: TA = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12: TA = Callable[P, None]\nGoodTypeAlias13: TA = \"int | str\"\nGoodTypeAlias14: TA = list[\"int | str\"]\nGoodTypeAlias15: TA = Literal[3, 4, 5, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12,\n p13: GoodTypeAlias13,\n p14: GoodTypeAlias14,\n p15: GoodTypeAlias15,\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, Callable[..., None])\n assert_type(p13, int | str)\n assert_type(p14, list[int | str])\n assert_type(p15, Literal[3, 4, 5, None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be allowed as type aliases.\nBadTypeAlias1: TA = eval(\"\".join(map(chr, [105, 110, 116]))) # E\nBadTypeAlias2: TA = [int, str] # E\nBadTypeAlias3: TA = ((int, str),) # E\nBadTypeAlias4: TA = [int for i in range(1)] # E\nBadTypeAlias5: TA = {\"a\": \"b\"} # E\nBadTypeAlias6: TA = (lambda: int)() # E\nBadTypeAlias7: TA = [int][0] # E\nBadTypeAlias8: TA = int if 1 < 3 else str # E\nBadTypeAlias9: TA = var1 # E\nBadTypeAlias10: TA = True # E\nBadTypeAlias11: TA = 1 # E\nBadTypeAlias12: TA = list or set # E\nBadTypeAlias13: TA = f\"{'int'}\" # E\n\n\nListAlias: TA = list\nListOrSetAlias: TA = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2: ListAlias[int] # E: already specialized\nx3 = ListOrSetAlias() # E: cannot instantiate union\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_02.py","code":"\"\"\"\nTests recursive (self-referential) type aliases.\n\"\"\"\n\n# The typing specification doesn't mandate support for recursive\n# (self-referential) type aliases prior to PEP 695, but it also\n# doesn't indicates that they shouldn't work.\n# Most type checkers now support them, and many libraries and code\n# bases have started to rely on them.\n# PEP 695 formally mandates that recursive type aliases work.\n\nfrom typing import Mapping, TypeAlias, TypeVar, Union\n\nJson = Union[None, int, str, float, list[\"Json\"], dict[str, \"Json\"]]\n\nj1: Json = [1, {\"a\": 1}] # OK\nj2: Json = 3.4 # OK\nj3: Json = [1.2, None, [1.2, [\"\"]]] # OK\nj4: Json = {\"a\": 1, \"b\": 3j} # E: incompatible type\nj5: Json = [2, 3j] # E: incompatible type\n\n\n# This type alias should be equivalent to Json.\nJson2 = Union[None, int, str, float, list[\"Json2\"], dict[str, \"Json2\"]]\n\ndef func1(j1: Json) -> Json2:\n return j1\n\n\nRecursiveTuple = str | int | tuple[\"RecursiveTuple\", ...]\n\n\nt1: RecursiveTuple = (1, 1) # OK\nt2: RecursiveTuple = (1, \"1\") # OK\nt3: RecursiveTuple = (1, \"1\", 1, \"2\") # OK\nt4: RecursiveTuple = (1, (\"1\", 1), \"2\") # OK\nt5: RecursiveTuple = (1, (\"1\", 1), (1, (1, 2))) # OK\nt6: RecursiveTuple = (1, (\"1\", 1), (1, (1, [2]))) # E\nt7: RecursiveTuple = (1, [1]) # E\n\n\nRecursiveMapping = str | int | Mapping[str, \"RecursiveMapping\"]\n\nm1: RecursiveMapping = 1 # OK\nm2: RecursiveMapping = \"1\" # OK\nm3: RecursiveMapping = {\"1\": \"1\"} # OK\nm4: RecursiveMapping = {\"1\": \"1\", \"2\": 1} # OK\nm5: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {}} # OK\nm6: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": \"2\", \"2\": {}}} # OK\nm7: RecursiveMapping = {\"1\": [1]} # E\nm8: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": [1, 2]} # E\nm9: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": 1, \"2\": [1, 2, 3]}} # E\n\n\nT1 = TypeVar(\"T1\", str, int)\nT2 = TypeVar(\"T2\")\n\nGenericTypeAlias1 = list[\"GenericTypeAlias1[T1]\" | T1]\nSpecializedTypeAlias1 = GenericTypeAlias1[str]\n\ng1: SpecializedTypeAlias1 = [\"hi\", [\"hi\", \"hi\"]] # OK\ng2: GenericTypeAlias1[str] = [\"hi\", \"bye\", [\"\"], [[\"hi\"]]] # OK\ng3: GenericTypeAlias1[str] = [\"hi\", [2.4]] # E\n\nGenericTypeAlias2 = list[\"GenericTypeAlias2[T1, T2]\" | T1 | T2]\n\ng4: GenericTypeAlias2[str, int] = [[3, [\"hi\"]], \"hi\"] # OK\ng5: GenericTypeAlias2[str, float] = [[3, [\"hi\", 3.4, [3.4]]], \"hi\"] # OK\ng6: GenericTypeAlias2[str, int] = [[3, [\"hi\", 3, [3.4]]], \"hi\"] # E\n\n\nRecursiveUnion: TypeAlias = Union[\"RecursiveUnion\", int] # E: cyclical reference\n\n# On one line because different type checkers report the error on different lines\nMutualReference1: TypeAlias = Union[\"MutualReference2\", int]; MutualReference2: TypeAlias = Union[\"MutualReference1\", str] # E: cyclical reference\n","source":"typing_tests","origin":"conformance/tests/aliases_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-guard","pep":"647","introduced_in":"3.10","form":"modern","file":"type-guard/modern_01.py","code":"\"\"\"\nTests TypeGuard functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeguard\n\nfrom typing import Any, Callable, Protocol, Self, TypeGuard, TypeVar, assert_type\n\n\nT = TypeVar(\"T\")\n\ndef is_two_element_tuple(val: tuple[T, ...]) -> TypeGuard[tuple[T, T]]:\n return len(val) == 2\n\ndef func1(names: tuple[str, ...]):\n if is_two_element_tuple(names):\n assert_type(names, tuple[str, str])\n else:\n assert_type(names, tuple[str, ...])\n\n\ndef is_str_list(val: list[object], allow_empty: bool) -> TypeGuard[list[str]]:\n if len(val) == 0:\n return allow_empty\n return all(isinstance(x, str) for x in val)\n\ndef is_set_of(val: set[Any], type: type[T]) -> TypeGuard[set[T]]:\n return all(isinstance(x, type) for x in val)\n\ndef func2(val: set[object]):\n if is_set_of(val, int):\n assert_type(val, set[int])\n else:\n assert_type(val, set[object])\n\n\nT_A = TypeVar(\"T_A\", bound=\"A\")\n\nclass A:\n def tg_1(self, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @classmethod\n def tg_2(cls, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @staticmethod\n def tg_3(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n def tg4(self, val: object) -> TypeGuard[Self]:\n return isinstance(val, type(self))\n\n def tg5(self: T_A, val: object) -> TypeGuard[T_A]:\n return isinstance(val, type(self))\n\nclass B(A):\n pass\n\n# > Type checkers should assume that type narrowing should be applied to\n# > the expression that is passed as the first positional argument to a\n# > user-defined type guard. If the type guard function accepts more than\n# > one argument, no type narrowing is applied to those additional argument\n# > expressions.\n\ndef func3() -> None:\n val1 = object()\n if A().tg_1(val1):\n assert_type(val1, int)\n\n val2 = object()\n if A().tg_2(val2):\n assert_type(val2, int)\n\n val3 = object()\n if A.tg_2(val3):\n assert_type(val3, int)\n\n val4 = object()\n if A().tg_3(val4):\n assert_type(val4, int)\n\n val5 = object()\n if A.tg_3(val5):\n assert_type(val5, int)\n\n val6 = object()\n if B().tg4(val6):\n assert_type(val6, B)\n\n val7 = object()\n if B().tg4(val7):\n assert_type(val7, B)\n\n\n# > If a type guard function is implemented as an instance method or class\n# > method, the first positional argument maps to the second parameter\n# > (after “self” or “cls”).\n\nclass C:\n # Type checker should emit error here.\n def tg_1(self) -> TypeGuard[int]: # E\n return False\n\n @classmethod\n # Type checker should emit error here.\n def tg_2(cls) -> TypeGuard[int]: # E\n return False\n\n# > ``TypeGuard`` is also valid as the return type of a ``Callable`` type. In that\n# > context, it is treated as a subtype of bool. For example, ``Callable[..., TypeGuard[int]]``\n# > is assignable to ``Callable[..., bool]``.\n\n\ndef takes_callable_bool(f: Callable[[object], bool]) -> None:\n pass\n\n\ndef takes_callable_str(f: Callable[[object], str]) -> None:\n pass\n\n\ndef simple_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ntakes_callable_bool(simple_typeguard) # OK\ntakes_callable_str(simple_typeguard) # E\n\n\nclass CallableBoolProto(Protocol):\n def __call__(self, val: object) -> bool: ...\n\n\nclass CallableStrProto(Protocol):\n def __call__(self, val: object) -> str: ...\n\n\ndef takes_callable_bool_proto(f: CallableBoolProto) -> None:\n pass\n\n\ndef takes_callable_str_proto(f: CallableStrProto) -> None:\n pass\n\n\ntakes_callable_bool_proto(simple_typeguard) # OK\ntakes_callable_str_proto(simple_typeguard) # E\n\n# > Unlike ``TypeGuard``, ``TypeIs`` is invariant in its argument type:\n# > ``TypeIs[B]`` is not a subtype of ``TypeIs[A]``,\n# > even if ``B`` is a subtype of ``A``.\n\ndef takes_int_typeguard(f: Callable[[object], TypeGuard[int]]) -> None:\n pass\n\n\ndef int_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ndef bool_typeguard(val: object) -> TypeGuard[bool]:\n return isinstance(val, bool)\n\n\ntakes_int_typeguard(int_typeguard) # OK\ntakes_int_typeguard(bool_typeguard) # OK\n","source":"typing_tests","origin":"conformance/tests/narrowing_typeguard.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests Callable annotation and parameter annotations for \"def\" statements.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#callable\n\nfrom typing import (\n Any,\n Callable,\n Concatenate,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n assert_type,\n)\n\nT_contra = TypeVar(\"T_contra\", contravariant=True)\nP = ParamSpec(\"P\")\n\n\ndef func1(cb: Callable[[int, str], list[str]]) -> None:\n assert_type(cb(1, \"\"), list[str])\n\n cb(1) # E\n cb(1, 2) # E\n cb(1, \"\", 1) # E\n # Mypy reports two errors, one for each kwarg.\n cb(a=1, b=\"\") # E: bad kwarg 'a'\n\n\ndef func2(cb: Callable[[], dict[str, str]]) -> None:\n assert_type(cb(), dict[str, str])\n\n cb(1) # E\n\n\n# https://typing.readthedocs.io/en/latest/spec/callables.html#meaning-of-in-callable\n\n\n# > The Callable special form supports the use of ... in place of the list of\n# > parameter types. This indicates that the type is consistent with any input\n# > signature.\ndef func3(cb: Callable[..., list[str]]):\n assert_type(cb(), list[str])\n assert_type(cb(\"\"), list[str])\n assert_type(cb(1, \"\"), list[str])\n\n\ndef func4(*args: int, **kwargs: int) -> None:\n assert_type(args, tuple[int, ...])\n assert_type(kwargs, dict[str, int])\n\n\nv1: Callable[int] # E\nv2: Callable[int, int] # E\nv3: Callable[[], [int]] # E\nv4: Callable[int, int, int] # E\nv5: Callable[[...], int] # E\n\n\ndef test_cb1(x: int) -> str:\n return \"\"\n\n\ndef test_cb2() -> str:\n return \"\"\n\n\ncb1: Callable[..., str]\ncb1 = test_cb1 # OK\ncb1 = test_cb2 # OK\n\ncb2: Callable[[], str] = cb1 # OK\n\n# > A ... can also be used with Concatenate. In this case, the parameters prior\n# > to the ... are required to be present in the input signature and be\n# > compatible in kind and type, but any additional parameters are permitted.\n\n\ndef test_cb3(a: int, b: int, c: int) -> str:\n return \"\"\n\n\ndef test_cb4(*, a: int) -> str:\n return \"\"\n\n\ncb3: Callable[Concatenate[int, ...], str]\ncb3 = test_cb1 # OK\ncb3 = test_cb2 # E\ncb3 = test_cb3 # OK\ncb3 = test_cb4 # E\n\n# > If the input signature in a function definition includes both a *args and\n# > **kwargs parameter and both are typed as Any (explicitly or implicitly\n# > because it has no annotation), a type checker should treat this as the\n# > equivalent of `...`. Any other parameters in the signature are unaffected\n# > and are retained as part of the signature.\n\n\nclass Proto1(Protocol):\n def __call__(self, *args: Any, **kwargs: Any) -> None: ...\n\n\nclass Proto2(Protocol):\n def __call__(self, a: int, /, *args, **kwargs) -> None: ...\n\n\nclass Proto3(Protocol):\n def __call__(self, a: int, *args: Any, **kwargs: Any) -> None: ...\n\n\nclass Proto4[**P](Protocol):\n def __call__(self, a: int, *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n\nclass Proto5(Protocol[T_contra]):\n def __call__(self, *args: T_contra, **kwargs: T_contra) -> None: ...\n\n\nclass Proto6(Protocol):\n def __call__(self, a: int, /, *args: Any, k: str, **kwargs: Any) -> None:\n pass\n\n\nclass Proto7(Protocol):\n def __call__(self, a: float, /, b: int, *, k: str, m: str) -> None:\n pass\n\n\nclass Proto8(Protocol):\n def __call__(self) -> None: ...\n\n\ndef func5(\n p1: Proto1,\n p2: Proto2,\n p3: Proto3,\n p4: Proto4[...],\n p5: Proto5[Any],\n p7: Proto7,\n p8: Proto8,\n c1: Callable[..., None],\n c2: Callable[Concatenate[int, ...], None],\n):\n ok1: Callable[..., None] = p1 # OK\n ok2: Proto1 = c1 # OK\n ok3: Callable[..., None] = p5 # OK\n ok4: Proto5[Any] = c1 # OK\n ok5: Callable[Concatenate[int, ...], None] = p2 # OK\n ok6: Proto2 = c2 # OK\n ok7: Callable[..., None] = p3 # OK\n ok8: Proto3 = c1 # OK\n ok9: Proto4[...] = p3 # OK\n ok10: Proto3 = p4 # OK\n ok11: Proto6 = p7 # OK\n\n err1: Proto5[Any] = p8 # E\n\n\n# > The ... syntax can also be used to provide a specialized value for a\n# > ParamSpec in a generic class or type alias.\n\n\nCallback1: TypeAlias = Callable[P, str]\nCallback2: TypeAlias = Callable[Concatenate[int, P], str]\n\n\ndef func6(cb1: Callable[[], str], cb2: Callable[[int], str]) -> None:\n f1: Callback1[...] = cb1 # OK\n f2: Callback2[...] = cb1 # E\n\n f3: Callback1[...] = cb2 # OK\n f4: Callback2[...] = cb2 # OK\n\n\n# > If ... is used with signature concatenation, the ... portion continues\n# > to mean “any conceivable set of parameters that could be compatible”.\n\nCallbackWithInt: TypeAlias = Callable[Concatenate[int, P], str]\nCallbackWithStr: TypeAlias = Callable[Concatenate[str, P], str]\n\n\ndef func7(cb: Callable[[int, str], str]) -> None:\n f1: Callable[Concatenate[int, ...], str] = cb # OK\n f2: Callable[Concatenate[str, ...], str] = cb # E\n f3: CallbackWithInt[...] = cb # OK\n f4: CallbackWithStr[...] = cb # E\n","source":"typing_tests","origin":"conformance/tests/callables_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests subtyping rules for callables.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#subtyping-rules-for-callables\n\nfrom typing import Callable, ParamSpec, Protocol, TypeAlias, overload\n\nP = ParamSpec(\"P\")\n\n# > Callable types are covariant with respect to their return types but\n# > contravariant with respect to their parameter types.\n\n\ndef func1(\n cb1: Callable[[float], int],\n cb2: Callable[[float], float],\n cb3: Callable[[int], int],\n) -> None:\n f1: Callable[[int], float] = cb1 # OK\n f2: Callable[[int], float] = cb2 # OK\n f3: Callable[[int], float] = cb3 # OK\n\n f4: Callable[[float], float] = cb1 # OK\n f5: Callable[[float], float] = cb2 # OK\n f6: Callable[[float], float] = cb3 # E\n\n f7: Callable[[int], int] = cb1 # OK\n f8: Callable[[int], int] = cb2 # E\n f9: Callable[[int], int] = cb3 # OK\n\n\n# > Callable A is a subtype of callable B if all keyword-only parameters in B\n# > are present in A as either keyword-only parameters or standard (positional\n# > or keyword) parameters.\n\n\nclass PosOnly2(Protocol):\n def __call__(self, b: int, a: int, /) -> None: ...\n\n\nclass KwOnly2(Protocol):\n def __call__(self, *, b: int, a: int) -> None: ...\n\n\nclass Standard2(Protocol):\n def __call__(self, a: int, b: int) -> None: ...\n\n\ndef func2(standard: Standard2, pos_only: PosOnly2, kw_only: KwOnly2):\n f1: Standard2 = pos_only # E\n f2: Standard2 = kw_only # E\n\n f3: PosOnly2 = standard # OK\n f4: PosOnly2 = kw_only # E\n\n f5: KwOnly2 = standard # OK\n f6: KwOnly2 = pos_only # E\n\n\n# > If a callable B has a signature with a *args parameter, callable A\n# > must also have a *args parameter to be a subtype of B, and the type of\n# > B’s *args parameter must be a subtype of A’s *args parameter.\n\n\nclass NoArgs3(Protocol):\n def __call__(self) -> None: ...\n\n\nclass IntArgs3(Protocol):\n def __call__(self, *args: int) -> None: ...\n\n\nclass FloatArgs3(Protocol):\n def __call__(self, *args: float) -> None: ...\n\n\ndef func3(no_args: NoArgs3, int_args: IntArgs3, float_args: FloatArgs3):\n f1: NoArgs3 = int_args # OK\n f2: NoArgs3 = float_args # OK\n\n f3: IntArgs3 = no_args # E: missing *args parameter\n f4: IntArgs3 = float_args # OK\n\n f5: FloatArgs3 = no_args # E: missing *args parameter\n f6: FloatArgs3 = int_args # E: float is not subtype of int\n\n\n# > If a callable B has a signature with one or more positional-only parameters,\n# > a callable A is a subtype of B if A has an *args parameter whose type is a\n# > supertype of the types of any otherwise-unmatched positional-only parameters\n# > in B.\n\n\nclass PosOnly4(Protocol):\n def __call__(self, a: int, b: str, /) -> None: ...\n\n\nclass IntArgs4(Protocol):\n def __call__(self, *args: int) -> None: ...\n\n\nclass IntStrArgs4(Protocol):\n def __call__(self, *args: int | str) -> None: ...\n\n\nclass StrArgs4(Protocol):\n def __call__(self, a: int, /, *args: str) -> None: ...\n\n\nclass Standard4(Protocol):\n def __call__(self, a: int, b: str) -> None: ...\n\n\ndef func4(int_args: IntArgs4, int_str_args: IntStrArgs4, str_args: StrArgs4):\n f1: PosOnly4 = int_args # E: str is not subtype of int\n f2: PosOnly4 = int_str_args # OK\n f3: PosOnly4 = str_args # OK\n f4: IntStrArgs4 = str_args # E: int | str is not subtype of str\n f5: IntStrArgs4 = int_args # E: int | str is not subtype of int\n f6: StrArgs4 = int_str_args # OK\n f7: StrArgs4 = int_args # E: str is not subtype of int\n f8: IntArgs4 = int_str_args # OK\n f9: IntArgs4 = str_args # E: int is not subtype of str\n f10: Standard4 = int_str_args # E: keyword parameters a and b missing\n f11: Standard4 = str_args # E: keyword parameter b missing\n\n\n# > If a callable B has a signature with a **kwargs parameter (without an\n# > unpacked TypedDict type annotation), callable A must also have a **kwargs\n# > parameter to be a subtype of B, and the type of B’s **kwargs parameter\n# > must be a subtype of A’s **kwargs parameter.\n\n\nclass NoKwargs5(Protocol):\n def __call__(self) -> None: ...\n\n\nclass IntKwargs5(Protocol):\n def __call__(self, **kwargs: int) -> None: ...\n\n\nclass FloatKwargs5(Protocol):\n def __call__(self, **kwargs: float) -> None: ...\n\n\ndef func5(no_kwargs: NoKwargs5, int_kwargs: IntKwargs5, float_kwargs: FloatKwargs5):\n f1: NoKwargs5 = int_kwargs # OK\n f2: NoKwargs5 = float_kwargs # OK\n\n f3: IntKwargs5 = no_kwargs # E: missing **kwargs parameter\n f4: IntKwargs5 = float_kwargs # OK\n\n f5: FloatKwargs5 = no_kwargs # E: missing **kwargs parameter\n f6: FloatKwargs5 = int_kwargs # E: float is not subtype of int\n\n\n# > If a callable B has a signature with one or more keyword-only parameters,\n# > a callable A is a subtype of B if A has a **kwargs parameter whose type\n# > is a supertype of the types of any otherwise-unmatched keyword-only\n# > parameters in B.\n\n\nclass KwOnly6(Protocol):\n def __call__(self, *, a: int, b: str) -> None: ...\n\n\nclass IntKwargs6(Protocol):\n def __call__(self, **kwargs: int) -> None: ...\n\n\nclass IntStrKwargs6(Protocol):\n def __call__(self, **kwargs: int | str) -> None: ...\n\n\nclass StrKwargs6(Protocol):\n def __call__(self, *, a: int, **kwargs: str) -> None: ...\n\n\nclass Standard6(Protocol):\n def __call__(self, a: int, b: str) -> None: ...\n\n\ndef func6(\n int_kwargs: IntKwargs6, int_str_kwargs: IntStrKwargs6, str_kwargs: StrKwargs6\n):\n f1: KwOnly6 = int_kwargs # E: str is not subtype of int\n f2: KwOnly6 = int_str_kwargs # OK\n f3: KwOnly6 = str_kwargs # OK\n f4: IntStrKwargs6 = str_kwargs # E: int | str is not subtype of str\n f5: IntStrKwargs6 = int_kwargs # E: int | str is not subtype of int\n f6: StrKwargs6 = int_str_kwargs # OK\n f7: StrKwargs6 = int_kwargs # E: str is not subtype of int\n f8: IntKwargs6 = int_str_kwargs # OK\n f9: IntKwargs6 = str_kwargs # E: int is not subtype of str\n f10: Standard6 = int_str_kwargs # E: Does not accept positional arguments\n f11: Standard6 = str_kwargs # E: Does not accept positional arguments\n\n\n# > A signature that includes *args: P.args, **kwargs: P.kwargs is equivalent\n# > to a Callable parameterized by P.\n\n\nclass ProtocolWithP[**P](Protocol):\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n\nTypeAliasWithP: TypeAlias = Callable[P, None]\n\n\ndef func7(proto: ProtocolWithP[P], ta: TypeAliasWithP[P]):\n # These two types are equivalent\n f1: TypeAliasWithP[P] = proto # OK\n f2: ProtocolWithP[P] = ta # OK\n\n\n# > If a callable A has a parameter x with a default argument value and B is\n# > the same as A except that x has no default argument, then A is a subtype\n# > of B. A is also a subtype of C if C is the same as A with parameter x\n# > removed.\n\n\nclass DefaultArg8(Protocol):\n def __call__(self, x: int = 0) -> None: ...\n\n\nclass NoDefaultArg8(Protocol):\n def __call__(self, x: int) -> None: ...\n\n\nclass NoX8(Protocol):\n def __call__(self) -> None: ...\n\n\ndef func8(default_arg: DefaultArg8, no_default_arg: NoDefaultArg8, no_x: NoX8):\n f1: DefaultArg8 = no_default_arg # E\n f2: DefaultArg8 = no_x # E\n\n f3: NoDefaultArg8 = default_arg # OK\n f4: NoDefaultArg8 = no_x # E\n\n f5: NoX8 = default_arg # OK\n f6: NoX8 = no_default_arg # E\n\n\n# > If a callable A is overloaded with two or more signatures, it is a subtype\n# > of callable B if at least one of the overloaded signatures in A is a\n# > subtype of B.\n\n\nclass Overloaded9(Protocol):\n @overload\n def __call__(self, x: int) -> int: ...\n @overload\n def __call__(self, x: str) -> str: ...\n\n\nclass IntArg9(Protocol):\n def __call__(self, x: int) -> int: ...\n\n\nclass StrArg9(Protocol):\n def __call__(self, x: str) -> str: ...\n\n\nclass FloatArg9(Protocol):\n def __call__(self, x: float) -> float: ...\n\n\ndef func9(overloaded: Overloaded9):\n f1: IntArg9 = overloaded # OK\n f2: StrArg9 = overloaded # OK\n f3: FloatArg9 = overloaded # E\n\n\n# > If a callable B is overloaded with two or more signatures, callable A is\n# > a subtype of B if A is a subtype of all of the signatures in B.\n\n\nclass Overloaded10(Protocol):\n @overload\n def __call__(self, x: int, y: str) -> float: ...\n @overload\n def __call__(self, x: str) -> complex: ...\n\n\nclass StrArg10(Protocol):\n def __call__(self, x: str) -> complex: ...\n\n\nclass IntStrArg10(Protocol):\n def __call__(self, x: int | str, y: str = \"\") -> int: ...\n\n\ndef func10(int_str_arg: IntStrArg10, str_arg: StrArg10):\n f1: Overloaded10 = int_str_arg # OK\n f2: Overloaded10 = str_arg # E\n","source":"typing_tests","origin":"conformance/tests/callables_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_24.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_25.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_07.py","code":"\"\"\"\nTests the \"type\" statement introduced in Python 3.12.\n\"\"\"\n\nfrom typing import Callable, TypeVar\n\n\ntype GoodAlias1 = int\ntype GoodAlias2[S1, *S2, **S3] = Callable[S3, S1] | tuple[*S2]\ntype GoodAlias3 = GoodAlias2[int, tuple[int, str], ...]\n\n\nclass ClassA:\n type GoodAlias4 = int | None\n\n\nGoodAlias1.bit_count # E: cannot access attribute\n\nGoodAlias1() # E: cannot call alias\n\nprint(GoodAlias1.__value__) # OK\nprint(GoodAlias1.__type_params__) # OK\nprint(GoodAlias1.other_attrib) # E: unknown attribute\n\n\nclass DerivedInt(GoodAlias1): # E: cannot use alias as base class\n pass\n\n\ndef func2(x: object):\n if isinstance(x, GoodAlias1): # E: cannot use alias in isinstance\n pass\n\nvar1 = 1\n\n# The following should not be allowed as type aliases.\ntype BadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116]))) # E\ntype BadTypeAlias2 = [int, str] # E\ntype BadTypeAlias3 = ((int, str),) # E\ntype BadTypeAlias4 = [int for i in range(1)] # E\ntype BadTypeAlias5 = {\"a\": \"b\"} # E\ntype BadTypeAlias6 = (lambda: int)() # E\ntype BadTypeAlias7 = [int][0] # E\ntype BadTypeAlias8 = int if 1 < 3 else str # E\ntype BadTypeAlias9 = var1 # E\ntype BadTypeAlias10 = True # E\ntype BadTypeAlias11 = 1 # E\ntype BadTypeAlias12 = list or set # E\ntype BadTypeAlias13 = f\"{'int'}\" # E\n\nV = TypeVar(\"V\")\n\ntype TA1[K] = dict[K, V] # E: combines old and new TypeVars\n\n\nT1 = TypeVar(\"T1\")\n\ntype TA2 = list[T1] # E: uses old TypeVar\n\n\ntype RecursiveTypeAlias1[T] = T | list[RecursiveTypeAlias1[T]]\n\nr1_1: RecursiveTypeAlias1[int] = 1\nr1_2: RecursiveTypeAlias1[int] = [1, [1, 2, 3]]\n\ntype RecursiveTypeAlias2[S: int, T: str, **P] = Callable[P, T] | list[S] | list[RecursiveTypeAlias2[S, T, P]]\n\nr2_1: RecursiveTypeAlias2[str, str, ...] # E: not compatible with S bound\nr2_2: RecursiveTypeAlias2[int, str, ...]\nr2_3: RecursiveTypeAlias2[int, int, ...] # E: not compatible with T bound\nr2_4: RecursiveTypeAlias2[int, str, [int, str]]\n\ntype RecursiveTypeAlias3 = RecursiveTypeAlias3 # E: circular definition\n\ntype RecursiveTypeAlias4[T] = T | RecursiveTypeAlias4[str] # E: circular definition\n\ntype RecursiveTypeAlias5[T] = T | list[RecursiveTypeAlias5[T]]\n\ntype RecursiveTypeAlias6 = RecursiveTypeAlias7 # E[RTA6+]: circular definition\ntype RecursiveTypeAlias7 = RecursiveTypeAlias6 # E[RTA6+]: circular definition\n","source":"typing_tests","origin":"conformance/tests/aliases_type_statement.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_08.py","code":"\"\"\"\nTests the TypeAliasType call introduced in Python 3.12.\n\"\"\"\n\nfrom typing import Callable, Generic, ParamSpec, TypeAliasType, TypeVar, TypeVarTuple\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nTStr = TypeVar(\"TStr\", bound=str)\nP = ParamSpec(\"P\")\nTs = TypeVarTuple(\"Ts\")\n\nmy_tuple = (S, T)\nvar1 = 3\n\nGoodAlias1 = TypeAliasType(\"GoodAlias1\", int)\nGoodAlias2 = TypeAliasType(\"GoodAlias2\", list[T], type_params=(T,))\nGoodAlias3 = TypeAliasType(\"GoodAlias3\", list[T] | list[S], type_params=(S, T))\nGoodAlias4 = TypeAliasType(\"GoodAlias4\", T | \"list[GoodAlias4[T]]\", type_params=(T,))\nGoodAlias5 = TypeAliasType(\n \"GoodAlias5\",\n Callable[P, TStr] | list[S] | list[\"GoodAlias5[S, TStr, P]\"] | tuple[*Ts],\n type_params=(S, TStr, P, Ts),\n)\n\nclass ClassA(Generic[T]):\n GoodAlias6 = TypeAliasType(\"GoodAlias6\", list[T])\n\n\nprint(GoodAlias1.__value__) # OK\nprint(GoodAlias1.__type_params__) # OK\nprint(GoodAlias1.other_attrib) # E: unknown attribute\n\n\nx1: GoodAlias4[int] = 1 # OK\nx2: GoodAlias4[int] = [1] # OK\nx3: GoodAlias5[str, str, ..., int, str] # OK\nx4: GoodAlias5[int, str, ..., int, str] # OK\nx5: GoodAlias5[int, str, [int, str], *tuple[int, str, int]] # OK\nx6: GoodAlias5[int, int, ...] # E: incorrect type arguments\n\n\nBadAlias1 = TypeAliasType(\"BadAlias1\", list[S], type_params=(T,)) # E: S not in scope\nBadAlias2 = TypeAliasType(\"BadAlias2\", list[S]) # E: S not in scope\nBadAlias3 = TypeAliasType(\"BadAlias3\", int, type_params=my_tuple) # E: not literal tuple\nBadAlias4 = TypeAliasType(\"BadAlias4\", \"BadAlias4\") # E: circular dependency\nBadAlias5 = TypeAliasType(\"BadAlias5\", T | \"BadAlias5[str]\", type_params=(T,)) # E: circular dependency\nBadAlias6 = TypeAliasType(\"BadAlias6\", \"BadAlias7\") # E: circular dependency\nBadAlias7 = TypeAliasType(\"BadAlias7\", BadAlias6) # E?: circular dependency\n\n# The following are invalid type expressions for a type alias.\nBadAlias8 = TypeAliasType(\"BadAlias8\", eval(\"\".join(map(chr, [105, 110, 116])))) # E\nBadAlias9 = TypeAliasType(\"BadAlias9\", [int, str]) # E\nBadAlias10 = TypeAliasType(\"BadAlias10\", ((int, str),)) # E\nBadAlias11 = TypeAliasType(\"BadAlias11\", [int for i in range(1)]) # E\nBadAlias12 = TypeAliasType(\"BadAlias12\", {\"a\": \"b\"}) # E\nBadAlias13 = TypeAliasType(\"BadAlias13\", (lambda: int)()) # E\nBadAlias14 = TypeAliasType(\"BadAlias14\", [int][0]) # E\nBadAlias15 = TypeAliasType(\"BadAlias15\", int if 1 < 3 else str) # E\nBadAlias16 = TypeAliasType(\"BadAlias16\", var1) # E\nBadAlias17 = TypeAliasType(\"BadAlias17\", True) # E\nBadAlias18 = TypeAliasType(\"BadAlias18\", 1) # E\nBadAlias19 = TypeAliasType(\"BadAlias19\", list or set) # E\nBadAlias20 = TypeAliasType(\"BadAlias20\", f\"{'int'}\") # E\n\nBadAlias21 = TypeAliasType(\"BadAlias21\", list[BadAlias21]) # E\n","source":"typing_tests","origin":"conformance/tests/aliases_typealiastype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_09.py","code":"\"\"\"\nTests the compatibility rules between type parameter syntax (introduced in PEP 695)\nand traditional TypeVars.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#compatibility-with-traditional-typevars\n\nfrom typing import TypeVar\n\n\nK = TypeVar(\"K\")\n\n\nclass ClassA[V](dict[K, V]): # E: traditional TypeVar not allowed here\n ...\n\n\nclass ClassB[K, V](dict[K, V]): # OK\n ...\n\n\nclass ClassC[V]:\n def method1(self, a: V, b: K) -> V | K: # OK\n raise NotImplementedError\n\n def method2[M](self, a: M, b: K) -> M | K: # E\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_compatibility.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_10.py","code":"\"\"\"\nValidates the type parameter syntax introduced in PEP 695.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#type-parameter-declarations\n\n\n# This generic class is parameterized by a TypeVar T, a\n# TypeVarTuple Ts, and a ParamSpec P.\nfrom typing import Generic, Protocol\n\n\nclass ChildClass[T, *Ts, **P]:\n pass\n\n\nclass ClassA[T](Generic[T]): # E: Runtime error\n ...\n\n\nclass ClassB[S, T](Protocol): # OK\n ...\n\n\nclass ClassC[S, T](Protocol[S, T]): # E\n ...\n\n\nclass ClassD[T: str]:\n def method1(self, x: T):\n x.capitalize() # OK\n x.is_integer() # E\n\n\nclass ClassE[T: dict[str, int]]: # OK\n pass\n\n\nclass ClassF[S: ForwardReference[int], T: \"ForwardReference[str]\"]: # OK\n ...\n\n\nclass ClassG[V]:\n class ClassD[T: dict[str, V]]: # E: generic type not allowed\n ...\n\n\nclass ClassH[T: [str, int]]: # E: illegal expression form\n ...\n\n\nclass ClassI[AnyStr: (str, bytes)]: # OK\n ...\n\n\nclass ClassJ[T: (ForwardReference[int], \"ForwardReference[str]\", bytes)]: # OK\n ...\n\n\nclass ClassK[T: ()]: # E: two or more types required\n ...\n\n\nclass ClassL[T: (str,)]: # E: two or more types required\n ...\n\n\nt1 = (bytes, str)\n\n\nclass ClassM[T: t1]: # E: literal tuple expression required\n ...\n\n\nclass ClassN[T: (3, bytes)]: # E: invalid expression form\n ...\n\n\nclass ClassO[T: (list[S], str)]: # E: generic type\n ...\n\n\nclass ForwardReference[T]: ...\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_declarations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_11.py","code":"\"\"\"\nTests the handling of \"infer_variance\" parameter for TypeVar.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#auto-variance-for-typevar\n\nfrom typing import Final, Generic, Iterator, overload, Sequence, TypeVar\nfrom dataclasses import dataclass\n\n\nT = TypeVar(\"T\", infer_variance=True)\nK = TypeVar(\"K\", infer_variance=True)\nV = TypeVar(\"V\", infer_variance=True)\n\nS1 = TypeVar(\"S1\", covariant=True, infer_variance=True) # E: cannot use covariant with infer_variance\n\nS2 = TypeVar(\"S2\", contravariant=True, infer_variance=True) # E: cannot use contravariant with infer_variance\n\n\nclass ShouldBeCovariant1(Generic[T]):\n def __getitem__(self, index: int) -> T:\n raise NotImplementedError\n\n def __iter__(self) -> Iterator[T]:\n raise NotImplementedError\n\n\nvco1_1: ShouldBeCovariant1[float] = ShouldBeCovariant1[int]() # OK\nvco1_2: ShouldBeCovariant1[int] = ShouldBeCovariant1[float]() # E\n\n\nclass ShouldBeCovariant2(Sequence[T]):\n @overload\n def __getitem__(self, index: int) -> T:\n ...\n @overload\n def __getitem__(self, index: slice) -> Sequence[T]:\n ...\n def __getitem__(self, index: int | slice) -> T | Sequence[T]:\n raise NotImplementedError\n\n def __len__(self) -> int:\n raise NotImplementedError\n\n\nvco2_1: ShouldBeCovariant2[float] = ShouldBeCovariant2[int]() # OK\nvco2_2: ShouldBeCovariant2[int] = ShouldBeCovariant2[float]() # E\n\n\nclass ShouldBeCovariant3(Generic[T]):\n def method1(self) -> \"ShouldBeCovariant2[T]\":\n raise NotImplementedError\n\n\nvco3_1: ShouldBeCovariant3[float] = ShouldBeCovariant3[int]() # OK\nvco3_2: ShouldBeCovariant3[int] = ShouldBeCovariant3[float]() # E\n\n\n@dataclass(frozen=True)\nclass ShouldBeCovariant4(Generic[T]):\n x: T\n\n\n# This test is problematic as of Python 3.13 because of the\n# newly synthesized \"__replace__\" method, which causes the type\n# variable to be inferred as invariant rather than covariant.\n# See https://github.com/python/mypy/issues/17623#issuecomment-2266312738\n# for details. Until we sort this out, we'll leave this test commented\n# out.\n\n# vo4_1: ShouldBeCovariant4[float] = ShouldBeCovariant4[int](1) # OK\n# vo4_4: ShouldBeCovariant4[int] = ShouldBeCovariant4[float](1.0) # E\n\n\nclass ShouldBeCovariant5(Generic[T]):\n def __init__(self, x: T) -> None:\n self._x = x\n\n @property\n def x(self) -> T:\n return self._x\n\n\nvo5_1: ShouldBeCovariant5[float] = ShouldBeCovariant5[int](1) # OK\nvo5_2: ShouldBeCovariant5[int] = ShouldBeCovariant5[float](1.0) # E\n\n\nclass ShouldBeCovariant6(Generic[T]):\n x: Final[T]\n\n def __init__(self, value: T):\n self.x = value\n\n\nvo6_1: ShouldBeCovariant6[float] = ShouldBeCovariant6[int](1) # OK\nvo6_2: ShouldBeCovariant6[int] = ShouldBeCovariant6[float](1.0) # E\n\n\nclass ShouldBeInvariant1(Generic[T]):\n def __init__(self, value: T) -> None:\n self._value = value\n\n @property\n def value(self) -> T:\n return self._value\n\n @value.setter\n def value(self, value: T):\n self._value = value\n\n\nvinv1_1: ShouldBeInvariant1[float] = ShouldBeInvariant1[int](1) # E\nvinv1_2: ShouldBeInvariant1[int] = ShouldBeInvariant1[float](1.1) # E\n\n\nclass ShouldBeInvariant2(Generic[T]):\n def __init__(self, value: T) -> None:\n self._value = value\n\n def get_value(self) -> T:\n return self._value\n\n def set_value(self, value: T):\n self._value = value\n\n\nvinv2_1: ShouldBeInvariant2[float] = ShouldBeInvariant2[int](1) # E\nvinv2_2: ShouldBeInvariant2[int] = ShouldBeInvariant2[float](1.1) # E\n\n\nclass ShouldBeInvariant3(dict[K, V]):\n pass\n\n\nvinv3_1: ShouldBeInvariant3[float, str] = ShouldBeInvariant3[int, str]() # E\nvinv3_2: ShouldBeInvariant3[int, str] = ShouldBeInvariant3[float, str]() # E\nvinv3_3: ShouldBeInvariant3[str, float] = ShouldBeInvariant3[str, int]() # E\nvinv3_4: ShouldBeInvariant3[str, int] = ShouldBeInvariant3[str, float]() # E\n\n\n@dataclass\nclass ShouldBeInvariant4[T]:\n x: T\n\n\nvinv4_1: ShouldBeInvariant4[float] = ShouldBeInvariant4[int](1) # E\n\n\nclass ShouldBeInvariant5[T]:\n def __init__(self, x: T) -> None:\n self.x = x\n\n\nvinv5_1: ShouldBeInvariant5[float] = ShouldBeInvariant5[int](1) # E\n\n\nclass ShouldBeContravariant1(Generic[T]):\n def __init__(self, value: T) -> None:\n pass\n\n def set_value(self, value: T):\n pass\n\n\nvcontra1_1: ShouldBeContravariant1[float] = ShouldBeContravariant1[int](1) # E\nvcontra1_2: ShouldBeContravariant1[int] = ShouldBeContravariant1[float](1.2) # OK\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_infer_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_12.py","code":"\"\"\"\nTests the scoping rules for type parameter syntax introduced in PEP 695.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#type-parameter-scopes\n\nfrom typing import Callable, Mapping, Sequence, TypeVar, assert_type\n\n# > A compiler error or runtime exception is generated if the definition\n# > of an earlier type parameter references a later type parameter even\n# > if the name is defined in an outer scope.\n\n\nclass ClassA[S, T: Sequence[S]]: # E\n ...\n\n\nclass ClassB[S: Sequence[T], T]: # E\n ...\n\n\nclass Foo[T]:\n ...\n\n\nprint(T) # E: Runtime error: 'T' is not defined\n\n\ndef decorator1[\n T, **P, R\n](x: type[Foo[T]]) -> Callable[[Callable[P, R]], Callable[P, R]]:\n raise NotImplementedError\n\n\n@decorator1(Foo[T]) # E: Runtime error: 'T' is not defined\nclass ClassD[T]:\n ...\n\n\ntype Alias1[K, V] = Mapping[K, V] | Sequence[K]\n\n\nS: int = int(0)\n\n\ndef outer1[S](x: str):\n S: str = x\n T: int = 1\n\n def outer2[T]():\n def inner1():\n nonlocal S # OK\n assert_type(S, str)\n # nonlocal T # Syntax error\n\n def inner2():\n global S # OK\n assert_type(S, int)\n\n\nclass Outer1:\n class Private:\n pass\n\n class Inner[T](Private, Sequence[T]): # OK\n pass\n\n def method1[T](self, a: Inner[T]) -> Inner[T]: # OK\n return a\n\n\ndef decorator2[**P, R](x: int) -> Callable[[Callable[P, R]], Callable[P, R]]:\n raise NotImplementedError\n\n\nT = int(0)\n\n\n@decorator2(T) # OK\nclass ClassE[T](Sequence[T]):\n T = int(1)\n\n def method1[T](self): # E\n ...\n\n def method2[T](self, x=T): # E\n ...\n\n def method3[T](self, x: T): # E\n ...\n\n\nT = int(0)\n\n\ndef f(a: int, b: str, c: complex):\n class Outer2[T]:\n T = a\n\n assert_type(T, int)\n\n class Inner1:\n T = b\n\n assert_type(T, str)\n\n def inner_method(self):\n assert_type(T, TypeVar)\n\n def outer_method(self):\n T = c\n\n assert_type(T, complex)\n\n def inner_func():\n assert_type(T, complex)\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_13.py","code":"\"\"\"\nTests the \"alternative\" (non-class) syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#alternative-syntax\n\nfrom typing import TypedDict\n\n\nMovie = TypedDict(\"Movie\", {\"name\": str, \"year\": int, \"illegal key name\": bool})\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982, \"illegal key name\": True}\n\nMovieOptional = TypedDict(\"MovieOptional\", {\"name\": str, \"year\": int}, total=False)\n\nmovie_opt1: MovieOptional = {}\nmovie_opt2: MovieOptional = {\"year\": 1982}\n\n# > A type checker is only expected to accept a dictionary display expression as\n# > the second argument to TypedDict. In particular, a variable that refers to a\n# > dictionary object does not need to be supported, to simplify implementation.\nmy_dict = {\"name\": str}\nBadTypedDict1 = TypedDict(\"BadTypedDict1\", my_dict) # E\n\n\n# This should generate an error because it uses a non-str key.\nBadTypedDict2 = TypedDict(\"BadTypedDict2\", {1: str}) # E\n\n\n# This should generate an error because it uses a non-matching name.\nBadTypedDict3 = TypedDict(\"WrongName\", {\"name\": str}) # E\n\n\n# This should generate an error because of the additional parameter.\nBadTypedDict4 = TypedDict(\"BadTypedDict4\", {\"name\": str}, total=False, other=False) # E\n\n\n# > The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13.\n# > It may also be unsupported by static type checkers.\n\nMovie2 = TypedDict(\"Movie2\", name=str, year=int) # E?\n\nmovie2: Movie2\nmovie2 = {\"name\": \"Blade Runner\", \"year\": 1982} # E?: May generate errors if keyword-argument syntax is unsupported\nmovie2 = {\"name\": \"Blade Runner\", \"year\": \"\"} # E?: Incorrect type for year\n","source":"typing_tests","origin":"conformance/tests/typeddicts_alt_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_14.py","code":"\"\"\"\nTests the class syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import Generic, TypeVar, TypedDict\nimport sys\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n # > String literal forward references are valid in the value types.\n director: \"Person\"\n\n\nclass Person(TypedDict):\n name: str\n age: int\n\n\n# > Methods are not allowed, since the runtime type of a TypedDict object\n# > will always be just dict (it is never a subclass of dict).\nclass BadTypedDict1(TypedDict):\n name: str\n\n # Methods are not allowed, so this should generate an error.\n def method1(self): # E\n pass\n\n # Methods are not allowed, so this should generate an error.\n @classmethod # E[method2]\n def method2(cls): # E[method2]\n pass\n\n # Methods are not allowed, so this should generate an error.\n @staticmethod # E[method3]\n def method3(): # E[method3]\n pass\n\n\nclass CustomMeta(type):\n pass\n\n\n# > Specifying a custom metaclass is not allowed.\nclass BadTypedDict2(TypedDict, metaclass=CustomMeta): # E\n name: str\n\n\n# This should generate an error because \"other\" is not an allowed keyword argument.\nclass BadTypedDict3(TypedDict, other=True): # E\n name: str\n\n# > `if` conditions that the type checker is able to\n# > statically evaluate are also permitted (e.g. `if sys.version_info > (3, 14)`),\n# > in order to specify items that exist only under the given conditions.\nclass ConditionalField(TypedDict):\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nConditionalField(x=1, y=2)\nConditionalField(x=1, y=2, z=3) # E\n\n\n# > TypedDicts may be made generic by adding Generic[T] among the bases.\nT = TypeVar(\"T\")\n\n\nclass GenericTypedDict(TypedDict, Generic[T]):\n name: str\n value: T\n\n\n# > An empty TypedDict can be created by only including pass in the\n# > body (if there is a docstring, pass can be omitted):\nclass EmptyDict1(TypedDict):\n pass\n\n\nclass EmptyDict2(TypedDict):\n \"\"\"Docstring\"\"\"\n\n\nclass MovieTotal(TypedDict, total=True):\n name: str\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n","source":"typing_tests","origin":"conformance/tests/typeddicts_class_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_15.py","code":"\"\"\"\nTests inheritance rules for TypedDict classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclass BookBasedMovie(Movie):\n based_on: str\n\nclass BookBasedMovieAlso(TypedDict):\n name: str\n year: int\n based_on: str\n\nb1: BookBasedMovie = {\"name\": \"Little Women\", \"year\": 2019, \"based_on\": \"Little Women\"}\n\nb2: BookBasedMovieAlso = b1\n\n\nclass X(TypedDict):\n x: int\n\nclass Y(TypedDict):\n y: str\n\nclass XYZ(X, Y):\n z: bool\n\nx1 = XYZ(x=1, y=\"\", z=True)\n\n# > A TypedDict cannot inherit from both a TypedDict type and a\n# > non-TypedDict base class other than Generic.\n\nclass NonTypedDict:\n pass\n\nclass BadTypedDict(TypedDict, NonTypedDict): # E\n pass\n\n\n# > Changing a field type of a parent TypedDict class in a subclass is\n# > not allowed.\n\nclass X1(TypedDict):\n x: str\n\nclass Y1(X1): # E[Y1]\n x: int # E[Y1]: cannot overwrite TypedDict field \"x\"\n\n\n# > Multiple inheritance does not allow conflict types for the same name field:\nclass X2(TypedDict):\n x: int\n\nclass Y2(TypedDict):\n x: str\n\nclass XYZ2(X2, Y2): # E: cannot overwrite TypedDict field \"x\" while merging\n xyz: bool\n","source":"typing_tests","origin":"conformance/tests/typeddicts_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_16.py","code":"\"\"\"\nTests operations provided by a TypedDict object.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#supported-and-unsupported-operations\n\n\nfrom typing import TypedDict, assert_type\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie\n\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982}\nmovie[\"name\"] = \"Other\"\nmovie[\"year\"] = 1981\n\nmovie[\"name\"] = 1982 # E: wrong type\nmovie[\"year\"] = \"\" # E: wrong type\nmovie[\"other\"] = \"\" # E: unknown key added\n\nprint(movie[\"other\"]) # E: unknown key referenced\n\nmovie = {\"name\": \"Blade Runner\"} # E: year is missing\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982.1} # E: year is wrong type\n\n# > The use of a key that is not known to exist should be reported as an error.\nmovie = {\"name\": \"\", \"year\": 1900, \"other\": 2} # E: extra key\n\n\ndef func1(variable_key: str):\n # > A key that is not a literal should generally be rejected.\n movie: Movie = {variable_key: \"\", \"year\": 1900} # E: variable key\n\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"name\")\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"other\") # E?\n\n\nmovie.clear() # E: clear not allowed\n\ndel movie[\"name\"] # E: del not allowed for required key\n\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n year: int\n\n\nmovie_optional: MovieOptional = {}\n\nassert_type(movie_optional.get(\"name\"), str | None)\n\nmovie_optional.clear() # E: clear not allowed\n\ndel movie_optional[\"name\"]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_operations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_17.py","code":"\"\"\"\nTests the type consistency rules for TypedDict objects.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#type-consistency\n\nfrom typing import Any, Literal, Mapping, TypedDict\n\n\nclass A1(TypedDict):\n x: int | None\n\n\nclass B1(TypedDict):\n x: int\n\n\nb1: B1 = {\"x\": 0}\n\n# > Value types behave invariantly.\na1: A1 = b1 # E: 'B1' not compatible with 'A1'\n\n# > any TypedDict type is consistent with Mapping[str, object]\nv1: Mapping[str, object] = b1\n\n# > A TypedDict type with a required key is not consistent with a TypedDict\n# > type where the same key is a non-required key.\n\nclass A2(TypedDict, total=False):\n x: int\n\n\nclass B2(TypedDict):\n x: int\n\n\nb2: B2 = {\"x\": 0}\na2: A2 = b2 # E: 'B2' not compatible with 'A2'\n\n\n# > A TypedDict type A is consistent with TypedDict B if A is structurally\n# > compatible with B. This is true if and only if both of these conditions\n# > are satisfied:\n# > 1. For each key in B, A has the corresponding key and the corresponding\n# > value type in A is consistent with the value type in B. For each key in B,\n# > the value type in B is also consistent with the corresponding value type\n# > in A.\n# > 2. For each required key in B, the corresponding key is required in A. For\n# > each non-required key in B, the corresponding key is not required in A.\n\n\nclass A3(TypedDict):\n x: int\n\n\nclass B3(TypedDict):\n x: int\n y: int\n\n\nb3: B3 = {\"x\": 0, \"y\": 0}\na3: A3 = b3\n\na3 = {\"x\": 0}\nb3 = a3 # E\n\n\n# This should generate an error because it's a literal assignment.\na3_1: A3 = {\"x\": 0, \"y\": 0} # E\n\n# This should not generate an error.\na3_2 = b3\n\n# > A TypedDict isn’t consistent with any Dict[...] type.\n\nd1: dict[str, int] = b3 # E\nd2: dict[str, object] = b3 # E\nd3: dict[Any, Any] = b3 # E\n\n# > A TypedDict with all int values is not consistent with Mapping[str, int].\n\nm1: Mapping[str, int] = b3 # E\nm2: Mapping[str, object] = b3 # OK\nm3: Mapping[str, Any] = b3 # OK\n\n\n# Test \"get\" method.\nUserType1 = TypedDict(\"UserType1\", {\"name\": str, \"age\": int}, total=False)\nuser1: UserType1 = {\"name\": \"Bob\", \"age\": 40}\n\nname1: str = user1.get(\"name\", \"n/a\")\nage1: int = user1.get(\"age\", 42)\n\nUserType2 = TypedDict(\"UserType2\", {\"name\": str, \"age\": int})\nuser2: UserType2 = {\"name\": \"Bob\", \"age\": 40}\n\nname2: str | None = user2.get(\"name\")\n\n# The spec does not say whether type checkers should adjust the return type of `.get()`\n# to exclude `None` if it is known that the key exists. Either option is acceptable.\nname3: str = user2.get(\"name\") # E?\n\nage2: int = user2.get(\"age\", 42)\n\nage3: int | str = user2.get(\"age\", \"42\")\n\nage4: int = user2.get(\"age\", \"42\") # E?\n\n# Test nested TypedDicts.\nclass Inner1(TypedDict):\n inner_key: str\n\n\nclass Inner2(TypedDict):\n inner_key: Inner1\n\n\nclass Outer1(TypedDict):\n outer_key: Inner2\n\n\no1: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": \"hi\"}}}\n\n# This should generate an error because the inner-most value\n# should be a string.\no2: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": 1}}} # E\n\n\nclass Inner3(TypedDict):\n x: int\n\n\nclass Inner4(TypedDict):\n x: int\n\n\nclass Outer2(TypedDict):\n y: str\n z: Literal[\"\"] | Inner3\n\n\nclass Outer3(TypedDict):\n y: str\n z: Literal[\"\"] | Inner4\n\n\ndef func1(td: Outer3):\n ...\n\n\no3: Outer2 = {\"y\": \"\", \"z\": {\"x\": 0}}\no4: Outer3 = o3\n","source":"typing_tests","origin":"conformance/tests/typeddicts_type_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_18.py","code":"\"\"\"\nTests for basic usage of TypedDict.\n\"\"\"\n\nfrom typing import TypeVar, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982}\n\n\ndef record_movie(movie: Movie) -> None:\n ...\n\n\nrecord_movie({\"name\": \"Blade Runner\", \"year\": 1982})\n\n\nmovie[\"director\"] = \"Ridley Scott\" # E: invalid key 'director'\nmovie[\"year\"] = \"1982\" # E: invalid value type (\"int\" expected)\n\n# The code below should be rejected, since 'title' is not a valid key,\n# and the 'name' key is missing:\nmovie2: Movie = {\"title\": \"Blade Runner\", \"year\": 1982} # E\n\nm = Movie(name='Blade Runner', year=1982)\n\n\n# > TypedDict type objects cannot be used in isinstance() tests such as\n# > isinstance(d, Movie).\nif isinstance(movie, Movie): # E\n pass\n\n\n# TypedDict should not be allowed as a bound for a TypeVar.\nT = TypeVar(\"T\", bound=TypedDict) # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"typed-kwargs","pep":"692","introduced_in":"3.12","form":"modern","file":"typed-kwargs/modern_01.py","code":"\"\"\"\nTests the use of an unpacked TypedDict for annotating **kwargs.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#unpack-for-keyword-arguments\n\n# This sample tests the handling of Unpack[TypedDict] when used with\n# a **kwargs parameter in a function signature.\n\nfrom typing import Protocol, TypeVar, TypedDict, NotRequired, Required, Unpack, assert_type\n\n\nclass TD1(TypedDict):\n v1: Required[int]\n v2: NotRequired[str]\n\n\nclass TD2(TD1):\n v3: Required[str]\n\n\ndef func1(**kwargs: Unpack[TD2]) -> None:\n v1 = kwargs[\"v1\"]\n assert_type(v1, int)\n\n # > Type checkers may allow reading an item using ``d['x']`` even if\n # > the key ``'x'`` is not required\n kwargs[\"v2\"] # E?: v2 may not be present\n\n if \"v2\" in kwargs:\n v2 = kwargs[\"v2\"]\n assert_type(v2, str)\n\n v3 = kwargs[\"v3\"]\n assert_type(v3, str)\n\n\ndef func2(v3: str, **kwargs: Unpack[TD1]) -> None:\n # > When Unpack is used, type checkers treat kwargs inside the function\n # > body as a TypedDict.\n assert_type(kwargs, TD1)\n\n\ndef func3() -> None:\n # Mypy reports multiple errors here.\n func1() # E: missing required keyword args\n func1(v1=1, v2=\"\", v3=\"5\") # OK\n\n td2 = TD2(v1=2, v3=\"4\")\n func1(**td2) # OK\n func1(v1=1, v2=\"\", v3=\"5\", v4=5) # E?: v4 is not in TD2, but could be in a subtype\n func1(1, \"\", \"5\") # E: args not passed by position\n\n # > Passing a dictionary of type dict[str, object] as a **kwargs argument\n # > to a function that has **kwargs annotated with Unpack must generate a\n # > type checker error.\n my_dict: dict[str, str] = {}\n func1(**my_dict) # E: untyped dict\n\n d1 = {\"v1\": 2, \"v3\": \"4\", \"v4\": 4}\n func1(**d1) # E?: OK or Type error (spec allows either)\n func2(**td2) # OK\n func1(v1=2, **td2) # E: v1 is already specified\n func2(1, **td2) # E: v1 is already specified\n func2(v1=1, **td2) # E: v1 is already specified\n\n\nclass TDProtocol1(Protocol):\n def __call__(self, *, v1: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol2(Protocol):\n def __call__(self, *, v1: int, v3: str, v2: str = \"\") -> None:\n ...\n\n\nclass TDProtocol3(Protocol):\n def __call__(self, *, v1: int, v2: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol4(Protocol):\n def __call__(self, *, v1: int) -> None:\n ...\n\n\nclass TDProtocol5(Protocol):\n def __call__(self, v1: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol6(Protocol):\n def __call__(self, **kwargs: Unpack[TD2]) -> None:\n ...\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#assignment\n\nv1: TDProtocol1 = func1 # OK\nv2: TDProtocol2 = func1 # OK\nv3: TDProtocol3 = func1 # E: v2 is wrong type\nv4: TDProtocol4 = func1 # E: v3 is missing\nv5: TDProtocol5 = func1 # E: params are positional\nv6: TDProtocol6 = func1 # OK\n\n\ndef func4(v1: int, /, **kwargs: Unpack[TD2]) -> None:\n ...\n\n\ndef func5(v1: int, **kwargs: Unpack[TD2]) -> None: # E: parameter v1 overlaps with the TypedDict.\n ...\n\n\nT = TypeVar(\"T\", bound=TD2)\n\n# > TypedDict is the only permitted heterogeneous type for typing **kwargs.\n# > Therefore, in the context of typing **kwargs, using Unpack with types other\n# > than TypedDict should not be allowed and type checkers should generate\n# > errors in such cases.\n\ndef func6(**kwargs: Unpack[T]) -> None: # E: unpacked value must be a TypedDict, not a TypeVar bound to TypedDict.\n ...\n\n# > The situation where the destination callable contains **kwargs: Unpack[TypedDict] and\n# > the source callable doesn’t contain **kwargs should be disallowed. This is because,\n# > we cannot be sure that additional keyword arguments are not being passed in when an instance of a subclass\n# > had been assigned to a variable with a base class type and then unpacked in the destination callable invocation\n\ndef func7(*, v1: int, v3: str, v2: str = \"\") -> None:\n ...\n\n\nv7: TDProtocol6 = func7 # E: source does not have kwargs\n","source":"typing_tests","origin":"conformance/tests/callables_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"typed-kwargs","pep":"692","introduced_in":"3.12","form":"modern","file":"typed-kwargs/modern_02.py","code":"\"\"\"\nTests the use of unpacked TypedDicts with read-only items when used to annotate\na **kwargs parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Protocol, TypedDict, Unpack\nfrom typing_extensions import ReadOnly\n\n# > :pep:`692` introduced ``Unpack`` to annotate ``**kwargs`` with a\n# > ``TypedDict``. Marking one or more of the items of a ``TypedDict`` used\n# > in this way as read-only will have no effect on the type signature of\n# > the method. However, it *will* prevent the item from being modified in\n# > the body of the function.\n\n\nclass Args(TypedDict):\n key1: int\n key2: str\n\n\nclass ReadOnlyArgs(TypedDict):\n key1: ReadOnly[int]\n key2: ReadOnly[str]\n\n\nclass Function(Protocol):\n def __call__(self, **kwargs: Unpack[Args]) -> None: ...\n\n\ndef impl(**kwargs: Unpack[ReadOnlyArgs]) -> None:\n kwargs[\"key1\"] = 3 # E\n\n\nfn: Function = impl # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_12.py","code":"\"\"\"\nTests for the use of TypeVarTuple with \"*args\" parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#args-as-a-type-variable-tuple\n\n# > If *args is annotated as a type variable tuple, the types of the individual\n# > arguments become the types in the type variable tuple.\n\nfrom typing import TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef args_to_tuple(*args: *Ts) -> tuple[*Ts]:\n raise NotImplementedError\n\n\nclass Env:\n ...\n\n\ndef exec_le(path: str, *args: *tuple[*Ts, Env], env: Env | None = None) -> tuple[*Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(x: int, y: str):\n assert_type(args_to_tuple(x, y), tuple[int, str])\n\n assert_type(exec_le(\"\", Env()), tuple[()]) # OK\n assert_type(exec_le(y, x, y, Env()), tuple[int, str]) # OK\n exec_le(\"\", 0, \"\") # E\n exec_le(\"\", 0, \"\", env=Env()) # E\n\n\n# > Using an unpacked unbounded tuple is equivalent to the\n# > PEP 484#arbitrary-argument-lists-and-default-argument-values behavior of\n# > *args: int, which accepts zero or more values of type int.\n\n\ndef func1(*args: *tuple[int, ...]) -> None:\n ...\n\n\nfunc1() # OK\nfunc1(1, 2, 3, 4, 5) # OK\nfunc1(1, \"2\", 3) # E\n\n\ndef func2(*args: *tuple[int, *tuple[str, ...], str]) -> None:\n ...\n\n\nfunc2(1, \"\") # OK\nfunc2(1, \"\", \"\", \"\", \"\") # OK\nfunc2(1, 1, \"\") # E\nfunc2(1) # E\nfunc2(\"\") # E\n\n\ndef func3(*args: *tuple[int, str]) -> None:\n ...\n\n\nfunc3(1, \"hello\") # OK\nfunc3(1) # E\n\n\ndef func4(*args: tuple[*Ts]):\n ...\n\n\nfunc4((0,), (1,)) # OK\nfunc4((0,), (1, 2)) # E (length mismatch)\nfunc4((0,), (\"1\",)) # OK\n\n\n# This is a syntax error, so leave it commented out.\n# def func5(**kwargs: *Ts): # E\n# ...\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_13.py","code":"\"\"\"\nTests basic usage of TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#typevartuple\n\nfrom typing import Generic, NewType, TypeVarTuple, assert_type\n\nTs = TypeVarTuple(\"Ts\")\nTs1 = TypeVarTuple(\"Ts1\")\n\n\nclass Array1(Generic[*Ts]):\n ...\n\n\ndef func1(*args: *Ts) -> tuple[*Ts]:\n raise NotImplementedError\n\n\nShape = TypeVarTuple(\"Shape\")\n\n\nclass Array(Generic[*Shape]):\n def __init__(self, shape: tuple[*Shape]):\n self._shape: tuple[*Shape] = shape\n\n def get_shape(self) -> tuple[*Shape]:\n return self._shape\n\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nTime = NewType(\"Time\", int)\nBatch = NewType(\"Batch\", int)\n\nv1: Array[Height, Width] = Array((Height(1), Width(2))) # OK\nv2: Array[Batch, Height, Width] = Array((Batch(1), Height(1), Width(1))) # OK\nv3: Array[Time, Batch, Height, Width] = Array(\n (Time(1), Batch(1), Height(1), Width(1))\n) # OK\n\nv4: Array[Height, Width] = Array(Height(1)) # E\nv5: Array[Batch, Height, Width] = Array((Batch(1), Width(1))) # E\nv6: Array[Time, Batch, Height, Width] = Array( # E[v6]\n (Time(1), Batch(1), Width(1), Height(1)) # E[v6]\n)\n\n\n# > Type Variable Tuples Must Always be Unpacked\n\n\nclass ClassA(Generic[Shape]): # E: not unpacked\n def __init__(self, shape: tuple[Shape]): # E: not unpacked\n self._shape: tuple[*Shape] = shape\n\n def get_shape(self) -> tuple[Shape]: # E: not unpacked\n raise NotImplementedError\n\n def method1(*args: Shape) -> None: # E: not unpacked\n ...\n\n\n# > TypeVarTuple does not support type constraints.\n\nTs2 = TypeVarTuple(\"Ts2\", int, float) # E\nTs3 = TypeVarTuple(\"Ts3\", bound=int) # E: bound is unavailable in Python 3.12\n\n\n# > If the same TypeVarTuple instance is used in multiple places in a signature\n# > or class, a valid type inference might be to bind the TypeVarTuple to a\n# > tuple of a union of types.\n\n\ndef func2(arg1: tuple[*Ts], arg2: tuple[*Ts]) -> tuple[*Ts]:\n raise NotImplementedError\n\n\n# > We do not allow this; type unions may not appear within the tuple.\n# > If a type variable tuple appears in multiple places in a signature,\n# > the types must match exactly (the list of type parameters must be the\n# > same length, and the type parameters themselves must be identical)\n\ndef check_func2(x: int):\n assert_type(func2((x,), (1,)), tuple[int]) # OK\nfunc2((0,), (0.0,)) # OK\nfunc2((0.0,), (0,)) # OK\nfunc2((0,), (1,)) # OK\n\nfunc2((0,), (\"0\",)) # OK\nfunc2((0, 0), (0,)) # E\n\n\ndef multiply(x: Array[*Shape], y: Array[*Shape]) -> Array[*Shape]:\n raise NotImplementedError\n\n\ndef func3(x: Array[Height], y: Array[Width], z: Array[Height, Width]):\n multiply(x, x) # OK\n multiply(x, y) # E\n multiply(x, z) # E\n\n\n# > Only a single type variable tuple may appear in a type parameter list.\n\n\nclass Array3(Generic[*Ts, *Ts1]): # E\n ...\n\n\nclass Array4[*Ts1, *Ts2]: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_14.py","code":"\"\"\"\nTests the use of TypeVarTuple within a Callable.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variable-tuples-with-callable\n\n# > Type variable tuples can also be used in the arguments section of a Callable.\n\n\nfrom typing import Callable, TypeVar, TypeVarTuple, assert_type\n\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Process:\n def __init__(self, target: Callable[[*Ts], None], args: tuple[*Ts]) -> None:\n ...\n\n\ndef func1(arg1: int, arg2: str) -> None:\n ...\n\n\nProcess(target=func1, args=(0, \"\")) # OK\nProcess(target=func1, args=(\"\", 0)) # E\n\n\ndef func2(f: Callable[[int, *Ts, T], tuple[T, *Ts]]) -> tuple[*Ts, T]:\n raise NotImplementedError\n\n\ndef callback1(a: int, b: str, c: int, d: complex) -> tuple[complex, str, int]:\n raise NotImplementedError\n\n\ndef callback2(a: int, d: str) -> tuple[str]:\n raise NotImplementedError\n\n\nassert_type(func2(callback1), tuple[str, int, complex])\nassert_type(func2(callback2), tuple[str])\n\n\ndef func3(*args: *tuple[int, *Ts, T]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(a: int, b: str, c: float, d: complex):\n assert_type(func3(a, b, c, d), tuple[complex, str, float])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_callable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_15.py","code":"\"\"\"\nTests type concatenation using TypeVarTuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-concatenation\n\n# > Type variable tuples don’t have to be alone; normal types can be prefixed and/or suffixed.\n\nfrom typing import Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nShape = TypeVarTuple(\"Shape\")\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef add_batch_axis(x: Array[*Shape]) -> Array[Batch, *Shape]:\n raise NotImplementedError\n\n\ndef del_batch_axis(x: Array[Batch, *Shape]) -> Array[*Shape]:\n raise NotImplementedError\n\n\ndef add_batch_channels(x: Array[*Shape]) -> Array[Batch, *Shape, Channels]:\n raise NotImplementedError\n\n\ndef func1(a: Array[Height, Width]):\n b = add_batch_axis(a) # OK\n assert_type(b, Array[Batch, Height, Width])\n c = del_batch_axis(b) # OK\n assert_type(c, Array[Height, Width])\n d = add_batch_channels(a) # OK\n assert_type(d, Array[Batch, Height, Width, Channels])\n\n\ndef prefix_tuple(x: T, y: tuple[*Ts]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef call_prefix_tuple(x: int, y: bool, z: str):\n result = prefix_tuple(x=x, y=(y, z))\n assert_type(result, tuple[int, bool, str])\n\n\ndef move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n return (*tup[1:], tup[0])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_concat.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_16.py","code":"\"\"\"\nTests the use of TypeVarTuple in function overloads.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#overloads-for-accessing-individual-types\n\nfrom typing import Any, Generic, TypeVar, TypeVarTuple, assert_type, overload\n\n\nShape = TypeVarTuple(\"Shape\")\nAxis1 = TypeVar(\"Axis1\")\nAxis2 = TypeVar(\"Axis2\")\nAxis3 = TypeVar(\"Axis3\")\n\n\nclass Array(Generic[*Shape]):\n @overload\n def transpose(self: \"Array[Axis1, Axis2]\") -> \"Array[Axis2, Axis1]\":\n ...\n\n @overload\n def transpose(self: \"Array[Axis1, Axis2, Axis3]\") -> \"Array[Axis3, Axis2, Axis1]\":\n ...\n\n def transpose(self) -> Any:\n raise NotImplementedError\n\n\ndef func1(a: Array[Axis1, Axis2], b: Array[Axis1, Axis2, Axis3]):\n assert_type(a.transpose(), Array[Axis2, Axis1])\n assert_type(b.transpose(), Array[Axis3, Axis2, Axis1])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_overloads.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_17.py","code":"\"\"\"\nTests the handling of a TypeVarTuple specialization.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#behaviour-when-type-parameters-are-not-specified\n\nfrom typing import Any, Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nTime = NewType(\"Time\", int)\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef takes_any_array1(arr: Array):\n ...\n\n\ndef takes_any_array2(arr: Array[*tuple[Any, ...]]):\n ...\n\n\ndef func1(x: Array[Height, Width]):\n takes_any_array1(x) # OK\n takes_any_array2(x) # OK\n\n\ndef func2(y: Array[Time, Height, Width]):\n takes_any_array1(y) # OK\n takes_any_array2(y) # OK\n\n\n# > Generic aliases can be created using a type variable tuple in a similar\n# > way to regular type variables.\n\nIntTuple = tuple[int, *Ts]\nNamedArray = tuple[str, Array[*Ts]]\n\n\ndef func3(a: IntTuple[float, bool], b: NamedArray[Height]):\n assert_type(a, tuple[int, float, bool])\n assert_type(b, tuple[str, Array[Height]])\n\n\ndef func4(a: IntTuple[()], b: NamedArray[()]):\n assert_type(a, tuple[int])\n assert_type(b, tuple[str, Array[()]])\n\n\nShape = TypeVarTuple(\"Shape\")\nDType = TypeVar(\"DType\")\n\n\nclass Array2(Generic[DType, *Shape]):\n ...\n\n\nFloatArray = Array2[float, *Shape]\nArray1D = Array2[DType, Any]\n\n\ndef func5_0(a: Array1D, b: Array1D[int]):\n assert_type(a, Array2[Any, Any])\n assert_type(b, Array2[int, Any])\n\n\ndef takes_float_array_of_any_shape(x: FloatArray):\n ...\n\n\ndef func5_1(x: FloatArray[Height, Width]):\n takes_float_array_of_any_shape(x) # OK\n\n\ndef takes_float_array_with_specific_shape(y: FloatArray[Height, Width]):\n ...\n\n\ndef func5_2(x: FloatArray):\n takes_float_array_with_specific_shape(x) # OK\n\n\nT = TypeVar(\"T\")\nVariadicTuple = tuple[T, *Ts]\n\n\ndef func6(a: VariadicTuple[str, int], b: VariadicTuple[float], c: VariadicTuple):\n assert_type(a, tuple[str, int])\n assert_type(b, tuple[float])\n assert_type(c, tuple[Any, *tuple[Any, ...]])\n\n\nTs1 = TypeVarTuple(\"Ts1\")\nTs2 = TypeVarTuple(\"Ts2\")\n\nIntTupleVar = tuple[int, *Ts1] # OK\nIntFloatTupleVar = IntTupleVar[float, *Ts2] # OK\nIntFloatsTupleVar = IntTupleVar[*tuple[float, ...]] # OK\n\n\nIntTupleGeneric = tuple[int, T]\n\nIntTupleGeneric[str] # OK\nIntTupleGeneric[*Ts] # E\nIntTupleGeneric[*tuple[float, ...]] # E\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nTA1 = tuple[*Ts, T1, T2] # OK\nTA2 = tuple[T1, T2, *Ts] # OK\nTA3 = tuple[T1, *Ts, T2, T3] # OK\nTA4 = tuple[T1, T2, *tuple[int, ...]] # OK\nTA5 = tuple[T1, *Ts, T2, *Ts] # E\nTA6 = tuple[T1, *Ts, T2, *tuple[int, ...]] # E\n\n\nTA7 = tuple[*Ts, T1, T2]\n\nv1: TA7[int] # E: requires at least two type arguments\n\n\ndef func7(a: TA7[*Ts, T1, T2]) -> tuple[tuple[*Ts], T1, T2]:\n raise NotImplementedError\n\n\ndef func8(a: TA7[str, bool], b: TA7[str, bool, float], c: TA7[str, bool, float, int]):\n assert_type(func7(a), tuple[tuple[()], str, bool])\n assert_type(func7(b), tuple[tuple[str], bool, float])\n assert_type(func7(c), tuple[tuple[str, bool], float, int])\n\n\nTA8 = tuple[T1, *Ts, T2, T3]\n\n\ndef func9(a: TA8[T1, *Ts, T2, T3]) -> tuple[tuple[*Ts], T1, T2, T3]:\n raise NotImplementedError\n\n\ndef func10(a: TA8[str, bool, float], b: TA8[str, bool, float, int]):\n assert_type(func9(a), tuple[tuple[()], str, bool, float])\n assert_type(func9(b), tuple[tuple[bool], str, float, int])\n\n\nTA9 = tuple[*Ts, T1]\nTA10 = TA9[*tuple[int, ...]] # OK\n\n\ndef func11(a: TA10, b: TA9[*tuple[int, ...], str], c: TA9[*tuple[int, ...], str]):\n assert_type(a, tuple[*tuple[int, ...], int])\n assert_type(b, tuple[*tuple[int, ...], str])\n assert_type(c, tuple[*tuple[int, ...], str])\n\n\nTA11 = tuple[T, *Ts1]\nTA12 = TA11[*Ts2] # E\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_18.py","code":"\"\"\"\nTests unpack operations for TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#unpacking-tuple-types\n\nfrom typing import Any, Generic, NewType, TypeVarTuple\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nTs = TypeVarTuple(\"Ts\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef process_batch_channels(x: Array[Batch, *tuple[Any, ...], Channels]) -> None:\n ...\n\n\ndef func3(\n x: Array[Batch, Height, Width, Channels], y: Array[Batch, Channels], z: Array[Batch]\n):\n process_batch_channels(x) # OK\n process_batch_channels(y) # OK\n process_batch_channels(z) # E\n\n\nShape = TypeVarTuple(\"Shape\")\n\n\ndef expect_variadic_array(x: Array[Batch, *Shape]) -> None:\n ...\n\n\ndef expect_precise_array(x: Array[Batch, Height, Width, Channels]) -> None:\n ...\n\n\ndef func4(y: Array[*tuple[Any, ...]]):\n expect_variadic_array(y) # OK\n expect_precise_array(y) # OK\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_unpack.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_19.py","code":"\"\"\"\nTests variance of TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance-inference\n\n\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple\n\nclass InvariantTypeVarTuple[*InOutTs]:\n a: tuple[*InOutTs]\n\nin_out_obj: InvariantTypeVarTuple[object] = InvariantTypeVarTuple[int]() # E\nin_out_int: InvariantTypeVarTuple[int] = InvariantTypeVarTuple[object]() # E\nin_out_int = InvariantTypeVarTuple[int]()\nin_out_variadic_int: InvariantTypeVarTuple[*tuple[int, ...]] = InvariantTypeVarTuple[*tuple[object, ...]]() # E\nin_out_variadic_object: InvariantTypeVarTuple[*tuple[object, ...]] = InvariantTypeVarTuple[*tuple[int, ...]]() # E\nin_out_empty: InvariantTypeVarTuple[()] = InvariantTypeVarTuple[()]() # OK\nin_out_fixed_from_variadic: InvariantTypeVarTuple[int] = InvariantTypeVarTuple[*tuple[int, ...]]() # E\nin_out_variadic_from_fixed: InvariantTypeVarTuple[*tuple[int, ...]] = InvariantTypeVarTuple[int]() # E\n\n\nclass ContravariantTypeVarTuple[*InTs]:\n def f(self, t: tuple[*InTs]):\n raise NotImplementedError\n\nin_obj: ContravariantTypeVarTuple[object, object] = ContravariantTypeVarTuple[object, int]() # E\nin_int: ContravariantTypeVarTuple[int] = ContravariantTypeVarTuple[object]() # OK\nin_variadic_int: ContravariantTypeVarTuple[*tuple[int, ...]] = ContravariantTypeVarTuple[*tuple[object, ...]]() # OK\nin_variadic_object: ContravariantTypeVarTuple[*tuple[object, ...]] = ContravariantTypeVarTuple[*tuple[int, ...]]() # E\nin_empty: ContravariantTypeVarTuple[()] = ContravariantTypeVarTuple[()]() # OK\nin_fixed_from_variadic: ContravariantTypeVarTuple[int] = ContravariantTypeVarTuple[*tuple[int, ...]]() # OK\nin_variadic_from_fixed: ContravariantTypeVarTuple[*tuple[int, ...]] = ContravariantTypeVarTuple[int]() # E\n\n\nclass CovariantTypeVarTuple[*OutTs]:\n def f(self) -> tuple[*OutTs]:\n raise NotImplementedError\n\n\nout_int: CovariantTypeVarTuple[int] = CovariantTypeVarTuple[object]() # E\nout_obj: CovariantTypeVarTuple[object] = CovariantTypeVarTuple[int]() # OK\nout_multiple1: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[bool, bool]() # OK\nout_multiple2: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[bool, object]() # E\nout_multiple3: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[object, bool]() # E\nout_multiple4: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[object, object]() # E\nout_variadic_int: CovariantTypeVarTuple[*tuple[int, ...]] = CovariantTypeVarTuple[*tuple[object, ...]]() # E\nout_variadic_object: CovariantTypeVarTuple[*tuple[object, ...]] = CovariantTypeVarTuple[*tuple[int, ...]]() # OK\nout_empty: CovariantTypeVarTuple[()] = CovariantTypeVarTuple[()]() # OK\nout_fixed_from_variadic: CovariantTypeVarTuple[int] = CovariantTypeVarTuple[*tuple[int, ...]]() # E\nout_variadic_from_fixed: CovariantTypeVarTuple[*tuple[int, ...]] = CovariantTypeVarTuple[int]() # OK\n\nTs = TypeVarTuple(\"Ts\") # OK\nInferTs = TypeVarTuple(\"InferTs\", infer_variance=True) # OK\nInvTs1 = TypeVarTuple(\"InvTs1\", covariant=True, contravariant=True) # E\nInvTs2 = TypeVarTuple(\"InvTs2\", covariant=True, infer_variance=True) # E\nInvTs3 = TypeVarTuple(\"InvTs3\", contravariant=True, infer_variance=True) # E\n\nclass InvariantTypeVarTupleOld(Generic[*Ts]):\n def in_f(self, *args: *Ts) -> None: # OK\n raise NotImplementedError\n\n def out_f(self) -> tuple[*Ts]: # OK\n raise NotImplementedError\n\n\nobj_old: InvariantTypeVarTupleOld[object] = InvariantTypeVarTupleOld[int]() # E\nint_old: InvariantTypeVarTupleOld[int] = InvariantTypeVarTupleOld[object]() # E\nint_old = InvariantTypeVarTupleOld[int]()\n\n\nInTs = TypeVarTuple(\"InTs\", contravariant=True)\n\nclass ContravariantTypeVarTupleOld(Generic[*InTs]):\n def in_f(self, *args: *InTs) -> None: # OK\n raise NotImplementedError\n\n def out_f(self) -> tuple[*InTs]: # E\n raise NotImplementedError\n\n\nin_obj_old: ContravariantTypeVarTupleOld[object] = ContravariantTypeVarTupleOld[int]() # E\nin_int_old: ContravariantTypeVarTupleOld[int] = ContravariantTypeVarTupleOld[object]() # OK\n\n\nOutTs = TypeVarTuple(\"OutTs\", covariant=True)\n\nclass CovariantTypeVarTupleOld(Generic[*OutTs]):\n def in_f(self, *args: *OutTs) -> None: # E\n raise NotImplementedError\n\n def out_f(self) -> tuple[*OutTs]: # OK\n raise NotImplementedError\n\n\nout_int_old: CovariantTypeVarTupleOld[int] = CovariantTypeVarTupleOld[object]() # E\nout_obj_old: CovariantTypeVarTupleOld[object] = CovariantTypeVarTupleOld[int]() # OK\n\n\n# `infer_variance=True` on a traditional `TypeVarTuple`\nclass InferredContravariantTypeVarTupleOld(Generic[*InferTs]):\n def in_f(self, *args: *InferTs) -> None: # OK\n raise NotImplementedError\n\n\ninfer_in_obj_old: InferredContravariantTypeVarTupleOld[object] = InferredContravariantTypeVarTupleOld[int]() # E\ninfer_in_int_old: InferredContravariantTypeVarTupleOld[int] = InferredContravariantTypeVarTupleOld[object]() # OK\n\n\nclass InferredCovariantTypeVarTupleOld(Generic[*InferTs]):\n def out_f(self) -> tuple[*InferTs]: # OK\n raise NotImplementedError\n\n\ninfer_out_int_old: InferredCovariantTypeVarTupleOld[int] = InferredCovariantTypeVarTupleOld[object]() # E\ninfer_out_obj_old: InferredCovariantTypeVarTupleOld[object] = InferredCovariantTypeVarTupleOld[int]() # OK\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_20.py","code":"\"\"\"\nTests the handling of unpacked tuples embedded within other tuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#unpacked-tuple-form\n\n# > An unpacked form of ``tuple`` (using an unpack operator ``*``)\n# > can be used within a tuple type argument list\n\n# > Unpacking a concrete tuple type is analogous to unpacking a tuple of values at runtime.\n\n\nfrom typing import TypeVarTuple, Unpack, assert_type\n\n\ndef func1(x: tuple[int, *tuple[bool, bool], str]):\n assert_type(x, tuple[int, bool, bool, str])\n assert_type(x, tuple[*tuple[int, bool], bool, str])\n assert_type(x, tuple[int, bool, *tuple[bool, str]])\n\n\n# > Unpacking an unbounded tuple preserves the unbounded tuple as it is.\n\n\ndef func2(x: tuple[int, *tuple[bool, ...], str]):\n assert_type(x, tuple[int, *tuple[bool, ...], str])\n\n\n# > For example, tuple[int, *tuple[str]] is equivalent to tuple[int, str].\n\nu1: tuple[*tuple[int], *tuple[int]] = (int(1), int(1)) # OK\nassert_type(u1, tuple[int, int])\nu2: tuple[*tuple[int, ...], *tuple[int]] # OK\n\n\n# > Only one unbounded tuple can be used within another tuple:\n\nt1: tuple[*tuple[str], *tuple[str]] # OK\nt2: tuple[*tuple[str, *tuple[str, ...]]] # OK\nt3: tuple[*tuple[str, ...], *tuple[int, ...]] # E\nt4: tuple[*tuple[str, *tuple[str, ...]], *tuple[int, ...]] # E\n\n\n# > An unpacked TypeVarTuple counts as an unbounded tuple in the context of this rule\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef func3(t: tuple[*Ts]):\n t5: tuple[*tuple[str], *Ts] # OK\n t6: tuple[*tuple[str, ...], *Ts] # E\n\n\n# > The ``*`` syntax requires Python 3.11 or newer. For older versions of Python,\n# > the ``typing.Unpack`` special form can be used:\n\nt11: tuple[Unpack[tuple[str]], Unpack[tuple[str]]] # OK\nt12: tuple[Unpack[tuple[str, Unpack[tuple[str, ...]]]]] # OK\nt13: tuple[Unpack[tuple[str, ...]], Unpack[tuple[int, ...]]] # E\nt14: tuple[ # E[t14]\n Unpack[tuple[str, Unpack[tuple[str, ...]]]], Unpack[tuple[int, ...]] # E[t14]\n]\n","source":"typing_tests","origin":"conformance/tests/tuples_unpacked.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n an = g.__anext__()\n try:\n while True:\n try:\n an.__next__()\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n break\n else:\n res.append('EMPTY StopIteration')\n break\n except StopAsyncIteration:\n raise\n except Exception as ex:\n res.append(str(type(ex)))\n break\n except StopAsyncIteration:\n res.append('STOP')\n break\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_exception_11(self):\n def sync_gen():\n yield 10\n yield 20\n\n def sync_gen_wrapper():\n yield 1\n sg = sync_gen()\n sg.send(None)\n try:\n sg.throw(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n async def async_gen():\n yield 10\n yield 20\n\n async def async_gen_wrapper():\n yield 1\n asg = async_gen()\n await asg.asend(None)\n try:\n await asg.athrow(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())\n\n def test_async_gen_exception_12(self):\n async def gen():\n await anext(me)\n yield 123\n\n me = gen()\n ai = me.__aiter__()\n an = ai.__anext__()\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n an.__next__()\n\n def test_async_gen_3_arg_deprecation_warning(self):\n async def gen():\n yield 123\n\n with self.assertWarns(DeprecationWarning):\n gen().athrow(GeneratorExit, GeneratorExit(), None)\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n\n self.assertTrue(inspect.isawaitable(g.aclose()))\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n asyncio.set_event_loop_policy(None)\n\n def check_async_iterator_anext(self, ait_class):\n with self.subTest(anext=\"pure-Python\"):\n self._check_async_iterator_anext(ait_class, py_anext)\n with self.subTest(anext=\"builtin\"):\n self._check_async_iterator_anext(ait_class, anext)\n\n def _check_async_iterator_anext(self, ait_class, anext):\n g = ait_class()\n async def consume():\n results = []\n results.append(await anext(g))\n results.append(await anext(g))\n results.append(await anext(g, 'buckle my shoe'))\n return results\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2, 'buckle my shoe'])\n with self.assertRaises(StopAsyncIteration):\n self.loop.run_until_complete(consume())\n\n async def test_2():\n g1 = ait_class()\n self.assertEqual(await anext(g1), 1)\n self.assertEqual(await anext(g1), 2)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n\n g2 = ait_class()\n self.assertEqual(await anext(g2, \"default\"), 1)\n self.assertEqual(await anext(g2, \"default\"), 2)\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n\n return \"completed\"\n\n result = self.loop.run_until_complete(test_2())\n self.assertEqual(result, \"completed\")\n\n def test_send():\n p = ait_class()\n obj = anext(p, \"completed\")\n with self.assertRaises(StopIteration):\n with contextlib.closing(obj.__await__()) as g:\n g.send(None)\n\n test_send()\n\n async def test_throw():\n p = ait_class()\n obj = anext(p, \"completed\")\n self.assertRaises(SyntaxError, obj.throw, SyntaxError)\n return \"completed\"\n\n result = self.loop.run_until_complete(test_throw())\n self.assertEqual(result, \"completed\")\n\n def test_async_generator_anext(self):\n async def agen():\n yield 1\n yield 2\n self.check_async_iterator_anext(agen)\n\n def test_python_async_iterator_anext(self):\n class MyAsyncIter:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n async def __anext__(self):\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIter)\n\n def test_python_async_iterator_types_coroutine_anext(self):\n import types\n class MyAsyncIterWithTypesCoro:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n @types.coroutine\n def __anext__(self):\n if False:\n yield \"this is a generator-based coroutine\"\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIterWithTypesCoro)\n\n def test_async_gen_aiter(self):\n async def gen():\n yield 1\n yield 2\n g = gen()\n async def consume():\n return [i async for i in aiter(g)]\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_aiter_class(self):\n results = []\n class Gen:\n async def __aiter__(self):\n yield 1\n yield 2\n g = Gen()\n async def consume():\n ait = aiter(g)\n while True:\n try:\n results.append(await anext(ait))\n except StopAsyncIteration:\n break\n self.loop.run_until_complete(consume())\n self.assertEqual(results, [1, 2])\n\n def test_aiter_idempotent(self):\n async def gen():\n yield 1\n applied_once = aiter(gen())\n applied_twice = aiter(applied_once)\n self.assertIs(applied_once, applied_twice)\n\n def test_anext_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await anext()\n async def call_with_too_many_args():\n await anext(gen(), 1, 3)\n async def call_with_wrong_type_args():\n await anext(1, gen())\n async def call_with_kwarg():\n await anext(aiterator=gen())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_kwarg())\n\n def test_anext_bad_await(self):\n async def bad_awaitable():\n class BadAwaitable:\n def __await__(self):\n return 42\n class MyAsyncIter:\n def __aiter__(self):\n return self\n def __anext__(self):\n return BadAwaitable()\n regex = r\"__await__.*iterator\"\n awaitable = anext(MyAsyncIter(), \"default\")\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n awaitable = anext(MyAsyncIter())\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(bad_awaitable())\n self.assertEqual(result, \"completed\")\n\n async def check_anext_returning_iterator(self, aiter_class):\n awaitable = anext(aiter_class(), \"default\")\n with self.assertRaises(TypeError):\n await awaitable\n awaitable = anext(aiter_class())\n with self.assertRaises(TypeError):\n await awaitable\n return \"completed\"\n\n def test_anext_return_iterator(self):\n class WithIterAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return iter(\"abc\")\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithIterAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_return_generator(self):\n class WithGenAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n yield\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithGenAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_await_raises(self):\n class RaisingAwaitable:\n def __await__(self):\n raise ZeroDivisionError()\n yield\n class WithRaisingAwaitableAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return RaisingAwaitable()\n async def do_test():\n awaitable = anext(WithRaisingAwaitableAnext())\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n awaitable = anext(WithRaisingAwaitableAnext(), \"default\")\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(do_test())\n self.assertEqual(result, \"completed\")\n\n def test_anext_iter(self):\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyError(Exception):\n pass\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n def test1(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError()), 2)\n try:\n g.send(None)\n except StopIteration as e:\n err = e\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(err.value, \"default\")\n\n def test2(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError()), 2)\n with self.assertRaises(MyError):\n g.throw(MyError())\n\n def test3(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n g.close()\n with self.assertRaisesRegex(RuntimeError, 'cannot reuse'):\n self.assertEqual(g.send(None), 1)\n\n def test4(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n self.assertEqual(g.throw(MyError()), 20)\n with self.assertRaisesRegex(MyError, 'val'):\n g.throw(MyError('val'))\n\n def test5(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n return\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n with self.assertRaisesRegex(StopIteration, 'default'):\n g.throw(MyError())\n\n def test6(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n await _async_yield(1)\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n with self.assertRaises(MyError):\n g.throw(MyError())\n\n def run_test(test):\n with self.subTest('pure-Python anext()'):\n test(py_anext)\n with self.subTest('builtin anext()'):\n test(anext)\n\n run_test(test1)\n run_test(test2)\n run_test(test3)\n run_test(test4)\n run_test(test5)\n run_test(test6)\n\n def test_aiter_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await aiter()\n async def call_with_too_many_args():\n await aiter(gen(), 1)\n async def call_with_wrong_type_arg():\n await aiter(1)\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_arg())\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n await asyncio.sleep(0.01)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n gc_collect() # For PyPy or other GCs.\n\n # Starts running the aclose task\n await asyncio.sleep(0)\n # For asyncio.sleep(0) in finally block\n await asyncio.sleep(0)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_aclose_12(self):\n DONE = 0\n\n async def target():\n await asyncio.sleep(0.01)\n 1 / 0\n\n async def foo():\n nonlocal DONE\n task = asyncio.create_task(target())\n try:\n yield 1\n finally:\n try:\n await task\n except ZeroDivisionError:\n DONE = 1\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout)\n yield 1\n finally:\n await asyncio.sleep(0)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1))\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t1)\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t2)\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(finalized, 2)\n\n def test_async_gen_asyncio_shutdown_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n self.assertEqual(messages, [])\n\n def test_async_gen_asyncio_shutdown_exception_01(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n message, = messages\n self.assertEqual(message['asyncgen'], it)\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('an error occurred during closing of asynchronous generator',\n message['message'])\n\n def test_async_gen_asyncio_shutdown_exception_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n gc_collect()\n\n asyncio.run(main())\n\n message, = messages\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('unhandled exception during asyncio.run() shutdown',\n message['message'])\n\n def test_async_gen_expression_01(self):\n async def arange(n):\n for i in range(n):\n await asyncio.sleep(0.01)\n yield i\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 async for i in arange(n))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(10)])\n\n def test_async_gen_expression_02(self):\n async def wrap(n):\n await asyncio.sleep(0.01)\n return n\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 for i in range(n) if await wrap(i))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(1, 10)])\n\n def test_asyncgen_nonstarted_hooks_are_cancellable(self):\n # See https://bugs.python.org/issue38013\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n\n asyncio.run(main())\n\n self.assertEqual([], messages)\n\n def test_async_gen_await_same_anext_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.__anext__()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"\n ):\n await nxt\n\n await it.aclose() # prevent unfinished iterator warning\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_await_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.aclose()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n await nxt\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_twice_with_different_coros(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n await it.aclose()\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_after_exhaustion(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n async for _ in it:\n pass\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_compatible_with_get_stack(self):\n async def async_generator():\n yield object()\n\n async def run():\n ag = async_generator()\n asyncio.create_task(ag.aclose())\n tasks = asyncio.all_tasks()\n for task in tasks:\n # No AttributeError raised\n task.get_stack()\n\n self.loop.run_until_complete(run())\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"breakpoint","pep":"553","introduced_in":"3.7","form":"modern","file":"breakpoint/modern_01.py","code":"import ast\nimport asyncio\nimport builtins\nimport collections\nimport decimal\nimport fractions\nimport gc\nimport io\nimport locale\nimport math\nimport os\nimport pickle\nimport platform\nimport random\nimport re\nimport sys\nimport traceback\nimport types\nimport typing\nimport unittest\nimport warnings\nfrom contextlib import ExitStack\nfrom functools import partial\nfrom inspect import CO_COROUTINE\nfrom itertools import product\nfrom textwrap import dedent\nfrom types import AsyncGeneratorType, FunctionType, CellType\nfrom operator import neg\nfrom test import support\nfrom test.support import (cpython_only, swap_attr, maybe_get_event_loop_policy)\nfrom test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink)\nfrom test.support.script_helper import assert_python_ok\nfrom test.support.warnings_helper import check_warnings\nfrom test.support import requires_IEEE_754\nfrom unittest.mock import MagicMock, patch\n\n\nclass TestBreakpoint(unittest.TestCase):\n def setUp(self):\n # These tests require a clean slate environment. For example, if the\n # test suite is run with $PYTHONBREAKPOINT set to something else, it\n # will mess up these tests. Similarly for sys.breakpointhook.\n # Cleaning the slate here means you can't use breakpoint() to debug\n # these tests, but I think that's okay. Just use pdb.set_trace() if\n # you must.\n self.resources = ExitStack()\n self.addCleanup(self.resources.close)\n self.env = self.resources.enter_context(EnvironmentVarGuard())\n del self.env['PYTHONBREAKPOINT']\n self.resources.enter_context(\n swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))\n\n def test_breakpoint(self):\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once()\n\n def test_breakpoint_with_breakpointhook_set(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_breakpointhook_reset(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n # Reset the hook and it will not be called again.\n sys.breakpointhook = sys.__breakpointhook__\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_args_and_keywords(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint(1, 2, 3, four=4, five=5)\n my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)\n\n def test_breakpoint_with_passthru_error(self):\n def my_breakpointhook():\n pass\n sys.breakpointhook = my_breakpointhook\n self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_builtin(self):\n self.env['PYTHONBREAKPOINT'] = 'int'\n with patch('builtins.int') as mock:\n breakpoint('7')\n mock.assert_called_once_with('7')\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_other(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_noop_0(self):\n self.env['PYTHONBREAKPOINT'] = '0'\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_not_called()\n\n def test_envar_good_path_empty_string(self):\n # PYTHONBREAKPOINT='' is the same as it not being set.\n self.env['PYTHONBREAKPOINT'] = ''\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_unimportable(self):\n for envar in (\n '.', '..', '.foo', 'foo.', '.int', 'int.',\n '.foo.bar', '..foo.bar', '/./',\n 'nosuchbuiltin',\n 'nosuchmodule.nosuchcallable',\n ):\n with self.subTest(envar=envar):\n self.env['PYTHONBREAKPOINT'] = envar\n mock = self.resources.enter_context(patch('pdb.set_trace'))\n w = self.resources.enter_context(check_warnings(quiet=True))\n breakpoint()\n self.assertEqual(\n str(w.message),\n f'Ignoring unimportable $PYTHONBREAKPOINT: \"{envar}\"')\n self.assertEqual(w.category, RuntimeWarning)\n mock.assert_not_called()\n\n def test_envar_ignored_when_hook_is_set(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n sys.breakpointhook = int\n breakpoint()\n mock.assert_not_called()\n\n def test_runtime_error_when_hook_is_lost(self):\n del sys.breakpointhook\n with self.assertRaises(RuntimeError):\n breakpoint()\n","source":"cpython_tests","origin":"Lib/test/test_builtin.py::TestBreakpoint","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(ZeroDivisionError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n notes = cm.exception.__notes__\n self.assertRegex(str(notes), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(notes), r'\\battr\\b')\n self.assertRegex(str(notes), r'\\bDescriptor\\b')\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(TypeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n notes = cm.exception.__notes__\n self.assertRegex(str(notes), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(notes), r'\\battr\\b')\n self.assertRegex(str(notes), r'\\bDescriptor\\b')\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_03.py","code":"import concurrent.futures\nimport contextvars\nimport functools\nimport gc\nimport random\nimport time\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import threading_helper\n\n\nclass ContextTest(unittest.TestCase):\n def test_context_var_new_1(self):\n with self.assertRaisesRegex(TypeError, 'takes exactly 1'):\n contextvars.ContextVar()\n\n with self.assertRaisesRegex(TypeError, 'must be a str'):\n contextvars.ContextVar(1)\n\n c = contextvars.ContextVar('aaa')\n self.assertEqual(c.name, 'aaa')\n\n with self.assertRaises(AttributeError):\n c.name = 'bbb'\n\n self.assertNotEqual(hash(c), hash('aaa'))\n\n @isolated_context\n def test_context_var_repr_1(self):\n c = contextvars.ContextVar('a')\n self.assertIn('a', repr(c))\n\n c = contextvars.ContextVar('a', default=123)\n self.assertIn('123', repr(c))\n\n lst = []\n c = contextvars.ContextVar('a', default=lst)\n lst.append(c)\n self.assertIn('...', repr(c))\n self.assertIn('...', repr(lst))\n\n t = c.set(1)\n self.assertIn(repr(c), repr(t))\n self.assertNotIn(' used ', repr(t))\n c.reset(t)\n self.assertIn(' used ', repr(t))\n\n def test_context_subclassing_1(self):\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContextVar(contextvars.ContextVar):\n # Potentially we might want ContextVars to be subclassable.\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContext(contextvars.Context):\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyToken(contextvars.Token):\n pass\n\n def test_context_new_1(self):\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1, a=1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(a=1)\n contextvars.Context(**{})\n\n def test_context_typerrors_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx[1]\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n 1 in ctx\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx.get(1)\n\n def test_context_get_context_1(self):\n ctx = contextvars.copy_context()\n self.assertIsInstance(ctx, contextvars.Context)\n\n def test_context_run_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required'):\n ctx.run()\n\n def test_context_run_2(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n kwargs['spam'] = 'foo'\n args += ('bar',)\n return args, kwargs\n\n for f in (func, functools.partial(func)):\n # partial doesn't support FASTCALL\n\n self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))\n self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, a=2),\n (('bar',), {'a': 2, 'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, 11, a=2),\n ((11, 'bar'), {'a': 2, 'spam': 'foo'}))\n\n a = {}\n self.assertEqual(\n ctx.run(f, 11, **a),\n ((11, 'bar'), {'spam': 'foo'}))\n self.assertEqual(a, {})\n\n def test_context_run_3(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2, a=123)\n\n @isolated_context\n def test_context_run_4(self):\n ctx1 = contextvars.Context()\n ctx2 = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func2():\n self.assertIsNone(var.get(None))\n\n def func1():\n self.assertIsNone(var.get(None))\n var.set('spam')\n ctx2.run(func2)\n self.assertEqual(var.get(None), 'spam')\n\n cur = contextvars.copy_context()\n self.assertEqual(len(cur), 1)\n self.assertEqual(cur[var], 'spam')\n return cur\n\n returned_ctx = ctx1.run(func1)\n self.assertEqual(ctx1, returned_ctx)\n self.assertEqual(returned_ctx[var], 'spam')\n self.assertIn(var, returned_ctx)\n\n def test_context_run_5(self):\n ctx = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func():\n self.assertIsNone(var.get(None))\n var.set('spam')\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n\n self.assertIsNone(var.get(None))\n\n def test_context_run_6(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('a', default=0)\n\n def fun():\n self.assertEqual(c.get(), 0)\n self.assertIsNone(ctx.get(c))\n\n c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(ctx.get(c), 42)\n\n ctx.run(fun)\n\n def test_context_run_7(self):\n ctx = contextvars.Context()\n\n def fun():\n with self.assertRaisesRegex(RuntimeError, 'is already entered'):\n ctx.run(fun)\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_1(self):\n c = contextvars.ContextVar('c')\n with self.assertRaises(LookupError):\n c.get()\n\n self.assertIsNone(c.get(None))\n\n t0 = c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n self.assertIs(t0.old_value, t0.MISSING)\n self.assertIs(t0.old_value, contextvars.Token.MISSING)\n self.assertIs(t0.var, c)\n\n t = c.set('spam')\n self.assertEqual(c.get(), 'spam')\n self.assertEqual(c.get(None), 'spam')\n self.assertEqual(t.old_value, 42)\n c.reset(t)\n\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n\n c.set('spam2')\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t)\n self.assertEqual(c.get(), 'spam2')\n\n ctx1 = contextvars.copy_context()\n self.assertIn(c, ctx1)\n\n c.reset(t0)\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t0)\n self.assertIsNone(c.get(None))\n\n self.assertIn(c, ctx1)\n self.assertEqual(ctx1[c], 'spam2')\n self.assertEqual(ctx1.get(c, 'aa'), 'spam2')\n self.assertEqual(len(ctx1), 1)\n self.assertEqual(list(ctx1.items()), [(c, 'spam2')])\n self.assertEqual(list(ctx1.values()), ['spam2'])\n self.assertEqual(list(ctx1.keys()), [c])\n self.assertEqual(list(ctx1), [c])\n\n ctx2 = contextvars.copy_context()\n self.assertNotIn(c, ctx2)\n with self.assertRaises(KeyError):\n ctx2[c]\n self.assertEqual(ctx2.get(c, 'aa'), 'aa')\n self.assertEqual(len(ctx2), 0)\n self.assertEqual(list(ctx2), [])\n\n @isolated_context\n def test_context_getset_2(self):\n v1 = contextvars.ContextVar('v1')\n v2 = contextvars.ContextVar('v2')\n\n t1 = v1.set(42)\n with self.assertRaisesRegex(ValueError, 'by a different'):\n v2.reset(t1)\n\n @isolated_context\n def test_context_getset_3(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n def fun():\n self.assertEqual(c.get(), 42)\n with self.assertRaises(KeyError):\n ctx[c]\n self.assertIsNone(ctx.get(c))\n self.assertEqual(ctx.get(c, 'spam'), 'spam')\n self.assertNotIn(c, ctx)\n self.assertEqual(list(ctx.keys()), [])\n\n t = c.set(1)\n self.assertEqual(list(ctx.keys()), [c])\n self.assertEqual(ctx[c], 1)\n\n c.reset(t)\n self.assertEqual(list(ctx.keys()), [])\n with self.assertRaises(KeyError):\n ctx[c]\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_4(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n tok = ctx.run(c.set, 1)\n\n with self.assertRaisesRegex(ValueError, 'different Context'):\n c.reset(tok)\n\n @isolated_context\n def test_context_getset_5(self):\n c = contextvars.ContextVar('c', default=42)\n c.set([])\n\n def fun():\n c.set([])\n c.get().append(42)\n self.assertEqual(c.get(), [42])\n\n contextvars.copy_context().run(fun)\n self.assertEqual(c.get(), [])\n\n def test_context_copy_1(self):\n ctx1 = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def ctx1_fun():\n c.set(10)\n\n ctx2 = ctx1.copy()\n self.assertEqual(ctx2[c], 10)\n\n c.set(20)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 10)\n\n ctx2.run(ctx2_fun)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 30)\n\n def ctx2_fun():\n self.assertEqual(c.get(), 10)\n c.set(30)\n self.assertEqual(c.get(), 30)\n\n ctx1.run(ctx1_fun)\n\n @isolated_context\n @threading_helper.requires_working_threading()\n def test_context_threads_1(self):\n cvar = contextvars.ContextVar('cvar')\n\n def sub(num):\n for i in range(10):\n cvar.set(num + i)\n time.sleep(random.uniform(0.001, 0.05))\n self.assertEqual(cvar.get(), num + i)\n return num\n\n tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)\n try:\n results = list(tp.map(sub, range(10)))\n finally:\n tp.shutdown()\n self.assertEqual(results, list(range(10)))\n","source":"cpython_tests","origin":"Lib/test/test_context.py::ContextTest","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_17.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFieldNoAnnotation(unittest.TestCase):\n def test_field_without_annotation(self):\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n @dataclass\n class C:\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base(self):\n @dataclass\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base_not_dataclass(self):\n # Same test, but with the base class not a dataclass.\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFieldNoAnnotation","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_18.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDocString(unittest.TestCase):\n def assertDocStrEqual(self, a, b):\n # Because 3.6 and 3.7 differ in how inspect.signature work\n # (see bpo #32108), for the time being just compare them with\n # whitespace stripped.\n self.assertEqual(a.replace(' ', ''), b.replace(' ', ''))\n\n def test_existing_docstring_not_overridden(self):\n @dataclass\n class C:\n \"\"\"Lorem ipsum\"\"\"\n x: int\n\n self.assertEqual(C.__doc__, \"Lorem ipsum\")\n\n def test_docstring_no_fields(self):\n @dataclass\n class C:\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C()\")\n\n def test_docstring_one_field(self):\n @dataclass\n class C:\n x: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int)\")\n\n def test_docstring_two_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int)\")\n\n def test_docstring_three_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n z: str\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int, z:str)\")\n\n def test_docstring_one_field_with_default(self):\n @dataclass\n class C:\n x: int = 3\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int=3)\")\n\n def test_docstring_one_field_with_default_none(self):\n @dataclass\n class C:\n x: Union[int, type(None)] = None\n\n self.assertDocStrEqual(C.__doc__, \"C(x:Optional[int]=None)\")\n\n def test_docstring_list_field(self):\n @dataclass\n class C:\n x: List[int]\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int])\")\n\n def test_docstring_list_field_with_default_factory(self):\n @dataclass\n class C:\n x: List[int] = field(default_factory=list)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int]=)\")\n\n def test_docstring_deque_field(self):\n @dataclass\n class C:\n x: deque\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque)\")\n\n def test_docstring_deque_field_with_default_factory(self):\n @dataclass\n class C:\n x: deque = field(default_factory=deque)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque=)\")\n\n def test_docstring_with_no_signature(self):\n # See https://github.com/python/cpython/issues/103449\n class Meta(type):\n __call__ = dict\n class Base(metaclass=Meta):\n pass\n\n @dataclass\n class C(Base):\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDocString","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_19.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestInit(unittest.TestCase):\n def test_base_has_init(self):\n class B:\n def __init__(self):\n self.z = 100\n\n # Make sure that declaring this class doesn't raise an error.\n # The issue is that we can't override __init__ in our class,\n # but it should be okay to add __init__ to us if our base has\n # an __init__.\n @dataclass\n class C(B):\n x: int = 0\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertNotIn('z', vars(c))\n\n # Make sure that if we don't add an init, the base __init__\n # gets called.\n @dataclass(init=False)\n class C(B):\n x: int = 10\n c = C()\n self.assertEqual(c.x, 10)\n self.assertEqual(c.z, 100)\n\n def test_no_init(self):\n @dataclass(init=False)\n class C:\n i: int = 0\n self.assertEqual(C().i, 0)\n\n @dataclass(init=False)\n class C:\n i: int = 2\n def __init__(self):\n self.i = 3\n self.assertEqual(C().i, 3)\n\n def test_overwriting_init(self):\n # If the class has __init__, use it no matter the value of\n # init=.\n\n @dataclass\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(3).x, 6)\n\n @dataclass(init=True)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(4).x, 8)\n\n @dataclass(init=False)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(5).x, 10)\n\n def test_inherit_from_protocol(self):\n # Dataclasses inheriting from protocol should preserve their own `__init__`.\n # See bpo-45081.\n\n class P(Protocol):\n a: int\n\n @dataclass\n class C(P):\n a: int\n\n self.assertEqual(C(5).a, 5)\n\n @dataclass\n class D(P):\n def __init__(self, a):\n self.a = a * 2\n\n self.assertEqual(D(5).a, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestInit","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_20.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestRepr(unittest.TestCase):\n def test_repr(self):\n @dataclass\n class B:\n x: int\n\n @dataclass\n class C(B):\n y: int = 10\n\n o = C(4)\n self.assertEqual(repr(o), 'TestRepr.test_repr..C(x=4, y=10)')\n\n @dataclass\n class D(C):\n x: int = 20\n self.assertEqual(repr(D()), 'TestRepr.test_repr..D(x=20, y=10)')\n\n @dataclass\n class C:\n @dataclass\n class D:\n i: int\n @dataclass\n class E:\n pass\n self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr..C.D(i=0)')\n self.assertEqual(repr(C.E()), 'TestRepr.test_repr..C.E()')\n\n def test_no_repr(self):\n # Test a class with no __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n self.assertIn(f'{__name__}.TestRepr.test_no_repr..C object at',\n repr(C(3)))\n\n # Test a class with a __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'C-class'\n self.assertEqual(repr(C(3)), 'C-class')\n\n def test_overwriting_repr(self):\n # If the class has __repr__, use it no matter the value of\n # repr=.\n\n @dataclass\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=True)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestRepr","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_21.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestEq(unittest.TestCase):\n def test_no_eq(self):\n # Test a class with no __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n self.assertNotEqual(C(0), C(0))\n c = C(3)\n self.assertEqual(c, c)\n\n # Test a class with an __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 10\n self.assertEqual(C(3), 10)\n\n def test_overwriting_eq(self):\n # If the class has __eq__, use it no matter the value of\n # eq=.\n\n @dataclass\n class C:\n x: int\n def __eq__(self, other):\n return other == 3\n self.assertEqual(C(1), 3)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=True)\n class C:\n x: int\n def __eq__(self, other):\n return other == 4\n self.assertEqual(C(1), 4)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 5\n self.assertEqual(C(1), 5)\n self.assertNotEqual(C(1), 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestEq","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_22.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestOrdering(unittest.TestCase):\n def test_functools_total_ordering(self):\n # Test that functools.total_ordering works with this class.\n @total_ordering\n @dataclass\n class C:\n x: int\n def __lt__(self, other):\n # Perform the test \"backward\", just to make\n # sure this is being called.\n return self.x >= other\n\n self.assertLess(C(0), -1)\n self.assertLessEqual(C(0), -1)\n self.assertGreater(C(0), 1)\n self.assertGreaterEqual(C(0), 1)\n\n def test_no_order(self):\n # Test that no ordering functions are added by default.\n @dataclass(order=False)\n class C:\n x: int\n # Make sure no order methods are added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__lt__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n # Test that __lt__ is still called\n @dataclass(order=False)\n class C:\n x: int\n def __lt__(self, other):\n return False\n # Make sure other methods aren't added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n def test_overwriting_order(self):\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __lt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __lt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __le__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __le__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __gt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __gt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __ge__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __ge__(self):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestOrdering","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_23.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestHash(unittest.TestCase):\n def test_unsafe_hash(self):\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n y: str\n self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))\n\n def test_hash_rules(self):\n def non_bool(value):\n # Map to something else that's True, but not a bool.\n if value is None:\n return None\n if value:\n return (3,)\n return 0\n\n def test(case, unsafe_hash, eq, frozen, with_hash, result):\n with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,\n frozen=frozen):\n if result != 'exception':\n if with_hash:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n else:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n pass\n\n # See if the result matches what's expected.\n if result == 'fn':\n # __hash__ contains the function we generated.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNotNone(C.__dict__['__hash__'])\n\n elif result == '':\n # __hash__ is not present in our class.\n if not with_hash:\n self.assertNotIn('__hash__', C.__dict__)\n\n elif result == 'none':\n # __hash__ is set to None.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNone(C.__dict__['__hash__'])\n\n elif result == 'exception':\n # Creating the class should cause an exception.\n # This only happens with with_hash==True.\n assert(with_hash)\n with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n\n else:\n assert False, f'unknown result {result!r}'\n\n # There are 8 cases of:\n # unsafe_hash=True/False\n # eq=True/False\n # frozen=True/False\n # And for each of these, a different result if\n # __hash__ is defined or not.\n for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([\n (False, False, False, '', ''),\n (False, False, True, '', ''),\n (False, True, False, 'none', ''),\n (False, True, True, 'fn', ''),\n (True, False, False, 'fn', 'exception'),\n (True, False, True, 'fn', 'exception'),\n (True, True, False, 'fn', 'exception'),\n (True, True, True, 'fn', 'exception'),\n ], 1):\n test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)\n test(case, unsafe_hash, eq, frozen, True, res_defined_hash)\n\n # Test non-bool truth values, too. This is just to\n # make sure the data-driven table in the decorator\n # handles non-bool values.\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)\n\n\n def test_eq_only(self):\n # If a class defines __eq__, __hash__ is automatically added\n # and set to None. This is normal Python behavior, not\n # related to dataclasses. Make sure we don't interfere with\n # that (see bpo=32546).\n\n @dataclass\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1))\n self.assertNotEqual(C(1), C(4))\n\n # And make sure things work in this case if we specify\n # unsafe_hash=True.\n @dataclass(unsafe_hash=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1.0))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n # And check that the classes __eq__ is being used, despite\n # specifying eq=True.\n @dataclass(unsafe_hash=True, eq=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == 3 and self.i == other.i\n self.assertEqual(C(3), C(3))\n self.assertNotEqual(C(1), C(1))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n def test_0_field_hash(self):\n @dataclass(frozen=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n @dataclass(unsafe_hash=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n def test_1_field_hash(self):\n @dataclass(frozen=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n def test_hash_no_args(self):\n # Test dataclasses with no hash= argument. This exists to\n # make sure that if the @dataclass parameter name is changed\n # or the non-default hashing behavior changes, the default\n # hashability keeps working the same way.\n\n class Base:\n def __hash__(self):\n return 301\n\n # If frozen or eq is None, then use the default value (do not\n # specify any value in the decorator).\n for frozen, eq, base, expected in [\n (None, None, object, 'unhashable'),\n (None, None, Base, 'unhashable'),\n (None, False, object, 'object'),\n (None, False, Base, 'base'),\n (None, True, object, 'unhashable'),\n (None, True, Base, 'unhashable'),\n (False, None, object, 'unhashable'),\n (False, None, Base, 'unhashable'),\n (False, False, object, 'object'),\n (False, False, Base, 'base'),\n (False, True, object, 'unhashable'),\n (False, True, Base, 'unhashable'),\n (True, None, object, 'tuple'),\n (True, None, Base, 'tuple'),\n (True, False, object, 'object'),\n (True, False, Base, 'base'),\n (True, True, object, 'tuple'),\n (True, True, Base, 'tuple'),\n ]:\n\n with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):\n # First, create the class.\n if frozen is None and eq is None:\n @dataclass\n class C(base):\n i: int\n elif frozen is None:\n @dataclass(eq=eq)\n class C(base):\n i: int\n elif eq is None:\n @dataclass(frozen=frozen)\n class C(base):\n i: int\n else:\n @dataclass(frozen=frozen, eq=eq)\n class C(base):\n i: int\n\n # Now, make sure it hashes as expected.\n if expected == 'unhashable':\n c = C(10)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(c)\n\n elif expected == 'base':\n self.assertEqual(hash(C(10)), 301)\n\n elif expected == 'object':\n # I'm not sure what test to use here. object's\n # hash isn't based on id(), so calling hash()\n # won't tell us much. So, just check the\n # function used is object's.\n self.assertIs(C.__hash__, object.__hash__)\n\n elif expected == 'tuple':\n self.assertEqual(hash(C(42)), hash((42,)))\n\n else:\n assert False, f'unknown value for expected={expected!r}'\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestHash","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_24.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestFrozen(unittest.TestCase):\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n c = C(10)\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertEqual(c.i, 10)\n\n def test_frozen_empty(self):\n @dataclass(frozen=True)\n class C:\n pass\n\n c = C()\n self.assertFalse(hasattr(c, 'i'))\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertFalse(hasattr(c, 'i'))\n with self.assertRaises(FrozenInstanceError):\n del c.i\n\n def test_inherit(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n @dataclass(frozen=True)\n class D(C):\n j: int\n\n d = D(0, 10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n with self.assertRaises(FrozenInstanceError):\n d.j = 6\n self.assertEqual(d.i, 0)\n self.assertEqual(d.j, 10)\n\n def test_inherit_nonfrozen_from_empty_frozen(self):\n @dataclass(frozen=True)\n class C:\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(C):\n j: int\n\n def test_inherit_nonfrozen_from_empty(self):\n @dataclass\n class C:\n pass\n\n @dataclass\n class D(C):\n j: int\n\n d = D(3)\n self.assertEqual(d.j, 3)\n self.assertIsInstance(d, C)\n\n # Test both ways: with an intermediate normal (non-dataclass)\n # class and without an intermediate class.\n def test_inherit_nonfrozen_from_frozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass(frozen=True)\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(I):\n pass\n\n def test_inherit_frozen_from_nonfrozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one'):\n @dataclass(frozen=True)\n class D(I):\n pass\n\n def test_inherit_from_normal_class(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n class C:\n pass\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n @dataclass(frozen=True)\n class D(I):\n i: int\n\n d = D(10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n\n def test_non_frozen_normal_derived(self):\n # See bpo-32953.\n\n @dataclass(frozen=True)\n class D:\n x: int\n y: int = 10\n\n class S(D):\n pass\n\n s = S(3)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n s.cached = True\n\n # But can't change the frozen attributes.\n with self.assertRaises(FrozenInstanceError):\n s.x = 5\n with self.assertRaises(FrozenInstanceError):\n s.y = 5\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.cached, True)\n\n with self.assertRaises(FrozenInstanceError):\n del s.x\n self.assertEqual(s.x, 3)\n with self.assertRaises(FrozenInstanceError):\n del s.y\n self.assertEqual(s.y, 10)\n del s.cached\n self.assertFalse(hasattr(s, 'cached'))\n with self.assertRaises(AttributeError) as cm:\n del s.cached\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n\n def test_non_frozen_normal_derived_from_empty_frozen(self):\n @dataclass(frozen=True)\n class D:\n pass\n\n class S(D):\n pass\n\n s = S()\n self.assertFalse(hasattr(s, 'x'))\n s.x = 5\n self.assertEqual(s.x, 5)\n\n del s.x\n self.assertFalse(hasattr(s, 'x'))\n with self.assertRaises(AttributeError) as cm:\n del s.x\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n\n def test_overwriting_frozen(self):\n # frozen uses __setattr__ and __delattr__.\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __setattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __setattr__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __delattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __delattr__(self):\n pass\n\n @dataclass(frozen=False)\n class C:\n x: int\n def __setattr__(self, name, value):\n self.__dict__['x'] = value * 2\n self.assertEqual(C(10).x, 20)\n\n def test_frozen_hash(self):\n @dataclass(frozen=True)\n class C:\n x: Any\n\n # If x is immutable, we can compute the hash. No exception is\n # raised.\n hash(C(3))\n\n # If x is mutable, computing the hash is an error.\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(C({}))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestFrozen","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_25.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestSlots(unittest.TestCase):\n def test_simple(self):\n @dataclass\n class C:\n __slots__ = ('x',)\n x: Any\n\n # There was a bug where a variable in a slot was assumed to\n # also have a default value (of type\n # types.MemberDescriptorType).\n with self.assertRaisesRegex(TypeError,\n r\"__init__\\(\\) missing 1 required positional argument: 'x'\"):\n C()\n\n # We can create an instance, and assign to x.\n c = C(10)\n self.assertEqual(c.x, 10)\n c.x = 5\n self.assertEqual(c.x, 5)\n\n # We can't assign to anything else.\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'y'\"):\n c.y = 5\n\n def test_derived_added_field(self):\n # See bpo-33100.\n @dataclass\n class Base:\n __slots__ = ('x',)\n x: Any\n\n @dataclass\n class Derived(Base):\n x: int\n y: int\n\n d = Derived(1, 2)\n self.assertEqual((d.x, d.y), (1, 2))\n\n # We can add a new field to the derived instance.\n d.z = 10\n\n def test_generated_slots(self):\n @dataclass(slots=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n self.assertEqual((c.x, c.y), (1, 2))\n\n c.x = 3\n c.y = 4\n self.assertEqual((c.x, c.y), (3, 4))\n\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'z'\"):\n c.z = 5\n\n def test_add_slots_when_slots_exists(self):\n with self.assertRaisesRegex(TypeError, '^C already specifies __slots__$'):\n @dataclass(slots=True)\n class C:\n __slots__ = ('x',)\n x: int\n\n def test_generated_slots_value(self):\n\n class Root:\n __slots__ = {'x'}\n\n class Root2(Root):\n __slots__ = {'k': '...', 'j': ''}\n\n class Root3(Root2):\n __slots__ = ['h']\n\n class Root4(Root3):\n __slots__ = 'aa'\n\n @dataclass(slots=True)\n class Base(Root4):\n y: int\n j: str\n h: str\n\n self.assertEqual(Base.__slots__, ('y', ))\n\n @dataclass(slots=True)\n class Derived(Base):\n aa: float\n x: str\n z: int\n k: str\n h: str\n\n self.assertEqual(Derived.__slots__, ('z', ))\n\n @dataclass\n class AnotherDerived(Base):\n z: int\n\n self.assertNotIn('__slots__', AnotherDerived.__dict__)\n\n def test_cant_inherit_from_iterator_slots(self):\n\n class Root:\n __slots__ = iter(['a'])\n\n class Root2(Root):\n __slots__ = ('b', )\n\n with self.assertRaisesRegex(\n TypeError,\n \"^Slots of 'Root' cannot be determined\"\n ):\n @dataclass(slots=True)\n class C(Root2):\n x: int\n\n def test_returns_new_class(self):\n class A:\n x: int\n\n B = dataclass(A, slots=True)\n self.assertIsNot(A, B)\n\n self.assertFalse(hasattr(A, \"__slots__\"))\n self.assertTrue(hasattr(B, \"__slots__\"))\n\n # Can't be local to test_frozen_pickle.\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsClass:\n foo: str\n bar: int\n\n @dataclass(frozen=True)\n class FrozenWithoutSlotsClass:\n foo: str\n bar: int\n\n def test_frozen_pickle(self):\n # bpo-43999\n\n self.assertEqual(self.FrozenSlotsClass.__slots__, (\"foo\", \"bar\"))\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n obj = self.FrozenWithoutSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsGetStateClass:\n foo: str\n bar: int\n\n getstate_called: bool = field(default=False, compare=False)\n\n def __getstate__(self):\n object.__setattr__(self, 'getstate_called', True)\n return [self.foo, self.bar]\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsSetStateClass:\n foo: str\n bar: int\n\n setstate_called: bool = field(default=False, compare=False)\n\n def __setstate__(self, state):\n object.__setattr__(self, 'setstate_called', True)\n object.__setattr__(self, 'foo', state[0])\n object.__setattr__(self, 'bar', state[1])\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsAllStateClass:\n foo: str\n bar: int\n\n getstate_called: bool = field(default=False, compare=False)\n setstate_called: bool = field(default=False, compare=False)\n\n def __getstate__(self):\n object.__setattr__(self, 'getstate_called', True)\n return [self.foo, self.bar]\n\n def __setstate__(self, state):\n object.__setattr__(self, 'setstate_called', True)\n object.__setattr__(self, 'foo', state[0])\n object.__setattr__(self, 'bar', state[1])\n\n def test_frozen_slots_pickle_custom_state(self):\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsGetStateClass('a', 1)\n dumped = pickle.dumps(obj, protocol=proto)\n\n self.assertTrue(obj.getstate_called)\n self.assertEqual(obj, pickle.loads(dumped))\n\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsSetStateClass('a', 1)\n obj2 = pickle.loads(pickle.dumps(obj, protocol=proto))\n\n self.assertTrue(obj2.setstate_called)\n self.assertEqual(obj, obj2)\n\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsAllStateClass('a', 1)\n dumped = pickle.dumps(obj, protocol=proto)\n\n self.assertTrue(obj.getstate_called)\n\n obj2 = pickle.loads(dumped)\n self.assertTrue(obj2.setstate_called)\n self.assertEqual(obj, obj2)\n\n def test_slots_with_default_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default='b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_with_default_factory_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default_factory=lambda:'b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_no_weakref(self):\n @dataclass(slots=True)\n class A:\n # No weakref.\n pass\n\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A()\n with self.assertRaisesRegex(TypeError,\n \"cannot create weak reference\"):\n weakref.ref(a)\n with self.assertRaises(AttributeError):\n a.__weakref__\n\n def test_slots_weakref(self):\n @dataclass(slots=True, weakref_slot=True)\n class A:\n a: int\n\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n\n self.assertIs(a.__weakref__, a_ref)\n\n def test_slots_weakref_base_str(self):\n class Base:\n __slots__ = '__weakref__'\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_slots_weakref_base_tuple(self):\n # Same as test_slots_weakref_base, but use a tuple instead of a string\n # in the base class.\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still\n # weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_weakref_slot_without_slot(self):\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n @dataclass(weakref_slot=True)\n class A:\n a: int\n\n def test_weakref_slot_make_dataclass(self):\n A = make_dataclass('A', [('a', int),], slots=True, weakref_slot=True)\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n # And make sure if raises if slots=True is not given.\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n B = make_dataclass('B', [('a', int),], weakref_slot=True)\n\n def test_weakref_slot_subclass_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n # A *can* also specify weakref_slot=True if it wants to (gh-93521)\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. But an instance of A\n # is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_weakref_slot_subclass_no_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n @dataclass(slots=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. Even though A doesn't\n # specify weakref_slot, it should still be weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_weakref_slot_normal_base_weakref_slot(self):\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n field: int\n\n # __weakref__ is in the base class, not A. But an instance of\n # A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestSlots","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_26.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestDescriptors(unittest.TestCase):\n def test_set_name(self):\n # See bpo-33141.\n\n # Create a descriptor.\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n def __get__(self, instance, owner):\n if instance is not None:\n return 1\n return self\n\n # This is the case of just normal descriptor behavior, no\n # dataclass code is involved in initializing the descriptor.\n @dataclass\n class C:\n c: int=D()\n self.assertEqual(C.c.name, 'cx')\n\n # Now test with a default value and init=False, which is the\n # only time this is really meaningful. If not using\n # init=False, then the descriptor will be overwritten, anyway.\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n self.assertEqual(C().c, 1)\n\n def test_non_descriptor(self):\n # PEP 487 says __set_name__ should work on non-descriptors.\n # Create a descriptor.\n\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n\n def test_lookup_on_instance(self):\n # See bpo-33175.\n class D:\n pass\n\n d = D()\n # Create an attribute on the instance, not type.\n d.__set_name__ = Mock()\n\n # Make sure d.__set_name__ is not called.\n @dataclass\n class C:\n i: int=field(default=d, init=False)\n\n self.assertEqual(d.__set_name__.call_count, 0)\n\n def test_lookup_on_class(self):\n # See bpo-33175.\n class D:\n pass\n D.__set_name__ = Mock()\n\n # Make sure D.__set_name__ is called.\n @dataclass\n class C:\n i: int=field(default=D(), init=False)\n\n self.assertEqual(D.__set_name__.call_count, 1)\n\n def test_init_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_getting_field_calls_get(self):\n class D:\n pass\n\n D.__set__ = Mock()\n D.__get__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__get__ is called.\n D.__get__.reset_mock()\n value = c.i\n self.assertEqual(D.__get__.call_count, 1)\n\n def test_setting_field_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c.i = 10\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_setting_uninitialized_descriptor_field(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D\n\n # D.__set__ is not called because there's no D instance to call it on\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 0)\n\n # D.__set__ still isn't called after setting i to an instance of D\n # because descriptors don't behave like that when stored as instance vars\n c.i = D()\n c.i = 5\n self.assertEqual(D.__set__.call_count, 0)\n\n def test_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n return 100\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n c = C()\n self.assertEqual(c.i, 100)\n\n c = C(5)\n self.assertEqual(c.i, 5)\n\n def test_no_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n raise AttributeError()\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):\n c = C()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestDescriptors","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_27.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestMakeDataclass(unittest.TestCase):\n def test_simple(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace={'add_one': lambda self: self.x + 1})\n c = C(10)\n self.assertEqual((c.x, c.y), (10, 5))\n self.assertEqual(c.add_one(), 11)\n\n\n def test_no_mutate_namespace(self):\n # Make sure a provided namespace isn't mutated.\n ns = {}\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace=ns)\n self.assertEqual(ns, {})\n\n def test_base(self):\n class Base1:\n pass\n class Base2:\n pass\n C = make_dataclass('C',\n [('x', int)],\n bases=(Base1, Base2))\n c = C(2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n def test_base_dataclass(self):\n @dataclass\n class Base1:\n x: int\n class Base2:\n pass\n C = make_dataclass('C',\n [('y', int)],\n bases=(Base1, Base2))\n with self.assertRaisesRegex(TypeError, 'required positional'):\n c = C(2)\n c = C(1, 2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n self.assertEqual((c.x, c.y), (1, 2))\n\n def test_init_var(self):\n def post_init(self, y):\n self.x *= y\n\n C = make_dataclass('C',\n [('x', int),\n ('y', InitVar[int]),\n ],\n namespace={'__post_init__': post_init},\n )\n c = C(2, 3)\n self.assertEqual(vars(c), {'x': 6})\n self.assertEqual(len(fields(c)), 1)\n\n def test_class_var(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ])\n c = C(1)\n self.assertEqual(vars(c), {'x': 1})\n self.assertEqual(len(fields(c)), 1)\n self.assertEqual(C.y, 10)\n self.assertEqual(C.z, 20)\n\n def test_other_params(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ],\n init=False)\n # Make sure we have a repr, but no init.\n self.assertNotIn('__init__', vars(C))\n self.assertIn('__repr__', vars(C))\n\n # Make sure random other params don't work.\n with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):\n C = make_dataclass('C',\n [],\n xxinit=False)\n\n def test_no_types(self):\n C = make_dataclass('Point', ['x', 'y', 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': 'typing.Any',\n 'z': 'typing.Any'})\n\n C = make_dataclass('Point', ['x', ('y', int), 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': int,\n 'z': 'typing.Any'})\n\n def test_module_attr(self):\n self.assertEqual(ByMakeDataClass.__module__, __name__)\n self.assertEqual(ByMakeDataClass(1).__module__, __name__)\n self.assertEqual(WrongModuleMakeDataclass.__module__, \"custom\")\n Nested = make_dataclass('Nested', [])\n self.assertEqual(Nested.__module__, __name__)\n self.assertEqual(Nested().__module__, __name__)\n\n def test_pickle_support(self):\n for klass in [ByMakeDataClass, ManualModuleMakeDataClass]:\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n self.assertEqual(\n pickle.loads(pickle.dumps(klass, proto)),\n klass,\n )\n self.assertEqual(\n pickle.loads(pickle.dumps(klass(1), proto)),\n klass(1),\n )\n\n def test_cannot_be_pickled(self):\n for klass in [WrongNameMakeDataclass, WrongModuleMakeDataclass]:\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n with self.assertRaises(pickle.PickleError):\n pickle.dumps(klass, proto)\n with self.assertRaises(pickle.PickleError):\n pickle.dumps(klass(1), proto)\n\n def test_invalid_type_specification(self):\n for bad_field in [(),\n (1, 2, 3, 4),\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'Invalid field: '):\n make_dataclass('C', ['a', bad_field])\n\n # And test for things with no len().\n for bad_field in [float,\n lambda x:x,\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'has no len\\(\\)'):\n make_dataclass('C', ['a', bad_field])\n\n def test_duplicate_field_names(self):\n for field in ['a', 'ab']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'Field name duplicated'):\n make_dataclass('C', [field, 'a', field])\n\n def test_keyword_field_names(self):\n for field in ['for', 'async', 'await', 'as']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field, 'a'])\n\n def test_non_identifier_field_names(self):\n for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field, 'a'])\n\n def test_underscore_field_names(self):\n # Unlike namedtuple, it's okay if dataclass field names have\n # an underscore.\n make_dataclass('C', ['_', '_a', 'a_a', 'a_'])\n\n def test_funny_class_names_names(self):\n # No reason to prevent weird class names, since\n # types.new_class allows them.\n for classname in ['()', 'x,y', '*', '2@3', '']:\n with self.subTest(classname=classname):\n C = make_dataclass(classname, ['a', 'b'])\n self.assertEqual(C.__name__, classname)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestMakeDataclass","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_28.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestReplace(unittest.TestCase):\n def test(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n z: int = field(init=False, default=10)\n t: int = field(init=False, default=100)\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))\n self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))\n\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=3, z=20, t=50)\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, z=20)\n replace(c, x=3, z=20, t=50)\n\n # Make sure the result is still frozen.\n with self.assertRaisesRegex(FrozenInstanceError, \"cannot assign to field 'x'\"):\n c1.x = 3\n\n # Make sure we can't replace an attribute that doesn't exist,\n # if we're also replacing one that does exist. Test this\n # here, because setting attributes on frozen instances is\n # handled slightly differently from non-frozen ones.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'a'\"):\n c1 = replace(c, x=20, a=5)\n\n def test_invalid_field_name(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'z'\"):\n c1 = replace(c, z=3)\n\n def test_invalid_object(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(C, x=3)\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(0, x=3)\n\n def test_no_init(self):\n @dataclass\n class C:\n x: int\n y: int = field(init=False, default=10)\n\n c = C(1)\n c.y = 20\n\n # Make sure y gets the default value.\n c1 = replace(c, x=5)\n self.assertEqual((c1.x, c1.y), (5, 10))\n\n # Trying to replace y is an error.\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, x=2, y=30)\n\n with self.assertRaisesRegex(ValueError, 'init=False'):\n replace(c, y=30)\n\n def test_classvar(self):\n @dataclass\n class C:\n x: int\n y: ClassVar[int] = 1000\n\n c = C(1)\n d = C(2)\n\n self.assertIs(c.y, d.y)\n self.assertEqual(c.y, 1000)\n\n # Trying to replace y is an error: can't replace ClassVars.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an \"\n \"unexpected keyword argument 'y'\"):\n replace(c, y=30)\n\n replace(c, x=5)\n\n def test_initvar_is_specified(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int]\n\n def __post_init__(self, y):\n self.x *= y\n\n c = C(1, 10)\n self.assertEqual(c.x, 10)\n with self.assertRaisesRegex(ValueError, r\"InitVar 'y' must be \"\n \"specified with replace()\"):\n replace(c, x=3)\n c = replace(c, x=3, y=5)\n self.assertEqual(c.x, 15)\n\n def test_initvar_with_default_value(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int] = None\n z: InitVar[int] = 42\n\n def __post_init__(self, y, z):\n if y is not None:\n self.x += y\n if z is not None:\n self.x += z\n\n c = C(x=1, y=10, z=1)\n self.assertEqual(replace(c), C(x=12))\n self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42))\n self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1))\n\n def test_recursive_repr(self):\n @dataclass\n class C:\n f: \"C\"\n\n c = C(None)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr..C(f=...)\")\n\n def test_recursive_repr_two_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: \"C\"\n\n c = C(None, None)\n c.f = c\n c.g = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_two_attrs\"\n \"..C(f=..., g=...)\")\n\n def test_recursive_repr_indirection(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n c.f = d\n d.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection\"\n \"..C(f=TestReplace.test_recursive_repr_indirection\"\n \"..D(f=...))\")\n\n def test_recursive_repr_indirection_two(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"E\"\n\n @dataclass\n class E:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n e = E(None)\n c.f = d\n d.f = e\n e.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection_two\"\n \"..C(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..D(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..E(f=...)))\")\n\n def test_recursive_repr_misc_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: int\n\n c = C(None, 1)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_misc_attrs\"\n \"..C(f=..., g=1)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestReplace","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_29.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestAbstract(unittest.TestCase):\n def test_abc_implementation(self):\n class Ordered(abc.ABC):\n @abc.abstractmethod\n def __lt__(self, other):\n pass\n\n @abc.abstractmethod\n def __le__(self, other):\n pass\n\n @dataclass(order=True)\n class Date(Ordered):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertFalse(inspect.isabstract(Date))\n self.assertGreater(Date(2020,12,25), Date(2020,8,31))\n\n def test_maintain_abc(self):\n class A(abc.ABC):\n @abc.abstractmethod\n def foo(self):\n pass\n\n @dataclass\n class Date(A):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertTrue(inspect.isabstract(Date))\n msg = \"class Date without an implementation for abstract method 'foo'\"\n self.assertRaisesRegex(TypeError, msg, Date)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestAbstract","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_30.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestMatchArgs(unittest.TestCase):\n def test_match_args(self):\n @dataclass\n class C:\n a: int\n self.assertEqual(C(42).__match_args__, ('a',))\n\n def test_explicit_match_args(self):\n ma = ()\n @dataclass\n class C:\n a: int\n __match_args__ = ma\n self.assertIs(C(42).__match_args__, ma)\n\n def test_bpo_43764(self):\n @dataclass(repr=False, eq=False, init=False)\n class X:\n a: int\n b: int\n c: int\n self.assertEqual(X.__match_args__, (\"a\", \"b\", \"c\"))\n\n def test_match_args_argument(self):\n @dataclass(match_args=False)\n class X:\n a: int\n self.assertNotIn('__match_args__', X.__dict__)\n\n @dataclass(match_args=False)\n class Y:\n a: int\n __match_args__ = ('b',)\n self.assertEqual(Y.__match_args__, ('b',))\n\n @dataclass(match_args=False)\n class Z(Y):\n z: int\n self.assertEqual(Z.__match_args__, ('b',))\n\n # Ensure parent dataclass __match_args__ is seen, if child class\n # specifies match_args=False.\n @dataclass\n class A:\n a: int\n z: int\n @dataclass(match_args=False)\n class B(A):\n b: int\n self.assertEqual(B.__match_args__, ('a', 'z'))\n\n def test_make_dataclasses(self):\n C = make_dataclass('C', [('x', int), ('y', int)])\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=True)\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=False)\n self.assertNotIn('__match__args__', C.__dict__)\n\n C = make_dataclass('C', [('x', int), ('y', int)], namespace={'__match_args__': ('z',)})\n self.assertEqual(C.__match_args__, ('z',))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestMatchArgs","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_31.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom functools import total_ordering\nimport typing\nimport dataclasses\n\n\nclass TestKeywordArgs(unittest.TestCase):\n def test_no_classvar_kwarg(self):\n msg = 'field a is a ClassVar but specifies kw_only'\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=True)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass(kw_only=True)\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n def test_field_marked_as_kwonly(self):\n #######################\n # Using dataclass(kw_only=True)\n @dataclass(kw_only=True)\n class A:\n a: int\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Using dataclass(kw_only=False)\n @dataclass(kw_only=False)\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Not specifying dataclass(kw_only)\n @dataclass\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n def test_match_args(self):\n # kw fields don't show up in __match_args__.\n @dataclass(kw_only=True)\n class C:\n a: int\n self.assertEqual(C(a=42).__match_args__, ())\n\n @dataclass\n class C:\n a: int\n b: int = field(kw_only=True)\n self.assertEqual(C(42, b=10).__match_args__, ('a',))\n\n def test_KW_ONLY(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n\n @dataclass(kw_only=True)\n class B:\n a: int\n _: KW_ONLY\n b: int\n c: int\n B(a=3, b=4, c=5)\n msg = \"takes 1 positional argument but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n B(3, 4, 5)\n\n # Explicitly make a field that follows KW_ONLY be non-keyword-only.\n @dataclass\n class C:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=False)\n c = C(1, 2, b=3)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(c=2, b=3, a=1)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n\n def test_KW_ONLY_as_string(self):\n @dataclass\n class A:\n a: int\n _: 'dataclasses.KW_ONLY'\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n def test_KW_ONLY_twice(self):\n msg = \"'Y' is KW_ONLY, but KW_ONLY has already been specified\"\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n Y: KW_ONLY\n b: int\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n Y: KW_ONLY\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n c: int\n Y: KW_ONLY\n\n # But this usage is okay, since it's not using KW_ONLY.\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=True)\n\n # And if inheriting, it's okay.\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n _: KW_ONLY\n d: int\n\n # Make sure the error is raised in a derived class.\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n X: KW_ONLY\n d: int\n Y: KW_ONLY\n\n\n def test_post_init(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n raise CustomError(f'{b=} {d=}')\n with self.assertRaisesRegex(CustomError, 'b=3 d=4'):\n A(1, c=2, b=3, d=4)\n\n @dataclass\n class B:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n self.a = b\n self.c = d\n b = B(1, c=2, b=3, d=4)\n self.assertEqual(asdict(b), {'a': 3, 'c': 4})\n\n def test_defaults(self):\n # For kwargs, make sure we can have defaults after non-defaults.\n @dataclass\n class A:\n a: int = 0\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n a = A(d=4, b=3)\n self.assertEqual(a.a, 0)\n self.assertEqual(a.b, 3)\n self.assertEqual(a.c, 1)\n self.assertEqual(a.d, 4)\n\n # Make sure we still check for non-kwarg non-defaults not following\n # defaults.\n err_regex = \"non-default argument 'z' follows default argument\"\n with self.assertRaisesRegex(TypeError, err_regex):\n @dataclass\n class A:\n a: int = 0\n z: int\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n def test_make_dataclass(self):\n A = make_dataclass(\"A\", ['a'], kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n B = make_dataclass(\"B\",\n ['a', ('b', int, field(kw_only=False))],\n kw_only=True)\n self.assertTrue(fields(B)[0].kw_only)\n self.assertFalse(fields(B)[1].kw_only)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses.py::TestKeywordArgs","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"dict-union","pep":"584","introduced_in":"3.9","form":"modern","file":"dict-union/modern_01.py","code":"import collections\nimport collections.abc\nimport gc\nimport pickle\nimport random\nimport string\nimport sys\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import import_helper, C_RECURSION_LIMIT\nfrom test import mapping_tests\n\n\ndef test_merge_operator(self):\n\n a = {0: 0, 1: 1, 2: 1}\n b = {1: 1, 2: 2, 3: 3}\n\n c = a.copy()\n c |= b\n\n self.assertEqual(a | b, {0: 0, 1: 1, 2: 2, 3: 3})\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n c = b.copy()\n c |= a\n\n self.assertEqual(b | a, {1: 1, 2: 1, 3: 3, 0: 0})\n self.assertEqual(c, {1: 1, 2: 1, 3: 3, 0: 0})\n\n c = a.copy()\n c |= [(1, 1), (2, 2), (3, 3)]\n\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n self.assertIs(a.__or__(None), NotImplemented)\n self.assertIs(a.__or__(()), NotImplemented)\n self.assertIs(a.__or__(\"BAD\"), NotImplemented)\n self.assertIs(a.__or__(\"\"), NotImplemented)\n\n self.assertRaises(TypeError, a.__ior__, None)\n self.assertEqual(a.__ior__(()), {0: 0, 1: 1, 2: 1})\n self.assertRaises(ValueError, a.__ior__, \"BAD\")\n self.assertEqual(a.__ior__(\"\"), {0: 0, 1: 1, 2: 1})\n","source":"cpython_tests","origin":"Lib/test/test_dict.py::DictTest.test_merge_operator","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"exception-notes","pep":"678","introduced_in":"3.11","form":"modern","file":"exception-notes/modern_01.py","code":"import copy\nimport os\nimport sys\nimport unittest\nimport pickle\nimport weakref\nimport errno\nfrom textwrap import dedent\nfrom test.support import (captured_stderr, check_impl_detail,\n cpython_only, gc_collect,\n no_tracing, script_helper,\n SuppressCrashReport)\nfrom test.support.import_helper import import_module\nfrom test.support.os_helper import TESTFN, unlink\nfrom test.support.warnings_helper import check_warnings\nfrom test import support\n\n\ndef test_notes(self):\n for e in [BaseException(1), Exception(2), ValueError(3)]:\n with self.subTest(e=e):\n self.assertFalse(hasattr(e, '__notes__'))\n e.add_note(\"My Note\")\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n with self.assertRaises(TypeError):\n e.add_note(42)\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n e.add_note(\"Your Note\")\n self.assertEqual(e.__notes__, [\"My Note\", \"Your Note\"])\n\n del e.__notes__\n self.assertFalse(hasattr(e, '__notes__'))\n\n e.add_note(\"Our Note\")\n self.assertEqual(e.__notes__, [\"Our Note\"])\n\n e.__notes__ = 42\n self.assertEqual(e.__notes__, 42)\n\n with self.assertRaises(TypeError):\n e.add_note(\"will not work\")\n self.assertEqual(e.__notes__, 42)\n","source":"cpython_tests","origin":"Lib/test/test_exceptions.py::ExceptionTests.test_notes","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"numeric-underscores","pep":"515","introduced_in":"3.6","form":"modern","file":"numeric-underscores/modern_01.py","code":"import sys\nimport time\nimport unittest\nfrom unittest import mock\nfrom test import support\nfrom test.test_grammar import (VALID_UNDERSCORE_LITERALS,\n INVALID_UNDERSCORE_LITERALS)\n\n\nclass IntStrDigitLimitsTests(unittest.TestCase):\n\n int_class = int # Override this in subclasses to reuse the suite.\n\n def setUp(self):\n super().setUp()\n self._previous_limit = sys.get_int_max_str_digits()\n sys.set_int_max_str_digits(2048)\n\n def tearDown(self):\n sys.set_int_max_str_digits(self._previous_limit)\n super().tearDown()\n\n def test_disabled_limit(self):\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n self.assertLess(sys.get_int_max_str_digits(), 20_000)\n with support.adjust_int_max_str_digits(0):\n self.assertEqual(sys.get_int_max_str_digits(), 0)\n i = self.int_class('1' * 20_000)\n str(i)\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n\n def test_max_str_digits_edge_cases(self):\n \"\"\"Ignore the +/- sign and space padding.\"\"\"\n int_class = self.int_class\n maxdigits = sys.get_int_max_str_digits()\n\n int_class('1' * maxdigits)\n int_class(' ' + '1' * maxdigits)\n int_class('1' * maxdigits + ' ')\n int_class('+' + '1' * maxdigits)\n int_class('-' + '1' * maxdigits)\n self.assertEqual(len(str(10 ** (maxdigits - 1))), maxdigits)\n\n def check(self, i, base=None):\n with self.assertRaises(ValueError):\n if base is None:\n self.int_class(i)\n else:\n self.int_class(i, base)\n\n def test_max_str_digits(self):\n maxdigits = sys.get_int_max_str_digits()\n\n self.check('1' * (maxdigits + 1))\n self.check(' ' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1) + ' ')\n self.check('+' + '1' * (maxdigits + 1))\n self.check('-' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1))\n\n i = 10 ** maxdigits\n with self.assertRaises(ValueError):\n str(i)\n\n def test_denial_of_service_prevented_int_to_str(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 50_000, maxdigits # A test prerequisite.\n get_time = time.process_time\n if get_time() <= 0: # some platforms like WASM lack process_time()\n get_time = time.monotonic\n\n huge_int = int(f'0x{\"c\"*65_000}', base=16) # 78268 decimal digits.\n digits = 78_268\n with support.adjust_int_max_str_digits(digits):\n start = get_time()\n huge_decimal = str(huge_int)\n seconds_to_convert = get_time() - start\n self.assertEqual(len(huge_decimal), digits)\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if seconds_to_convert < 1/64:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{seconds_to_convert} seconds.')\n\n # We test with the limit almost at the size needed to check performance.\n # The performant limit check is slightly fuzzy, give it a some room.\n with support.adjust_int_max_str_digits(int(.995 * digits)):\n with self.assertRaises(ValueError) as err:\n start = get_time()\n str(huge_int)\n seconds_to_fail_huge = get_time() - start\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(seconds_to_fail_huge, seconds_to_convert/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge_int = int(f'0x{\"c\"*500_000}', base=16) # 602060 digits.\n with self.assertRaises(ValueError) as err:\n start = get_time()\n # If not limited, 8 seconds said Zen based cloud VM.\n str(extra_huge_int)\n seconds_to_fail_extra_huge = get_time() - start\n self.assertIn('conversion', str(err.exception))\n self.assertLess(seconds_to_fail_extra_huge, seconds_to_convert/2)\n\n def test_denial_of_service_prevented_str_to_int(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 100_000, maxdigits # A test prerequisite.\n get_time = time.process_time\n if get_time() <= 0: # some platforms like WASM lack process_time()\n get_time = time.monotonic\n\n digits = 133700\n huge = '8'*digits\n with support.adjust_int_max_str_digits(digits):\n start = get_time()\n int(huge)\n seconds_to_convert = get_time() - start\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if seconds_to_convert < 1/64:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{seconds_to_convert} seconds.')\n\n with support.adjust_int_max_str_digits(digits - 1):\n with self.assertRaises(ValueError) as err:\n start = get_time()\n int(huge)\n seconds_to_fail_huge = get_time() - start\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(seconds_to_fail_huge, seconds_to_convert/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge = '7'*1_200_000\n with self.assertRaises(ValueError) as err:\n start = get_time()\n # If not limited, 8 seconds in the Zen based cloud VM.\n int(extra_huge)\n seconds_to_fail_extra_huge = get_time() - start\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(seconds_to_fail_extra_huge, seconds_to_convert/2)\n\n def test_power_of_two_bases_unlimited(self):\n \"\"\"The limit does not apply to power of 2 bases.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n\n for base in (2, 4, 8, 16, 32):\n with self.subTest(base=base):\n self.int_class('1' * (maxdigits + 1), base)\n assert maxdigits < 100_000\n self.int_class('1' * 100_000, base)\n\n def test_underscores_ignored(self):\n maxdigits = sys.get_int_max_str_digits()\n\n triples = maxdigits // 3\n s = '111' * triples\n s_ = '1_11' * triples\n self.int_class(s) # succeeds\n self.int_class(s_) # succeeds\n self.check(f'{s}111')\n self.check(f'{s_}_111')\n\n def test_sign_not_counted(self):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '5' * max_digits\n i = int_class(s)\n pos_i = int_class(f'+{s}')\n assert i == pos_i\n neg_i = int_class(f'-{s}')\n assert -pos_i == neg_i\n str(pos_i)\n str(neg_i)\n\n def _other_base_helper(self, base):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '2' * max_digits\n i = int_class(s, base)\n if base > 10:\n with self.assertRaises(ValueError):\n str(i)\n elif base < 10:\n str(i)\n with self.assertRaises(ValueError) as err:\n int_class(f'{s}1', base)\n\n def test_int_from_other_bases(self):\n base = 3\n with self.subTest(base=base):\n self._other_base_helper(base)\n base = 36\n with self.subTest(base=base):\n self._other_base_helper(base)\n\n def test_int_max_str_digits_is_per_interpreter(self):\n # Changing the limit in one interpreter does not change others.\n code = \"\"\"if 1:\n # Subinterpreters maintain and enforce their own limit\n import sys\n sys.set_int_max_str_digits(2323)\n try:\n int('3'*3333)\n except ValueError:\n pass\n else:\n raise AssertionError('Expected a int max str digits ValueError.')\n \"\"\"\n with support.adjust_int_max_str_digits(4000):\n before_value = sys.get_int_max_str_digits()\n self.assertEqual(support.run_in_subinterp(code), 0,\n 'subinterp code failure, check stderr.')\n after_value = sys.get_int_max_str_digits()\n self.assertEqual(before_value, after_value)\n","source":"cpython_tests","origin":"Lib/test/test_int.py::IntStrDigitLimitsTests","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"numeric-underscores","pep":"515","introduced_in":"3.6","form":"modern","file":"numeric-underscores/modern_02.py","code":"import sys\nimport time\nimport unittest\nfrom unittest import mock\nfrom test import support\nfrom test.test_grammar import (VALID_UNDERSCORE_LITERALS,\n INVALID_UNDERSCORE_LITERALS)\n\n\nclass PyLongModuleTests(unittest.TestCase):\n # Tests of the functions in _pylong.py. Those get used when the\n # number of digits in the input values are large enough.\n\n def setUp(self):\n super().setUp()\n self._previous_limit = sys.get_int_max_str_digits()\n sys.set_int_max_str_digits(0)\n\n def tearDown(self):\n sys.set_int_max_str_digits(self._previous_limit)\n super().tearDown()\n\n def test_pylong_int_to_decimal(self):\n n = (1 << 100_000) - 1\n suffix = '9883109375'\n s = str(n)\n assert s[-10:] == suffix\n s = str(-n)\n assert s[-10:] == suffix\n s = '%d' % n\n assert s[-10:] == suffix\n s = b'%d' % n\n assert s[-10:] == suffix.encode('ascii')\n\n def test_pylong_int_divmod(self):\n n = (1 << 100_000)\n a, b = divmod(n*3 + 1, n)\n assert a == 3 and b == 1\n\n def test_pylong_str_to_int(self):\n v1 = 1 << 100_000\n s = str(v1)\n v2 = int(s)\n assert v1 == v2\n v3 = int(' -' + s)\n assert -v1 == v3\n v4 = int(' +' + s + ' ')\n assert v1 == v4\n with self.assertRaises(ValueError) as err:\n int(s + 'z')\n with self.assertRaises(ValueError) as err:\n int(s + '_')\n with self.assertRaises(ValueError) as err:\n int('_' + s)\n\n @support.cpython_only # tests implementation details of CPython.\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @mock.patch.object(_pylong, \"int_to_decimal_string\")\n def test_pylong_misbehavior_error_path_to_str(\n self, mock_int_to_str):\n with support.adjust_int_max_str_digits(20_000):\n big_value = int('7'*19_999)\n mock_int_to_str.return_value = None # not a str\n with self.assertRaises(TypeError) as ctx:\n str(big_value)\n self.assertIn('_pylong.int_to_decimal_string did not',\n str(ctx.exception))\n mock_int_to_str.side_effect = RuntimeError(\"testABC\")\n with self.assertRaises(RuntimeError):\n str(big_value)\n\n @support.cpython_only # tests implementation details of CPython.\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @mock.patch.object(_pylong, \"int_from_string\")\n def test_pylong_misbehavior_error_path_from_str(\n self, mock_int_from_str):\n big_value = '7'*19_999\n with support.adjust_int_max_str_digits(20_000):\n mock_int_from_str.return_value = b'not an int'\n with self.assertRaises(TypeError) as ctx:\n int(big_value)\n self.assertIn('_pylong.int_from_string did not',\n str(ctx.exception))\n\n mock_int_from_str.side_effect = RuntimeError(\"test123\")\n with self.assertRaises(RuntimeError):\n int(big_value)\n","source":"cpython_tests","origin":"Lib/test/test_int.py::PyLongModuleTests","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"tarfile-filter","pep":"706","introduced_in":"3.12","form":"modern","file":"tarfile-filter/modern_01.py","code":"import sys\nimport os\nimport io\nfrom hashlib import sha256\nfrom contextlib import contextmanager, ExitStack\nfrom random import Random\nimport pathlib\nimport shutil\nimport re\nimport warnings\nimport stat\nimport unittest\nimport unittest.mock\nimport tarfile\nfrom test import support\nfrom test.support import os_helper\nfrom test.support import script_helper\nfrom test.support import warnings_helper\n\n\nclass TestExtractionFilters(unittest.TestCase):\n\n # A temporary directory for the extraction results.\n # All files that \"escape\" the destination path should still end\n # up in this directory.\n outerdir = pathlib.Path(TEMPDIR) / 'outerdir'\n\n # The destination for the extraction, within `outerdir`\n destdir = outerdir / 'dest'\n\n @contextmanager\n def check_context(self, tar, filter):\n \"\"\"Extracts `tar` to `self.destdir` and allows checking the result\n\n If an error occurs, it must be checked using `expect_exception`\n\n Otherwise, all resulting files must be checked using `expect_file`,\n except the destination directory itself and parent directories of\n other files.\n When checking directories, do so before their contents.\n \"\"\"\n with os_helper.temp_dir(self.outerdir):\n try:\n tar.extractall(self.destdir, filter=filter)\n except Exception as exc:\n self.raised_exception = exc\n self.expected_paths = set()\n else:\n self.raised_exception = None\n self.expected_paths = set(self.outerdir.glob('**/*'))\n self.expected_paths.discard(self.destdir)\n try:\n yield\n finally:\n tar.close()\n if self.raised_exception:\n raise self.raised_exception\n self.assertEqual(self.expected_paths, set())\n\n def expect_file(self, name, type=None, symlink_to=None, mode=None,\n size=None):\n \"\"\"Check a single file. See check_context.\"\"\"\n if self.raised_exception:\n raise self.raised_exception\n # use normpath() rather than resolve() so we don't follow symlinks\n path = pathlib.Path(os.path.normpath(self.destdir / name))\n self.assertIn(path, self.expected_paths)\n self.expected_paths.remove(path)\n if mode is not None and os_helper.can_chmod():\n got = stat.filemode(stat.S_IMODE(path.stat().st_mode))\n self.assertEqual(got, mode)\n if type is None and isinstance(name, str) and name.endswith('/'):\n type = tarfile.DIRTYPE\n if symlink_to is not None:\n got = (self.destdir / name).readlink()\n expected = pathlib.Path(symlink_to)\n # The symlink might be the same (textually) as what we expect,\n # but some systems change the link to an equivalent path, so\n # we fall back to samefile().\n if expected != got:\n self.assertTrue(got.samefile(expected))\n elif type == tarfile.REGTYPE or type is None:\n self.assertTrue(path.is_file())\n elif type == tarfile.DIRTYPE:\n self.assertTrue(path.is_dir())\n elif type == tarfile.FIFOTYPE:\n self.assertTrue(path.is_fifo())\n else:\n raise NotImplementedError(type)\n if size is not None:\n self.assertEqual(path.stat().st_size, size)\n for parent in path.parents:\n self.expected_paths.discard(parent)\n\n def expect_exception(self, exc_type, message_re='.'):\n with self.assertRaisesRegex(exc_type, message_re):\n if self.raised_exception is not None:\n raise self.raised_exception\n self.raised_exception = None\n\n def test_benign_file(self):\n with ArchiveMaker() as arc:\n arc.add('benign.txt')\n for filter in 'fully_trusted', 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_file('benign.txt')\n\n def test_absolute(self):\n # Test handling a member with an absolute path\n # Inspired by 'absolute1' in https://github.com/jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add(self.outerdir / 'escaped.evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('../escaped.evil')\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n if str(self.outerdir).startswith('/'):\n # We strip leading slashes, as e.g. GNU tar does\n # (without --absolute-filenames).\n outerdir_stripped = str(self.outerdir).lstrip('/')\n self.expect_file(f'{outerdir_stripped}/escaped.evil')\n else:\n # On this system, absolute paths don't have leading\n # slashes.\n # So, there's nothing to strip. We refuse to unpack\n # to an absolute path, nonetheless.\n self.expect_exception(\n tarfile.AbsolutePathError,\n \"\"\"['\"].*escaped.evil['\"] has an absolute path\"\"\")\n\n @symlink_test\n def test_parent_symlink(self):\n # Test interplaying symlinks\n # Inspired by 'dirsymlink2a' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n\n # `current` links to `.` which is both:\n # - the destination directory\n # - `current` itself\n arc.add('current', symlink_to='.')\n\n # effectively points to ./../\n arc.add('parent', symlink_to='current/..')\n\n arc.add('parent/evil')\n\n if os_helper.can_symlink():\n with self.check_context(arc.open(), 'fully_trusted'):\n if self.raised_exception is not None:\n # Windows will refuse to create a file that's a symlink to itself\n # (and tarfile doesn't swallow that exception)\n self.expect_exception(FileExistsError)\n # The other cases will fail with this error too.\n # Skip the rest of this test.\n return\n else:\n self.expect_file('current', symlink_to='.')\n self.expect_file('parent', symlink_to='current/..')\n self.expect_file('../evil')\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"\"\"'parent/evil' would be extracted to ['\"].*evil['\"], \"\"\"\n + \"which is outside the destination\")\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.LinkOutsideDestinationError,\n \"\"\"'parent' would link to ['\"].*outerdir['\"], \"\"\"\n + \"which is outside the destination\")\n\n else:\n # No symlink support. The symlinks are ignored.\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('parent/evil')\n with self.check_context(arc.open(), 'tar'):\n self.expect_file('parent/evil')\n with self.check_context(arc.open(), 'data'):\n self.expect_file('parent/evil')\n\n @symlink_test\n def test_parent_symlink2(self):\n # Test interplaying symlinks\n # Inspired by 'dirsymlink2b' in jwilk/traversal-archives\n\n # Posix and Windows have different pathname resolution:\n # either symlink or a '..' component resolve first.\n # Let's see which we are on.\n if os_helper.can_symlink():\n testpath = os.path.join(TEMPDIR, 'resolution_test')\n os.mkdir(testpath)\n\n # testpath/current links to `.` which is all of:\n # - `testpath`\n # - `testpath/current`\n # - `testpath/current/current`\n # - etc.\n os.symlink('.', os.path.join(testpath, 'current'))\n\n # we'll test where `testpath/current/../file` ends up\n with open(os.path.join(testpath, 'current', '..', 'file'), 'w'):\n pass\n\n if os.path.exists(os.path.join(testpath, 'file')):\n # Windows collapses 'current\\..' to '.' first, leaving\n # 'testpath\\file'\n dotdot_resolves_early = True\n elif os.path.exists(os.path.join(testpath, '..', 'file')):\n # Posix resolves 'current' to '.' first, leaving\n # 'testpath/../file'\n dotdot_resolves_early = False\n else:\n raise AssertionError('Could not determine link resolution')\n\n with ArchiveMaker() as arc:\n\n # `current` links to `.` which is both the destination directory\n # and `current` itself\n arc.add('current', symlink_to='.')\n\n # `current/parent` is also available as `./parent`,\n # and effectively points to `./../`\n arc.add('current/parent', symlink_to='..')\n\n arc.add('parent/evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n if os_helper.can_symlink():\n self.expect_file('current', symlink_to='.')\n self.expect_file('parent', symlink_to='..')\n self.expect_file('../evil')\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'tar'):\n if os_helper.can_symlink():\n # Fail when extracting a file outside destination\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'data'):\n if os_helper.can_symlink():\n if dotdot_resolves_early:\n # Fail when extracting a file outside destination\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n # Fail as soon as we have a symlink outside the destination\n self.expect_exception(\n tarfile.LinkOutsideDestinationError,\n \"'current/parent' would link to \"\n + \"\"\"['\"].*outerdir['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n @symlink_test\n def test_absolute_symlink(self):\n # Test symlink to an absolute path\n # Inspired by 'dirsymlink' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('parent', symlink_to=self.outerdir)\n arc.add('parent/evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n if os_helper.can_symlink():\n self.expect_file('parent', symlink_to=self.outerdir)\n self.expect_file('../evil')\n else:\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'tar'):\n if os_helper.can_symlink():\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.AbsoluteLinkError,\n \"'parent' is a link to an absolute path\")\n\n def test_absolute_hardlink(self):\n # Test hardlink to an absolute path\n # Inspired by 'dirsymlink' in https://github.com/jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('parent', hardlink_to=self.outerdir / 'foo')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_exception(KeyError, \".*foo. not found\")\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_exception(KeyError, \".*foo. not found\")\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.AbsoluteLinkError,\n \"'parent' is a link to an absolute path\")\n\n @symlink_test\n def test_sly_relative0(self):\n # Inspired by 'relative0' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n # points to `../../tmp/moo`\n arc.add('../moo', symlink_to='..//tmp/moo')\n\n try:\n with self.check_context(arc.open(), filter='fully_trusted'):\n if os_helper.can_symlink():\n if isinstance(self.raised_exception, FileExistsError):\n # XXX TarFile happens to fail creating a parent\n # directory.\n # This might be a bug, but fixing it would hurt\n # security.\n # Note that e.g. GNU `tar` rejects '..' components,\n # so you could argue this is an invalid archive and we\n # just raise an bad type of exception.\n self.expect_exception(FileExistsError)\n else:\n self.expect_file('../moo', symlink_to='..//tmp/moo')\n else:\n # The symlink can't be extracted and is ignored\n pass\n except FileExistsError:\n pass\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'../moo' would be extracted to \"\n + \"'.*moo', which is outside \"\n + \"the destination\")\n\n @symlink_test\n def test_sly_relative2(self):\n # Inspired by 'relative2' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('tmp/')\n arc.add('tmp/../../moo', symlink_to='tmp/../..//tmp/moo')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('tmp', type=tarfile.DIRTYPE)\n if os_helper.can_symlink():\n self.expect_file('../moo', symlink_to='tmp/../../tmp/moo')\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'tmp/../../moo' would be extracted to \"\n + \"\"\"['\"].*moo['\"], which is outside the \"\"\"\n + \"destination\")\n\n @symlink_test\n def test_deep_symlink(self):\n # Test that symlinks and hardlinks inside a directory\n # point to the correct file (`target` of size 3).\n # If links aren't supported we get a copy of the file.\n with ArchiveMaker() as arc:\n arc.add('targetdir/target', size=3)\n # a hardlink's linkname is relative to the archive\n arc.add('linkdir/hardlink', hardlink_to=os.path.join(\n 'targetdir', 'target'))\n # a symlink's linkname is relative to the link's directory\n arc.add('linkdir/symlink', symlink_to=os.path.join(\n '..', 'targetdir', 'target'))\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n self.expect_file('targetdir/target', size=3)\n self.expect_file('linkdir/hardlink', size=3)\n if os_helper.can_symlink():\n self.expect_file('linkdir/symlink', size=3,\n symlink_to='../targetdir/target')\n else:\n self.expect_file('linkdir/symlink', size=3)\n\n @symlink_test\n def test_chains(self):\n # Test chaining of symlinks/hardlinks.\n # Symlinks are created before the files they point to.\n with ArchiveMaker() as arc:\n arc.add('linkdir/symlink', symlink_to='hardlink')\n arc.add('symlink2', symlink_to=os.path.join(\n 'linkdir', 'hardlink2'))\n arc.add('targetdir/target', size=3)\n arc.add('linkdir/hardlink', hardlink_to='targetdir/target')\n arc.add('linkdir/hardlink2', hardlink_to='linkdir/symlink')\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n self.expect_file('targetdir/target', size=3)\n self.expect_file('linkdir/hardlink', size=3)\n self.expect_file('linkdir/hardlink2', size=3)\n if os_helper.can_symlink():\n self.expect_file('linkdir/symlink', size=3,\n symlink_to='hardlink')\n self.expect_file('symlink2', size=3,\n symlink_to='linkdir/hardlink2')\n else:\n self.expect_file('linkdir/symlink', size=3)\n self.expect_file('symlink2', size=3)\n\n def test_modes(self):\n # Test how file modes are extracted\n # (Note that the modes are ignored on platforms without working chmod)\n with ArchiveMaker() as arc:\n arc.add('all_bits', mode='?rwsrwsrwt')\n arc.add('perm_bits', mode='?rwxrwxrwx')\n arc.add('exec_group_other', mode='?rw-rwxrwx')\n arc.add('read_group_only', mode='?---r-----')\n arc.add('no_bits', mode='?---------')\n arc.add('dir/', mode='?---rwsrwt')\n\n # On some systems, setting the sticky bit is a no-op.\n # Check if that's the case.\n tmp_filename = os.path.join(TEMPDIR, \"tmp.file\")\n with open(tmp_filename, 'w'):\n pass\n os.chmod(tmp_filename, os.stat(tmp_filename).st_mode | stat.S_ISVTX)\n have_sticky_files = (os.stat(tmp_filename).st_mode & stat.S_ISVTX)\n os.unlink(tmp_filename)\n\n os.mkdir(tmp_filename)\n os.chmod(tmp_filename, os.stat(tmp_filename).st_mode | stat.S_ISVTX)\n have_sticky_dirs = (os.stat(tmp_filename).st_mode & stat.S_ISVTX)\n os.rmdir(tmp_filename)\n\n with self.check_context(arc.open(), 'fully_trusted'):\n if have_sticky_files:\n self.expect_file('all_bits', mode='?rwsrwsrwt')\n else:\n self.expect_file('all_bits', mode='?rwsrwsrwx')\n self.expect_file('perm_bits', mode='?rwxrwxrwx')\n self.expect_file('exec_group_other', mode='?rw-rwxrwx')\n self.expect_file('read_group_only', mode='?---r-----')\n self.expect_file('no_bits', mode='?---------')\n if have_sticky_dirs:\n self.expect_file('dir/', mode='?---rwsrwt')\n else:\n self.expect_file('dir/', mode='?---rwsrwx')\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_file('all_bits', mode='?rwxr-xr-x')\n self.expect_file('perm_bits', mode='?rwxr-xr-x')\n self.expect_file('exec_group_other', mode='?rw-r-xr-x')\n self.expect_file('read_group_only', mode='?---r-----')\n self.expect_file('no_bits', mode='?---------')\n self.expect_file('dir/', mode='?---r-xr-x')\n\n with self.check_context(arc.open(), 'data'):\n normal_dir_mode = stat.filemode(stat.S_IMODE(\n self.outerdir.stat().st_mode))\n self.expect_file('all_bits', mode='?rwxr-xr-x')\n self.expect_file('perm_bits', mode='?rwxr-xr-x')\n self.expect_file('exec_group_other', mode='?rw-r--r--')\n self.expect_file('read_group_only', mode='?rw-r-----')\n self.expect_file('no_bits', mode='?rw-------')\n self.expect_file('dir/', mode=normal_dir_mode)\n\n def test_pipe(self):\n # Test handling of a special file\n with ArchiveMaker() as arc:\n arc.add('foo', type=tarfile.FIFOTYPE)\n\n for filter in 'fully_trusted', 'tar':\n with self.check_context(arc.open(), filter):\n if hasattr(os, 'mkfifo'):\n self.expect_file('foo', type=tarfile.FIFOTYPE)\n else:\n # The pipe can't be extracted and is skipped.\n pass\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.SpecialFileError,\n \"'foo' is a special file\")\n\n def test_special_files(self):\n # Creating device files is tricky. Instead of attempting that let's\n # only check the filter result.\n for special_type in tarfile.FIFOTYPE, tarfile.CHRTYPE, tarfile.BLKTYPE:\n tarinfo = tarfile.TarInfo('foo')\n tarinfo.type = special_type\n trusted = tarfile.fully_trusted_filter(tarinfo, '')\n self.assertIs(trusted, tarinfo)\n tar = tarfile.tar_filter(tarinfo, '')\n self.assertEqual(tar.type, special_type)\n with self.assertRaises(tarfile.SpecialFileError) as cm:\n tarfile.data_filter(tarinfo, '')\n self.assertIsInstance(cm.exception.tarinfo, tarfile.TarInfo)\n self.assertEqual(cm.exception.tarinfo.name, 'foo')\n\n def test_fully_trusted_filter(self):\n # The 'fully_trusted' filter returns the original TarInfo objects.\n with tarfile.TarFile.open(tarname) as tar:\n for tarinfo in tar.getmembers():\n filtered = tarfile.fully_trusted_filter(tarinfo, '')\n self.assertIs(filtered, tarinfo)\n\n def test_tar_filter(self):\n # The 'tar' filter returns TarInfo objects with the same name/type.\n # (It can also fail for particularly \"evil\" input, but we don't have\n # that in the test archive.)\n with tarfile.TarFile.open(tarname) as tar:\n for tarinfo in tar.getmembers():\n filtered = tarfile.tar_filter(tarinfo, '')\n self.assertIs(filtered.name, tarinfo.name)\n self.assertIs(filtered.type, tarinfo.type)\n\n def test_data_filter(self):\n # The 'data' filter either raises, or returns TarInfo with the same\n # name/type.\n with tarfile.TarFile.open(tarname) as tar:\n for tarinfo in tar.getmembers():\n try:\n filtered = tarfile.data_filter(tarinfo, '')\n except tarfile.FilterError:\n continue\n self.assertIs(filtered.name, tarinfo.name)\n self.assertIs(filtered.type, tarinfo.type)\n\n def test_default_filter_warns(self):\n \"\"\"Ensure the default filter warns\"\"\"\n with ArchiveMaker() as arc:\n arc.add('foo')\n with warnings_helper.check_warnings(\n ('Python 3.14', DeprecationWarning)):\n with self.check_context(arc.open(), None):\n self.expect_file('foo')\n\n def test_change_default_filter_on_instance(self):\n tar = tarfile.TarFile(tarname, 'r')\n def strict_filter(tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n tar.extraction_filter = strict_filter\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_on_class(self):\n def strict_filter(tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n tar = tarfile.TarFile(tarname, 'r')\n with support.swap_attr(tarfile.TarFile, 'extraction_filter',\n staticmethod(strict_filter)):\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_on_subclass(self):\n class TarSubclass(tarfile.TarFile):\n def extraction_filter(self, tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n\n tar = TarSubclass(tarname, 'r')\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_to_string(self):\n tar = tarfile.TarFile(tarname, 'r')\n tar.extraction_filter = 'data'\n with self.check_context(tar, None):\n self.expect_exception(TypeError)\n\n def test_custom_filter(self):\n def custom_filter(tarinfo, path):\n self.assertIs(path, self.destdir)\n if tarinfo.name == 'move_this':\n return tarinfo.replace(name='moved')\n if tarinfo.name == 'ignore_this':\n return None\n return tarinfo\n\n with ArchiveMaker() as arc:\n arc.add('move_this')\n arc.add('ignore_this')\n arc.add('keep')\n with self.check_context(arc.open(), custom_filter):\n self.expect_file('moved')\n self.expect_file('keep')\n\n def test_bad_filter_name(self):\n with ArchiveMaker() as arc:\n arc.add('foo')\n with self.check_context(arc.open(), 'bad filter name'):\n self.expect_exception(ValueError)\n\n def test_stateful_filter(self):\n # Stateful filters should be possible.\n # (This doesn't really test tarfile. Rather, it demonstrates\n # that third parties can implement a stateful filter.)\n class StatefulFilter:\n def __enter__(self):\n self.num_files_processed = 0\n return self\n\n def __call__(self, tarinfo, path):\n try:\n tarinfo = tarfile.data_filter(tarinfo, path)\n except tarfile.FilterError:\n return None\n self.num_files_processed += 1\n return tarinfo\n\n def __exit__(self, *exc_info):\n self.done = True\n\n with ArchiveMaker() as arc:\n arc.add('good')\n arc.add('bad', symlink_to='/')\n arc.add('good')\n with StatefulFilter() as custom_filter:\n with self.check_context(arc.open(), custom_filter):\n self.expect_file('good')\n self.assertEqual(custom_filter.num_files_processed, 2)\n self.assertEqual(custom_filter.done, True)\n\n def test_errorlevel(self):\n def extracterror_filter(tarinfo, path):\n raise tarfile.ExtractError('failed with ExtractError')\n def filtererror_filter(tarinfo, path):\n raise tarfile.FilterError('failed with FilterError')\n def oserror_filter(tarinfo, path):\n raise OSError('failed with OSError')\n def tarerror_filter(tarinfo, path):\n raise tarfile.TarError('failed with base TarError')\n def valueerror_filter(tarinfo, path):\n raise ValueError('failed with ValueError')\n\n with ArchiveMaker() as arc:\n arc.add('file')\n\n # If errorlevel is 0, errors affected by errorlevel are ignored\n\n with self.check_context(arc.open(errorlevel=0), extracterror_filter):\n self.expect_file('file')\n\n with self.check_context(arc.open(errorlevel=0), filtererror_filter):\n self.expect_file('file')\n\n with self.check_context(arc.open(errorlevel=0), oserror_filter):\n self.expect_file('file')\n\n with self.check_context(arc.open(errorlevel=0), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=0), valueerror_filter):\n self.expect_exception(ValueError)\n\n # If 1, all fatal errors are raised\n\n with self.check_context(arc.open(errorlevel=1), extracterror_filter):\n self.expect_file('file')\n\n with self.check_context(arc.open(errorlevel=1), filtererror_filter):\n self.expect_exception(tarfile.FilterError)\n\n with self.check_context(arc.open(errorlevel=1), oserror_filter):\n self.expect_exception(OSError)\n\n with self.check_context(arc.open(errorlevel=1), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=1), valueerror_filter):\n self.expect_exception(ValueError)\n\n # If 2, all non-fatal errors are raised as well.\n\n with self.check_context(arc.open(errorlevel=2), extracterror_filter):\n self.expect_exception(tarfile.ExtractError)\n\n with self.check_context(arc.open(errorlevel=2), filtererror_filter):\n self.expect_exception(tarfile.FilterError)\n\n with self.check_context(arc.open(errorlevel=2), oserror_filter):\n self.expect_exception(OSError)\n\n with self.check_context(arc.open(errorlevel=2), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=2), valueerror_filter):\n self.expect_exception(ValueError)\n\n # We only handle ExtractionError, FilterError & OSError specially.\n\n with self.check_context(arc.open(errorlevel='boo!'), filtererror_filter):\n self.expect_exception(TypeError) # errorlevel is not int\n","source":"cpython_tests","origin":"Lib/test/test_tarfile.py::TestExtractionFilters","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"tarfile-filter","pep":"706","introduced_in":"3.12","form":"modern","file":"tarfile-filter/modern_02.py","code":"import sys\nimport os\nimport io\nfrom hashlib import sha256\nfrom contextlib import contextmanager, ExitStack\nfrom random import Random\nimport pathlib\nimport shutil\nimport re\nimport warnings\nimport stat\nimport unittest\nimport unittest.mock\nimport tarfile\nfrom test import support\nfrom test.support import os_helper\nfrom test.support import script_helper\nfrom test.support import warnings_helper\n\n\nclass NoneInfoExtractTests(ReadTest):\n # These mainly check that all kinds of members are extracted successfully\n # if some metadata is None.\n # Some of the methods do additional spot checks.\n\n # We also test that the default filters can deal with None.\n\n extraction_filter = None\n\n @classmethod\n def setUpClass(cls):\n tar = tarfile.open(tarname, mode='r', encoding=\"iso8859-1\")\n cls.control_dir = pathlib.Path(TEMPDIR) / \"extractall_ctrl\"\n tar.errorlevel = 0\n with ExitStack() as cm:\n if cls.extraction_filter is None:\n cm.enter_context(warnings.catch_warnings(\n action=\"ignore\", category=DeprecationWarning))\n tar.extractall(cls.control_dir, filter=cls.extraction_filter)\n tar.close()\n cls.control_paths = set(\n p.relative_to(cls.control_dir)\n for p in pathlib.Path(cls.control_dir).glob('**/*'))\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.control_dir)\n\n def check_files_present(self, directory):\n got_paths = set(\n p.relative_to(directory)\n for p in pathlib.Path(directory).glob('**/*'))\n self.assertEqual(self.control_paths, got_paths)\n\n @contextmanager\n def extract_with_none(self, *attr_names):\n DIR = pathlib.Path(TEMPDIR) / \"extractall_none\"\n self.tar.errorlevel = 0\n for member in self.tar.getmembers():\n for attr_name in attr_names:\n setattr(member, attr_name, None)\n with os_helper.temp_dir(DIR):\n self.tar.extractall(DIR, filter='fully_trusted')\n self.check_files_present(DIR)\n yield DIR\n\n def test_extractall_none_mtime(self):\n # mtimes of extracted files should be later than 'now' -- the mtime\n # of a previously created directory.\n now = pathlib.Path(TEMPDIR).stat().st_mtime\n with self.extract_with_none('mtime') as DIR:\n for path in pathlib.Path(DIR).glob('**/*'):\n with self.subTest(path=path):\n try:\n mtime = path.stat().st_mtime\n except OSError:\n # Some systems can't stat symlinks, ignore those\n if not path.is_symlink():\n raise\n else:\n self.assertGreaterEqual(path.stat().st_mtime, now)\n\n def test_extractall_none_mode(self):\n # modes of directories and regular files should match the mode\n # of a \"normally\" created directory or regular file\n dir_mode = pathlib.Path(TEMPDIR).stat().st_mode\n regular_file = pathlib.Path(TEMPDIR) / 'regular_file'\n regular_file.write_text('')\n regular_file_mode = regular_file.stat().st_mode\n with self.extract_with_none('mode') as DIR:\n for path in pathlib.Path(DIR).glob('**/*'):\n with self.subTest(path=path):\n if path.is_dir():\n self.assertEqual(path.stat().st_mode, dir_mode)\n elif path.is_file():\n self.assertEqual(path.stat().st_mode,\n regular_file_mode)\n\n def test_extractall_none_uid(self):\n with self.extract_with_none('uid'):\n pass\n\n def test_extractall_none_gid(self):\n with self.extract_with_none('gid'):\n pass\n\n def test_extractall_none_uname(self):\n with self.extract_with_none('uname'):\n pass\n\n def test_extractall_none_gname(self):\n with self.extract_with_none('gname'):\n pass\n\n def test_extractall_none_ownership(self):\n with self.extract_with_none('uid', 'gid', 'uname', 'gname'):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_tarfile.py::NoneInfoExtractTests","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_01.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass ZoneInfoCacheTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n def setUp(self):\n self.klass.clear_cache()\n super().setUp()\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @property\n def tzpath(self):\n return [self.zoneinfo_data.tzpath]\n\n def test_ephemeral_zones(self):\n self.assertIs(\n self.klass(\"America/Los_Angeles\"), self.klass(\"America/Los_Angeles\")\n )\n\n def test_strong_refs(self):\n tz0 = self.klass(\"Australia/Sydney\")\n tz1 = self.klass(\"Australia/Sydney\")\n\n self.assertIs(tz0, tz1)\n\n def test_no_cache(self):\n\n tz0 = self.klass(\"Europe/Lisbon\")\n tz1 = self.klass.no_cache(\"Europe/Lisbon\")\n\n self.assertIsNot(tz0, tz1)\n\n def test_cache_reset_tzpath(self):\n \"\"\"Test that the cache persists when tzpath has been changed.\n\n The PEP specifies that as long as a reference exists to one zone\n with a given key, the primary constructor must continue to return\n the same object.\n \"\"\"\n zi0 = self.klass(\"America/Los_Angeles\")\n with self.tzpath_context([]):\n zi1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIs(zi0, zi1)\n\n def test_clear_cache_explicit_none(self):\n la0 = self.klass(\"America/Los_Angeles\")\n self.klass.clear_cache(only_keys=None)\n la1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIsNot(la0, la1)\n\n def test_clear_cache_one_key(self):\n \"\"\"Tests that you can clear a single key from the cache.\"\"\"\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n\n self.klass.clear_cache(only_keys=[\"America/Los_Angeles\"])\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n\n self.assertIsNot(la0, la1)\n self.assertIs(dub0, dub1)\n\n def test_clear_cache_two_keys(self):\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n tok0 = self.klass(\"Asia/Tokyo\")\n\n self.klass.clear_cache(\n only_keys=[\"America/Los_Angeles\", \"Europe/Dublin\"]\n )\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n tok1 = self.klass(\"Asia/Tokyo\")\n\n self.assertIsNot(la0, la1)\n self.assertIsNot(dub0, dub1)\n self.assertIs(tok0, tok1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ZoneInfoCacheTest","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_02.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass TzPathTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n @staticmethod\n @contextlib.contextmanager\n def python_tzpath_context(value):\n path_var = \"PYTHONTZPATH\"\n unset_env_sentinel = object()\n old_env = unset_env_sentinel\n try:\n with OS_ENV_LOCK:\n old_env = os.environ.get(path_var, None)\n os.environ[path_var] = value\n yield\n finally:\n if old_env is unset_env_sentinel:\n # In this case, `old_env` was never retrieved from the\n # environment for whatever reason, so there's no need to\n # reset the environment TZPATH.\n pass\n elif old_env is None:\n del os.environ[path_var]\n else:\n os.environ[path_var] = old_env # pragma: nocover\n\n def test_env_variable(self):\n \"\"\"Tests that the environment variable works with reset_tzpath.\"\"\"\n new_paths = [\n (\"\", []),\n (\"/etc/zoneinfo\", [\"/etc/zoneinfo\"]),\n (f\"/a/b/c{os.pathsep}/d/e/f\", [\"/a/b/c\", \"/d/e/f\"]),\n ]\n\n for new_path_var, expected_result in new_paths:\n with self.python_tzpath_context(new_path_var):\n with self.subTest(tzpath=new_path_var):\n self.module.reset_tzpath()\n tzpath = self.module.TZPATH\n self.assertSequenceEqual(tzpath, expected_result)\n\n def test_env_variable_relative_paths(self):\n test_cases = [\n [(\"path/to/somewhere\",), ()],\n [\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\",),\n ],\n [(\"../relative/path\",), ()],\n [\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\",),\n ],\n [(\"path/to/somewhere\", \"../relative/path\",), ()],\n [\n (\n \"/usr/share/zoneinfo\",\n \"path/to/somewhere\",\n \"../relative/path\",\n ),\n (\"/usr/share/zoneinfo\",),\n ],\n ]\n\n for input_paths, expected_paths in test_cases:\n path_var = os.pathsep.join(input_paths)\n with self.python_tzpath_context(path_var):\n with self.subTest(\"warning\", path_var=path_var):\n # Note: Per PEP 615 the warning is implementation-defined\n # behavior, other implementations need not warn.\n with self.assertWarns(self.module.InvalidTZPathWarning):\n self.module.reset_tzpath()\n\n tzpath = self.module.TZPATH\n with self.subTest(\"filtered\", path_var=path_var):\n self.assertSequenceEqual(tzpath, expected_paths)\n\n def test_reset_tzpath_kwarg(self):\n self.module.reset_tzpath(to=[\"/a/b/c\"])\n\n self.assertSequenceEqual(self.module.TZPATH, (\"/a/b/c\",))\n\n def test_reset_tzpath_relative_paths(self):\n bad_values = [\n (\"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"path/to/somewhere\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\", \"../relative/path\",),\n ]\n for input_paths in bad_values:\n with self.subTest(input_paths=input_paths):\n with self.assertRaises(ValueError):\n self.module.reset_tzpath(to=input_paths)\n\n def test_tzpath_type_error(self):\n bad_values = [\n \"/etc/zoneinfo:/usr/share/zoneinfo\",\n b\"/etc/zoneinfo:/usr/share/zoneinfo\",\n 0,\n ]\n\n for bad_value in bad_values:\n with self.subTest(value=bad_value):\n with self.assertRaises(TypeError):\n self.module.reset_tzpath(bad_value)\n\n def test_tzpath_attribute(self):\n tzpath_0 = [\"/one\", \"/two\"]\n tzpath_1 = [\"/three\"]\n\n with self.tzpath_context(tzpath_0):\n query_0 = self.module.TZPATH\n\n with self.tzpath_context(tzpath_1):\n query_1 = self.module.TZPATH\n\n self.assertSequenceEqual(tzpath_0, query_0)\n self.assertSequenceEqual(tzpath_1, query_1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TzPathTest","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_03.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass TestModule(ZoneInfoTestBase):\n module = py_zoneinfo\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @cached_property\n def _UTC_bytes(self):\n zone_file = self.zoneinfo_data.path_from_key(\"UTC\")\n with open(zone_file, \"rb\") as f:\n return f.read()\n\n def touch_zone(self, key, tz_root):\n \"\"\"Creates a valid TZif file at key under the zoneinfo root tz_root.\n\n tz_root must exist, but all folders below that will be created.\n \"\"\"\n if not os.path.exists(tz_root):\n raise FileNotFoundError(f\"{tz_root} does not exist.\")\n\n root_dir, *tail = key.rsplit(\"/\", 1)\n if tail: # If there's no tail, then the first component isn't a dir\n os.makedirs(os.path.join(tz_root, root_dir), exist_ok=True)\n\n zonefile_path = os.path.join(tz_root, key)\n with open(zonefile_path, \"wb\") as f:\n f.write(self._UTC_bytes)\n\n def test_getattr_error(self):\n with self.assertRaises(AttributeError):\n self.module.NOATTRIBUTE\n\n def test_dir_contains_all(self):\n \"\"\"dir(self.module) should at least contain everything in __all__.\"\"\"\n module_all_set = set(self.module.__all__)\n module_dir_set = set(dir(self.module))\n\n difference = module_all_set - module_dir_set\n\n self.assertFalse(difference)\n\n def test_dir_unique(self):\n \"\"\"Test that there are no duplicates in dir(self.module)\"\"\"\n module_dir = dir(self.module)\n module_unique = set(module_dir)\n\n self.assertCountEqual(module_dir, module_unique)\n\n def test_available_timezones(self):\n with self.tzpath_context([self.zoneinfo_data.tzpath]):\n self.assertTrue(self.zoneinfo_data.keys) # Sanity check\n\n available_keys = self.module.available_timezones()\n zoneinfo_keys = set(self.zoneinfo_data.keys)\n\n # If tzdata is not present, zoneinfo_keys == available_keys,\n # otherwise it should be a subset.\n union = zoneinfo_keys & available_keys\n self.assertEqual(zoneinfo_keys, union)\n\n def test_available_timezones_weirdzone(self):\n with tempfile.TemporaryDirectory() as td:\n # Make a fictional zone at \"Mars/Olympus_Mons\"\n self.touch_zone(\"Mars/Olympus_Mons\", td)\n\n with self.tzpath_context([td]):\n available_keys = self.module.available_timezones()\n self.assertIn(\"Mars/Olympus_Mons\", available_keys)\n\n def test_folder_exclusions(self):\n expected = {\n \"America/Los_Angeles\",\n \"America/Santiago\",\n \"America/Indiana/Indianapolis\",\n \"UTC\",\n \"Europe/Paris\",\n \"Europe/London\",\n \"Asia/Tokyo\",\n \"Australia/Sydney\",\n }\n\n base_tree = list(expected)\n posix_tree = [f\"posix/{x}\" for x in base_tree]\n right_tree = [f\"right/{x}\" for x in base_tree]\n\n cases = [\n (\"base_tree\", base_tree),\n (\"base_and_posix\", base_tree + posix_tree),\n (\"base_and_right\", base_tree + right_tree),\n (\"all_trees\", base_tree + right_tree + posix_tree),\n ]\n\n with tempfile.TemporaryDirectory() as td:\n for case_name, tree in cases:\n tz_root = os.path.join(td, case_name)\n os.mkdir(tz_root)\n\n for key in tree:\n self.touch_zone(key, tz_root)\n\n with self.tzpath_context([tz_root]):\n with self.subTest(case_name):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n\n def test_exclude_posixrules(self):\n expected = {\n \"America/New_York\",\n \"Europe/London\",\n }\n\n tree = list(expected) + [\"posixrules\"]\n\n with tempfile.TemporaryDirectory() as td:\n for key in tree:\n self.touch_zone(key, td)\n\n with self.tzpath_context([td]):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TestModule","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.12","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_04.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module\n\n\nclass ExtensionBuiltTest(unittest.TestCase):\n \"\"\"Smoke test to ensure that the C and Python extensions are both tested.\n\n Because the intention is for the Python and C versions of ZoneInfo to\n behave identically, these tests necessarily rely on implementation details,\n so the tests may need to be adjusted if the implementations change. Do not\n rely on these tests as an indication of stable properties of these classes.\n \"\"\"\n\n def test_cache_location(self):\n # The pure Python version stores caches on attributes, but the C\n # extension stores them in C globals (at least for now)\n self.assertFalse(hasattr(c_zoneinfo.ZoneInfo, \"_weak_cache\"))\n self.assertTrue(hasattr(py_zoneinfo.ZoneInfo, \"_weak_cache\"))\n\n def test_gc_tracked(self):\n import gc\n\n self.assertTrue(gc.is_tracked(py_zoneinfo.ZoneInfo))\n self.assertTrue(gc.is_tracked(c_zoneinfo.ZoneInfo))\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ExtensionBuiltTest","origin_revision":"v3.12.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_01.py","code":"from typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_02.py","code":"import typing\nx: typing.List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_03.py","code":"from typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: List[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> List[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_01.py","code":"from typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_02.py","code":"import typing\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_03.py","code":"from typing import List\nSomeAlias = list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: list[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> list[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_01.py","code":"x = lambda foo: None","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[lambdas do not have type annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_02.py","code":"from __future__ import annotations\nfrom typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_03.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not a PEP 585 type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_01.py","code":"open(\"foo\", encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop_before_315","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_02.py","code":"open(\"foo\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_03.py","code":"open(\"foo\", encoding=\"latin1\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"latin1\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_04.py","code":"open(\"foo\", encoding=\"us-ascii\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"us-ascii\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_05.py","code":"open(\"foo\", \"r\", \"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", \"r\", \"utf-8\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_06.py","code":"open(\"foo\", encoding=\"utf-8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[simple case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_07.py","code":"open(\"foo\", encoding=\"UTF8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[alternative spelling]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_08.py","code":"open(*args, encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_18.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"async def c(): return f'{await 1+foo()}'","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_18.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_01.py","code":"if s.startswith(\"foo\"):\n s = s[len(\"foo\"):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_02.py","code":"if s.startswith(S):\n s = s[len(S):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_03.py","code":"if s.endswith(\"foo\"):\n s = s[:-1 * len(\"foo\")]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_04.py","code":"if s.endswith(S):\n s = s[:-1 * len(S)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_05.py","code":"if s.startswith(x):\n s = s[len(x):] # TODO: removeprefix\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_06.py","code":"if True:\n if s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_07.py","code":"if True:\n something_else()\n if s.startswith(x):\n s = s[len(x):]\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_08.py","code":"if (\n x.startswith(y)\n):\n x = x[len(y):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_01.py","code":"s = s.removeprefix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_02.py","code":"s = s.removeprefix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_03.py","code":"s = s.removesuffix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_04.py","code":"s = s.removesuffix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_05.py","code":"s = s.removeprefix(x)\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_06.py","code":"if True:\n s = s.removeprefix(x)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_07.py","code":"if True:\n something_else()\n s = s.removeprefix(x)\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_08.py","code":"x = x.removeprefix(y)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_01.py","code":"if x.startswith(S):\n x = x[len(S):]\nelif x.endswith(T):\n x = x[:-1 * len(T)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop_before_39","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_02.py","code":"if s.startswith(\"a\"):\n s = s.lstrip(\"a\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[unrelated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_03.py","code":"if s.startswith(x):\n s = s[2:]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[cannot prove x is 2]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_04.py","code":"if s.startswith(x):\n s = s[len(x):]\nelse:\n print(\"no!)\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has else]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_05.py","code":"if something:\n print(\"something!\")\nelif s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has elif]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_01.py","code":"from __future__ import annotations\nfrom typing import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_02.py","code":"from __future__ import annotations\nfrom typing_extensions import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing_extensions.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_03.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_04.py","code":"from __future__ import annotations\nfrom collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_05.py","code":"from collections.abc import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_06.py","code":"from collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_01.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_02.py","code":"from __future__ import annotations\nfrom typing_extensions import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing_extensions.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_03.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_04.py","code":"from __future__ import annotations\nfrom collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_05.py","code":"from collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_06.py","code":"from collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"unchanged","file":"type-param-defaults/unchanged_01.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_noop[already converted!]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"unchanged","file":"type-param-defaults/unchanged_02.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int, int, None]: yield 1\ndef g() -> Generator[int, int, int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_noop[non-None send/return type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_01.py","code":"from typing import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_02.py","code":"import typing\nD = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": typing.Literal[\"b\", b\"c\"]})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_05.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {\n # first comment\n \"a\": int, # inline comment\n # second comment\n \"b\": str,\n # third comment\n}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_07.py","code":"from typing_extensions import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_08.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_09.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int}, total=True)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nFoo = TypedDict(\"Foo\", {\"lsts\": List[List[int]]})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_11.py","code":"import typing\nif True:\n if False:\n pass\n D = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_12.py","code":"from typing import TypedDict\nFoo = TypedDict(\"Foo\", {\"union\": str | int | None})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_01.py","code":"from typing import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_02.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_03.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_04.py","code":"import typing\nclass D(typing.TypedDict):\n a: typing.Literal['b', b'c']\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_05.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_06.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n # first comment\n a: int # inline comment\n # second comment\n b: str\n # third comment\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_07.py","code":"from typing_extensions import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_08.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_09.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict, total=True):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nclass Foo(TypedDict):\n lsts: List[List[int]]","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_11.py","code":"import typing\nif True:\n if False:\n pass\n class D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_12.py","code":"from typing import TypedDict\nclass Foo(TypedDict):\n union: str | int | None","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_01.py","code":"from wat import TypedDict\nQ = TypedDict(\"Q\")\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[from imported from elsewhere]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_02.py","code":"import typing\nD = typing.TypedDict(\"D\")","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {}, a=int)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[both]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_05.py","code":"import typing\nD = typing.TypedDict(\"D\", 1)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[not a dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {1: str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not a string]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_07.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a-b\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not an identifier]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_08.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"class\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is a keyword]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_09.py","code":"import typing\nD = typing.TypedDict(\"D\", {**d, \"a\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[dictionary splat operator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_10.py","code":"import typing\nC = typing.TypedDict(\"C\", *types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_11.py","code":"import typing\nD = typing.TypedDict(\"D\", **types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starstarkwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_12.py","code":"import typing\nD = typing.TypedDict(\"D\", x=int, total=False)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[kw_typed_dict with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_01.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_02.py","code":"import typing\nx: typing.Union[int]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_03.py","code":"import typing\nx: typing.Union[Foo[str, int], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_04.py","code":"import typing\nx: typing.Union[typing.List[str], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_05.py","code":"import typing\nx: typing.Union[int, str,]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_06.py","code":"import typing\nx: typing.Union[(int, str)]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_07.py","code":"import typing\nx: typing.Union[\n int,\n str\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_08.py","code":"import typing\nx: typing.Union[\n int,\n str,\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_09.py","code":"from typing import Optional\nx: Optional[str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_10.py","code":"import typing\nx: typing.Optional[\n ComplicatedLongType[int]\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: Optional[\"str\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_12.py","code":"from typing import Union, Sequence\ndef f(x: Union[Union[A, B], Sequence[Union[C, D]]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_13.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_14.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_15.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_16.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> Union[int, str]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_01.py","code":"from typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_02.py","code":"x: int\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_03.py","code":"x: Foo[str, int] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_04.py","code":"x: list[str] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_05.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_06.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_07.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_08.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_09.py","code":"from typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_10.py","code":"x: None | (\n ComplicatedLongType[int]\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_12.py","code":"from typing import Union\nfrom collections.abc import Sequence\ndef f(x: A | B | Sequence[C | D]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_13.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x})\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_14.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x}(\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_15.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x}(\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_16.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x})\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: int | str) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> int | str: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_01.py","code":"from __future__ import annotations\nfrom typing import Union\nSomeAlias = Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[<3.9 not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_02.py","code":"from typing import Union\ndef f() -> Union[()]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ empty Union]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_03.py","code":"from typing import Optional\ndef f() -> Optional[\"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Optional of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_04.py","code":"from typing import Union\ndef f() -> Union[int, \"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Union of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_05.py","code":"from typing import Union\ndef f() -> Union[1:2]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[invalid Union slicing]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack[Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack [Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_03.py","code":"from typing import Unpack\ndef f(*args: Unpack[tuple[int, ...]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_03.py","code":"from typing import Unpack\ndef f(*args: *tuple[int, ...]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_01.py","code":"from typing import Unpack\nfoo(Unpack())","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_02.py","code":"from typing import TypeVarTuple, Unpack\nShape = TypeVarTuple(\"Shape\")\nclass Foo(Unpack[Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not inside a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_03.py","code":"from typing import Unpack\nfrom typing import TypedDict\nclass D(TypedDict):\n x: int\ndef f(**kwargs: Unpack[D]) -> None: pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[3.12 TypedDict for kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_01.py","code":"from contextvars import ContextVar\nfrom types import MappingProxyType\nimport re\nimport collections\nimport time\n\n# Okay\nContextVar(\"cv\")\nContextVar(\"cv\", default=())\nContextVar(\"cv\", default=(1, 2, 3))\nContextVar(\"cv\", default=\"foo\")\nContextVar(\"cv\", default=tuple())\nContextVar(\"cv\", default=frozenset())\nContextVar(\"cv\", default=MappingProxyType({}))\nContextVar(\"cv\", default=re.compile(\"foo\"))\nContextVar(\"cv\", default=float(1))\nContextVar(\"cv\", default=frozenset[str]())\nContextVar[frozenset[str]](\"cv\", default=frozenset[str]())\n\n# Bad\nContextVar(\"cv\", default=[])\nContextVar(\"cv\", default={})\nContextVar(\"cv\", default=list())\nContextVar(\"cv\", default=set())\nContextVar(\"cv\", default=dict())\nContextVar(\"cv\", default=[char for char in \"foo\"])\nContextVar(\"cv\", default={char for char in \"foo\"})\nContextVar(\"cv\", default={char: idx for idx, char in enumerate(\"foo\")})\nContextVar(\"cv\", default=collections.deque())\nContextVar(\"cv\", default=set[str]())\nContextVar[set[str]](\"cv\", default=set[str]())\n\ndef bar() -> list[int]:\n return [1, 2, 3]\n\nContextVar(\"cv\", default=bar())\nContextVar(\"cv\", default=time.time())\n\ndef baz(): ...\nContextVar(\"cv\", default=baz())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_02.py","code":"from contextvars import ContextVar\n\nfrom fastapi import Query\nContextVar(\"cv\", default=Query(None))\n\nfrom something_else import Depends\nContextVar(\"cv\", default=Depends())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039_extended.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_01.py","code":"import typing\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, Sequence\n\nKNOWINGLY_MUTABLE_DEFAULT = []\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = []\n immutable_annotation: typing.Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: typing.ClassVar[list[int]] = []\n\n\n@dataclass\nclass B:\n mutable_default: list[int] = []\n immutable_annotation: Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: ClassVar[list[int]] = []\n\n# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n@dataclass\nclass AWithQuotes:\n mutable_default: 'list[int]' = []\n immutable_annotation: 'typing.Sequence[int]' = []\n without_annotation = []\n correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: 'list[int]' = field(default_factory=list)\n class_variable: 'typing.ClassVar[list[int]]'= []\n\n\n# Mutable defaults wrapped in field() calls\n@dataclass\nclass C:\n mutable_default: list[int] = field(default=[]) # RUF008\n mutable_default2: dict[str, int] = field(default={}) # RUF008\n mutable_default3: set[int] = field(default=set()) # RUF008\n mutable_default4: dict[str, int] = field(default=dict()) # RUF008\n correct_factory: list[int] = field(default_factory=list) # okay\n immutable_default: tuple[int, ...] = field(default=()) # okay\n immutable_default2: str = field(default=\"hello\") # okay\n immutable_default3: int = field(default=1) # okay\n non_mutable_var: list[int] = field(default=KNOWINGLY_MUTABLE_DEFAULT) # okay\n class_variable: ClassVar[list[int]] = field(default=[]) # okay\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_02.py","code":"# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n\nfrom __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Example():\n \"\"\"Class that uses ClassVar.\"\"\"\n\n options: ClassVar[dict[str, str]] = {}\n\n\nif typing.TYPE_CHECKING:\n from typing import ClassVar\n\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_03.py","code":"import datetime\nimport re\nimport typing\nfrom dataclasses import dataclass, field\nfrom fractions import Fraction\nfrom pathlib import Path\nfrom typing import ClassVar, NamedTuple\n\n\ndef default_function() -> list[int]:\n return []\n\n\nclass ImmutableType(NamedTuple):\n something: int = 8\n\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\n fine_path: Path = Path()\n fine_date: datetime.date = datetime.date(2042, 1, 1)\n fine_timedelta: datetime.timedelta = datetime.timedelta(hours=7)\n fine_tuple: tuple[int] = tuple([1])\n fine_regex: re.Pattern = re.compile(r\".*\")\n fine_float: float = float(\"-inf\")\n fine_int: int = int(12)\n fine_complex: complex = complex(1, 2)\n fine_str: str = str(\"foo\")\n fine_bool: bool = bool(\"foo\")\n fine_fraction: Fraction = Fraction(1, 2)\n\n\nDEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES = ImmutableType(40)\nDEFAULT_A_FOR_ALL_DATACLASSES = A([1, 2, 3])\n\n\n@dataclass\nclass B:\n hidden_mutable_default: list[int] = default_function()\n another_dataclass: A = A()\n not_optimal: ImmutableType = ImmutableType(20)\n good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES\n okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES\n\n fine_dataclass_function: list[int] = field(default_factory=list)\n\n\nclass IntConversionDescriptor:\n def __init__(self, *, default):\n self._default = default\n\n def __set_name__(self, owner, name):\n self._name = \"_\" + name\n\n def __get__(self, obj, type):\n if obj is None:\n return self._default\n\n return getattr(obj, self._name, self._default)\n\n def __set__(self, obj, value):\n setattr(obj, self._name, int(value))\n\n\n@dataclass\nclass InventoryItem:\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\n\n\n# Regression tests for:\n# https://github.com/astral-sh/ruff/issues/6447\nfrom typing import NewType\n\nListOfStrings = NewType(\"ListOfStrs\", list[str])\nStringsToInts = NewType(\"IntsToStrings\", dict[str, int])\n\nSpecialString = NewType(name=\"SpecialString\", tp=str)\nNegativeInteger = NewType(\"NegInt\", tp=int)\n\nInvalid1 = NewType(*Foo)\nInvalid2 = NewType(\"Invalid2\", name=Foo)\nInvalid3 = NewType(\"Invalid3\", name=Foo, lorem=\"ipsum\")\n\n@dataclass\nclass DataclassWithNewTypeFields:\n # Errors\n a: ListOfStrings = ListOfStrings([])\n b: StringsToInts = StringsToInts()\n c: Invalid1 = Invalid1()\n d: Invalid2 = Invalid2()\n e: Invalid3 = Invalid3()\n\n # No errors\n e: SpecialString = SpecialString(\"Lorem ipsum\")\n f: NegativeInteger = NegativeInteger(-110)\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/15772\ndef f() -> int:\n return 0\n\n@dataclass\nclass ShouldMatchB008RuleOfImmutableTypeAnnotationIgnored:\n this_is_not_fine: list[int] = default_function()\n # ignored\n this_is_fine: int = f()\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/17424\n@dataclass(frozen=True)\nclass C:\n foo: int = 1\n\n\n@dataclass\nclass D:\n c: C = C()\n\n\n@dataclass\nclass E:\n c: C = C()\n\n# https://github.com/astral-sh/ruff/issues/20266\n@dataclass(frozen=True)\nclass C:\n @dataclass(frozen=True)\n class D:\n foo: int = 1\n\n d: D = D() # OK","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_04.py","code":"from dataclasses import dataclass \nfrom typing import TYPE_CHECKING\n\n\ndef default_function() ->list[int]:\n return []\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\nif TYPE_CHECKING:\n from typing import ClassVar\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_05.py","code":"from dataclasses import InitVar, KW_ONLY, MISSING, dataclass, field\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n # Errors\n no_annotation = r\"foo\"\n missing = MISSING\n field = field()\n\n # No errors\n __slots__ = (\"foo\", \"bar\")\n __radd__ = __add__\n _private_attr = 100\n\n with_annotation: str\n with_annotation_and_default: int = 42\n with_annotation_and_field_specifier: bytes = field()\n\n class_var_no_arguments: ClassVar = 42\n class_var_with_arguments: ClassVar[int] = 42\n\n init_var_no_arguments: InitVar = \"lorem\"\n init_var_with_arguments: InitVar[str] = \"ipsum\"\n\n kw_only: KW_ONLY\n tu, ple, [unp, ack, ing] = (0, 1, 2, [3, 4, 5])\n mul, [ti, ple] = (a, ssign), ment = {1: b\"3\", \"2\": 4}, [6j, 5]\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_06.py","code":"from dataclasses import dataclass\nfrom enum import Enum, Flag, IntEnum, IntFlag, StrEnum, ReprEnum\n\nimport attr\nimport attrs\n\n\n## Errors\n\n@dataclass\nclass E(Enum): ...\n\n\n@dataclass # Foobar\nclass E(Flag): ...\n\n\n@dataclass()\nclass E(IntEnum): ...\n\n\n@dataclass() # Foobar\nclass E(IntFlag): ...\n\n\n@dataclass(\n frozen=True\n)\nclass E(StrEnum): ...\n\n\n@dataclass( # Foobar\n frozen=True\n)\nclass E(ReprEnum): ...\n\n\n@dataclass(\n frozen=True\n) # Foobar\nclass E(Enum): ...\n\n\n## No errors\n\n@attrs.define\nclass E(Enum): ...\n\n\n@attrs.frozen\nclass E(Enum): ...\n\n\n@attrs.mutable\nclass E(Enum): ...\n\n\n@attr.s\nclass E(Enum): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_01.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ntry: ...\nexcept* ValueError: ...\nexcept* KeyError: ...\nexcept * Error: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/except_star_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ntry: ...\nexcept* ValueError: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/except_star_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_01.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf'Magic wand: { bag['wand'] }' # nested quotes\nf\"{'\\n'.join(a)}\" # escape sequence\nf'''A complex trick: {\n bag['bag'] # comment\n}'''\nf\"{f\"{f\"{f\"{f\"{f\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nf\"{f'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nf\"{\n 1\n}\"\nf\"test {a \\\n } more\" # line continuation\nf\"\"\"{f\"\"\"{x}\"\"\"}\"\"\" # mark the whole triple quote\nf\"{'\\n'.join(['\\t', '\\v', '\\r'])}\" # multiple escape sequences, multiple errors\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/pep701_f_string_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\n# nested interpolations also need to be checked\nf'{1: abcd \"{'aa'}\" }'\nf'{1: abcd \"{\"\\n\"}\" }'\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/pep701_nested_interpolation_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_03.py","code":"# parse_options: {\"target-version\": \"3.12\"}\nf'Magic wand: { bag['wand'] }' # nested quotes\nf\"{'\\n'.join(a)}\" # escape sequence\nf'''A complex trick: {\n bag['bag'] # comment\n}'''\nf\"{f\"{f\"{f\"{f\"{f\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nf\"{f'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nf\"{\n 1\n}\"\nf\"test {a \\\n } more\" # line continuation\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep701_f_string_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_04.py","code":"# Empty f-strings\nf\"\"\nF\"\"\nf''\nf\"\"\"\"\"\"\nf''''''\n\nf\"{\" f\"}\"\nf\"{foo!s}\"\nf\"{3,}\"\nf\"{3!=4:}\"\nf'{3:{\"}\"}>10}'\nf'{3:{\"{\"}>10}'\nf\"{ foo = }\"\nf\"{ foo = :.3f }\"\nf\"{ foo = !s }\"\nf\"{ 1, 2 = }\"\nf'{f\"{3.1415=:.1f}\":*^20}'\n\n{\"foo \" f\"bar {x + y} \" \"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nf\"\\{foo}\\{bar:\\}\"\nf\"\\\\{{foo\\\\}}\"\nf\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nf\"{ ( foo ) = }\"\n\nf\"normal {foo} {{another}} {bar} {{{three}}}\"\nf\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nf\"normal {x:y + 2}\"\nf\"{x:{{1}.pop()}}\"\nf\"{(lambda x:{x})}\"\nf\"{x =}\"\nf\"{ x = }\"\nf\"{x=!a}\"\nf\"{x:.3f!r =}\"\nf\"{x = !r :.3f}\"\nf\"{x:.3f=!r}\"\n\"hello\" f\"{x}\"\nf\"{x}\" f\"{y}\"\nf\"{x}\" \"world\"\nf\"Invalid args in command: {command, *args}\"\n\"foo\" f\"{x}\" \"bar\"\n(\n f\"a\"\n F\"b\"\n \"c\"\n rf\"d\"\n fr\"e\"\n)\n\n# With unicode strings\nu\"foo\" f\"{bar}\" \"baz\" \" some\"\n\"foo\" f\"{bar}\" u\"baz\" \" some\"\n\"foo\" f\"{bar}\" \"baz\" u\" some\"\nu\"foo\" f\"bar {baz} really\" u\"bar\" \"no\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/f_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_01.py","code":"f\"hello {x:} world\"\nf\"hello {x:.3f} world\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/fstring_format_spec_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf\"{1:''}\" # but this is okay on all versions\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_nested_quote_in_format_spec_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_03.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf\"outer {'# not a comment'}\"\nf'outer {x:{\"# not a comment\"} }'\nf\"\"\"{f'''{f'{\"# not a comment\"}'}'''}\"\"\"\nf\"\"\"{f'''# before expression {f'# aro{f\"#{1+1}#\"}und #'}'''} # after expression\"\"\"\nf\"\"\"{\n 1\n}\"\"\"\nf\"escape outside of \\t {expr}\\n\"\nf\"test\\\"abcd\"\nf\"{1:\\x64}\" # escapes are valid in the format spec\nf\"{1:\\\"d\\\"}\" # this also means that escaped outer quotes are valid\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep701_f_string_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_01.py","code":"import typing\nimport typing_extensions\nfrom typing import Literal\n\n# Shouldn't affect non-union field types.\nfield1: Literal[1] # OK\n\n# Should emit for duplicate field types.\nfield2: Literal[1] | Literal[2] # Error\n\n# Should emit for union types in arguments.\ndef func1(arg1: Literal[1] | Literal[2]): # Error\n print(arg1)\n\n\n# Should emit for unions in return types.\ndef func2() -> Literal[1] | Literal[2]: # Error\n return \"my Literal[1]ing\"\n\n\n# Should emit in longer unions, even if not directly adjacent.\nfield3: Literal[1] | Literal[2] | str # Error\nfield4: str | Literal[1] | Literal[2] # Error\nfield5: Literal[1] | str | Literal[2] # Error\nfield6: Literal[1] | bool | Literal[2] | str # Error\n\n# Should emit for non-type unions.\nfield7 = Literal[1] | Literal[2] # Error\n\n# Should emit for parenthesized unions.\nfield8: Literal[1] | (Literal[2] | str) # Error\n\n# Should handle user parentheses when fixing.\nfield9: Literal[1] | (Literal[2] | str) # Error\nfield10: (Literal[1] | str) | Literal[2] # Error\n\n# Should emit for union in generic parent type.\nfield11: dict[Literal[1] | Literal[2], str] # Error\n\n# Should emit for unions with more than two cases\nfield12: Literal[1] | Literal[2] | Literal[3] # Error\nfield13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error\n\n# Should emit for unions with more than two cases, even if not directly adjacent\nfield14: Literal[1] | Literal[2] | str | Literal[3] # Error\n\n# Should emit for unions with mixed literal internal types\nfield15: Literal[1] | Literal[\"foo\"] | Literal[True] # Error\n\n# Shouldn't emit for duplicate field types with same value; covered by Y016\nfield16: Literal[1] | Literal[1] # OK\n\n# Shouldn't emit if in new parent type\nfield17: Literal[1] | dict[Literal[2], str] # OK\n\n# Shouldn't emit if not in a union parent\nfield18: dict[Literal[1], Literal[2]] # OK\n\n# Should respect name of literal type used\nfield19: typing.Literal[1] | typing.Literal[2] # Error\n\n# Should emit in cases with newlines\nfield20: typing.Union[\n Literal[\n 1 # test\n ],\n Literal[2],\n] # Error, newline and comment will not be emitted in message\n\n# Should handle multiple unions with multiple members\nfield21: Literal[1, 2] | Literal[3, 4] # Error\n\n# Should emit in cases with `typing.Union` instead of `|`\nfield22: typing.Union[Literal[1], Literal[2]] # Error\n\n# Should emit in cases with `typing_extensions.Literal`\nfield23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error\n\n# Should emit in cases with nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error\n\n# Should emit in cases with mixed `typing.Union` and `|`\nfield25: typing.Union[Literal[1], Literal[2] | str] # Error\n\n# Should emit only once in cases with multiple nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error\n\n# Should use the first literal subscript attribute when fixing\nfield25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error\n\nfrom typing import IO, Literal\n\nInlineOption = Literal[\"a\"] | Literal[\"b\"] | IO[str]\n\n# Should use unsafe fix when comments are deleted\nfield26: (\n # First comment\n Literal[\"a\", \"b\"]\n # Second comment\n | Literal[\"c\", \"d\"]\n)\nfield27: (\n Literal[\"a\", \"b\"] # First comment\n | Literal[\"c\", \"d\"] # Second comment\n)\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI030.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_02.py","code":"import typing\nfrom typing import Literal, TypeAlias, Union\n\nA: str | Literal[\"foo\"]\nB: TypeAlias = typing.Union[Literal[b\"bar\", b\"foo\"], bytes, str]\nC: TypeAlias = typing.Union[Literal[5], int, typing.Union[Literal[\"foo\"], str]]\nD: TypeAlias = typing.Union[Literal[b\"str_bytes\", 42], bytes, int]\nE: TypeAlias = typing.Union[typing.Union[typing.Union[typing.Union[Literal[\"foo\"], str]]]]\nF: TypeAlias = typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\nG: typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\n\ndef func(x: complex | Literal[1J], y: Union[Literal[3.14], float]): ...\n\n# OK\nA: Literal[\"foo\"]\nB: TypeAlias = Literal[b\"bar\", b\"foo\"]\nC: TypeAlias = typing.Union[Literal[5], Literal[\"foo\"]]\nD: TypeAlias = Literal[b\"str_bytes\", 42]\n\ndef func(x: Literal[1J], y: Literal[3.14]): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI051.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_03.py","code":"from typing import Literal\nimport typing as t\nimport typing_extensions\n\nx: Literal[True, False, True, False] # PYI062 twice here\n\ny: Literal[1, print(\"hello\"), 3, Literal[4, 1]] # PYI062 on the last 1\n\nz: Literal[{1, 3, 5}, \"foobar\", {1,3,5}] # PYI062 on the set literal\n\nLiteral[1, Literal[1]] # once\nLiteral[1, 2, Literal[1, 2]] # twice\nLiteral[1, Literal[1], Literal[1]] # twice\nLiteral[1, Literal[2], Literal[2]] # once\nt.Literal[1, t.Literal[2, t.Literal[1]]] # once\ntyping_extensions.Literal[1, 1, 1] # twice\nLiteral[\n 1, # comment\n Literal[ # another comment\n 1\n ]\n] # once\n\n# Ensure issue is only raised once, even on nested literals\nMyType = Literal[\"foo\", Literal[True, False, True], \"bar\"] # PYI062\n\nn: Literal[\"No\", \"duplicates\", \"here\", 1, \"1\"]\n\n\n# nested literals, all equivalent to `Literal[1]`\nLiteral[Literal[1]] # no duplicate\nLiteral[Literal[Literal[1], Literal[1]]] # once\nLiteral[Literal[1], Literal[Literal[Literal[1]]]] # once\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI062.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_01.py","code":"# parse_options: { \"target-version\": \"3.9\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/match_before_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_02.py","code":"match 2:\n case Class(x=x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_keyword_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_03.py","code":"match x:\n case [a] | [a]: ...\n case (x, y) | (x, y): ...\n case (x, (y | y)): ...\n case [a, _] | [a, _]: ...\n case [a] | [C(a)]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/different_match_pattern_bindings.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_04.py","code":"match x:\n case {x.a: 1, x.a: 2}: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/duplicate_match_key_attr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_05.py","code":"match x:\n case 2: ...\n case var: ...\nmatch x:\n case 2: ...\n case _: ...\nmatch x:\n case var if True: ... # don't try to refute a guarded pattern\n case 2: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/irrefutable_case_pattern_at_end.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_06.py","code":"# parse_options: { \"target-version\": \"3.10\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_after_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_07.py","code":"match foo:\n case foo_bar: ...\nmatch foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_08.py","code":"match foo:\n case case: ...\nmatch foo:\n case match: ...\nmatch foo:\n case type: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_09.py","code":"match foo:\n case match.bar: ...\n case case.bar: ...\n case type.bar: ...\n case match.case.type.bar.type.case.match: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_attr_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_10.py","code":"match foo:\n case _: ...\nmatch 1:\n case _: ...\nmatch 1.0:\n case _: ...\nmatch 1j:\n case _: ...\nmatch \"foo\":\n case _: ...\nmatch f\"foo {x}\":\n case _: ...\nmatch {1, 2}:\n case _: ...\nmatch ~foo:\n case _: ...\nmatch ...:\n case _: ...\nmatch not foo:\n case _: ...\nmatch await foo():\n case _: ...\nmatch lambda foo: foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_11.py","code":"match match:\n case _: ...\nmatch case:\n case _: ...\nmatch type:\n case _: ...\nmatch None:\n case _: ...\nmatch True:\n case _: ...\nmatch False:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_12.py","code":"match (1, 2) # Identifier\nmatch (1, 2): # Keyword\n case _: ...\nmatch [1:] # Identifier\nmatch [1, 2]: # Keyword\n case _: ...\nmatch * foo # Identifier\nmatch - foo # Identifier\nmatch -foo: # Keyword\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_or_identifier.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_13.py","code":"match subject:\n case [a, b]: ...\n case (a, b): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_parentheses_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_14.py","code":"match subject:\n case a if x: ...\n case a, b: ...\n case a, b if x: ...\n case a: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_15.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_16.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_17.py","code":"match 2:\n case Class(x) | [x] | x: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/multiple_assignment_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_18.py","code":"match ruff:\n case {\"lint\": {\"select\": x} | {\"extend-select\": x}} | {\"select\": x}:\n ...\nmatch 42:\n case [[x] | [x]] | x: ...\nmatch 42:\n case [[x | x] | [x]] | x: ...\nmatch 42:\n case ast.Subscript(n, ast.Constant() | ast.Slice()) | ast.Attribute(n): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/nested_alternative_patterns.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_19.py","code":"# Empty f-strings\nf\"\"\nF\"\"\nf''\nf\"\"\"\"\"\"\nf''''''\n\nf\"{\" f\"}\"\nf\"{foo!s}\"\nf\"{3,}\"\nf\"{3!=4:}\"\nf'{3:{\"}\"}>10}'\nf'{3:{\"{\"}>10}'\nf\"{ foo = }\"\nf\"{ foo = :.3f }\"\nf\"{ foo = !s }\"\nf\"{ 1, 2 = }\"\nf'{f\"{3.1415=:.1f}\":*^20}'\n\n{\"foo \" f\"bar {x + y} \" \"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nf\"\\{foo}\\{bar:\\}\"\nf\"\\\\{{foo\\\\}}\"\nf\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nf\"{ ( foo ) = }\"\n\nf\"normal {foo} {{another}} {bar} {{{three}}}\"\nf\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nf\"normal {x:y + 2}\"\nf\"{x:{{1}.pop()}}\"\nf\"{(lambda x:{x})}\"\nf\"{x =}\"\nf\"{ x = }\"\nf\"{x=!a}\"\nf\"{x:.3f!r =}\"\nf\"{x = !r :.3f}\"\nf\"{x:.3f=!r}\"\n\"hello\" f\"{x}\"\nf\"{x}\" f\"{y}\"\nf\"{x}\" \"world\"\nf\"Invalid args in command: {command, *args}\"\n\"foo\" f\"{x}\" \"bar\"\n(\n f\"a\"\n F\"b\"\n \"c\"\n rf\"d\"\n fr\"e\"\n)\n\n# With unicode strings\nu\"foo\" f\"{bar}\" \"baz\" \" some\"\n\"foo\" f\"{bar}\" u\"baz\" \" some\"\n\"foo\" f\"{bar}\" \"baz\" u\" some\"\nu\"foo\" f\"bar {baz} really\" u\"bar\" \"no\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/f_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_20.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_01.py","code":"match[0]: int\nmatch [x, y, z]: dict\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_annotated_assignment.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_02.py","code":"match not in case\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_03.py","code":"match\nmatch != foo\n(foo, match)\n[foo, match]\n{foo, match}\nmatch;\nmatch: int\nmatch,\nmatch.foo\nmatch / foo\nmatch << foo\nmatch and foo\nmatch is not foo\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_04.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_01.py","code":"# parse_options: {\"target-version\": \"3.8\"}\ndef foo(a, /): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pos_only_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_02.py","code":"lambda: a\nlambda: 1\nlambda x: 1\nlambda x, y: ...\nlambda a, b, c: 1\nlambda a, b=20, c=30: 1\nlambda x, y: x * y\nlambda y, z=1: z * y\nlambda *a: a\nlambda *a, z, x=0: ...\nlambda *, a, b, c: 1\nlambda *, a, b=20, c=30: 1\nlambda a, b, c, *, d, e: 0\nlambda **kwargs: f()\nlambda *args, **kwargs: f() + 1\nlambda *args, a, b=1, **kwargs: f() + 1\nlambda a, /: ...\nlambda a, /, b: ...\nlambda a=1, /,: ...\nlambda a, b, /, *, c: ...\nlambda kw=1, *, a: ...\nlambda a, b=20, /, c=30: 1\nlambda a, b, /, c, *, d, e: 0\nlambda a, b, /, c, *d, e, **f: 0","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/lambda.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_03.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_07.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\nclass D[S, T = int, U = uint](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_param_default_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_08.py","code":"type Alias[T] = list[T]\ndef f[T](t: T): ...\nclass C[T]: ...\nclass C[T, U, V]: ...\ntype Alias[T, U: str, V: (str, bytes), *Ts, **P, D = default] = ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_duplicate_type_parameter_names.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_09.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_default_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_10.py","code":"type X[**P] = int\ntype X[**P = int] = int\ntype X[T, **P] = int\ntype X[T, **P = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_param_spec.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_11.py","code":"type X[T] = int\ntype X[T = int] = int\ntype X[T: int = int] = int\ntype X[T: (int, int) = int] = int\ntype X[T: int = int, U: (int, int) = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_12.py","code":"type X[*Ts] = int\ntype X[*Ts = int] = int\ntype X[*Ts = *int] = int\ntype X[T, *Ts] = int\ntype X[T, *Ts = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var_tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_13.py","code":"class Test:\n ...\n\n\nclass Test():\n def __init__(self):\n pass\n\n\nclass Test(a=1, *A, **k):\n ...\n\n\nclass Test:\n def method():\n a, b = data\n\n\nclass Test(A, B):\n def __init__(self):\n pass\n\n def method_with_default(self, arg='default'):\n pass\n\n\n# Class with generic types:\n\n# TypeVar\nclass Test[T](): ...\n\n# TypeVar with default\nclass Test[T = str](): ...\n\n# TypeVar with bound\nclass Test[T: str](): ...\n\n# TypeVar with bound and default\nclass Test[T: int | str = int](): ...\n\n# TypeVar with tuple bound\nclass Test[T: (str, bytes)](): ...\n\n# Multiple TypeVar\nclass Test[T, U](): ...\n\n# Trailing comma\nclass Test[T, U,](): ...\n\n# TypeVarTuple\nclass Test[*Ts](): ...\n\n# TypeVarTuple with default\nclass Test[*Ts = Unpack[tuple[int, str]]](): ...\n\n# TypeVarTuple with starred default\nclass Test[*Ts = *tuple[int, str]](): ...\n\n# ParamSpec\nclass Test[**P](): ...\n\n# ParamSpec with default\nclass Test[**P = [int, str]](): ...\n\n# Mixed types\nclass Test[X, Y: str, *U, **P]():\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_14.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_01.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\nclass D[S, T = int, U = uint](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_param_default_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ntype x = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_stmt_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_03.py","code":"# parse_options: {\"target-version\": \"3.12\"}\nclass Foo[S: (str, bytes), T: float, *Ts, **P]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_type_params_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_04.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ndef foo[T](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/function_type_params_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_05.py","code":"type Alias[T] = list[T]\ndef f[T](t: T): ...\nclass C[T]: ...\nclass C[T, U, V]: ...\ntype Alias[T, U: str, V: (str, bytes), *Ts, **P, D = default] = ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_duplicate_type_parameter_names.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_06.py","code":"return; import a; from x import y; z; type T = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/simple_stmts_with_semicolons.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_07.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_default_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_08.py","code":"type X[**P] = int\ntype X[**P = int] = int\ntype X[T, **P] = int\ntype X[T, **P = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_param_spec.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_09.py","code":"type X[T] = int\ntype X[T = int] = int\ntype X[T: int = int] = int\ntype X[T: (int, int) = int] = int\ntype X[T: int = int, U: (int, int) = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_10.py","code":"type X[*Ts] = int\ntype X[*Ts = int] = int\ntype X[*Ts = *int] = int\ntype X[T, *Ts] = int\ntype X[T, *Ts = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var_tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_11.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype x = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_stmt_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_12.py","code":"class Test:\n ...\n\n\nclass Test():\n def __init__(self):\n pass\n\n\nclass Test(a=1, *A, **k):\n ...\n\n\nclass Test:\n def method():\n a, b = data\n\n\nclass Test(A, B):\n def __init__(self):\n pass\n\n def method_with_default(self, arg='default'):\n pass\n\n\n# Class with generic types:\n\n# TypeVar\nclass Test[T](): ...\n\n# TypeVar with default\nclass Test[T = str](): ...\n\n# TypeVar with bound\nclass Test[T: str](): ...\n\n# TypeVar with bound and default\nclass Test[T: int | str = int](): ...\n\n# TypeVar with tuple bound\nclass Test[T: (str, bytes)](): ...\n\n# Multiple TypeVar\nclass Test[T, U](): ...\n\n# Trailing comma\nclass Test[T, U,](): ...\n\n# TypeVarTuple\nclass Test[*Ts](): ...\n\n# TypeVarTuple with default\nclass Test[*Ts = Unpack[tuple[int, str]]](): ...\n\n# TypeVarTuple with starred default\nclass Test[*Ts = *tuple[int, str]](): ...\n\n# ParamSpec\nclass Test[**P](): ...\n\n# ParamSpec with default\nclass Test[**P = [int, str]](): ...\n\n# Mixed types\nclass Test[X, Y: str, *U, **P]():\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_13.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_14.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"unchanged","file":"type-param-syntax/unchanged_01.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/param_with_star_annotation_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_05.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_06.py","code":"def foo(*args: *int | str): ...\ndef foo(*args: *(int or str)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_07.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_08.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/star_index_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_09.py","code":"*a\n*(a + 1)\n*x.attr\n\narray_slice = array[0, *indexes, -1]\narray[0, *indexes, -1] = array_slice\narray[*indexes_to_select, *indexes_to_select]\narray[3:5, *indexes_to_select]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/starred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_10.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_11.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_12.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nout[(*(slice(None) for _ in range(2)), *ind)] = 1\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_01.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/decorator_named_expression_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_03.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/invalid_annotation_function_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_04.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_05.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_comp_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_06.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{x := 1, 2, 3}\n{1, x := 2, 3}\n{1, 2, x := 3}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_literal_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_07.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/walrus_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_08.py","code":"# parse_options: { \"target-version\": \"3.9\" }\n@buttons[0].clicked.connect\ndef spam(): ...\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/decorator_expression_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_09.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_10.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_11.py","code":"[a := 0 for x in range(0)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_rebound_comprehension_variable.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_12.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[(x:=1)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_13.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{(x := 1), 2, 3}\n{(last := x) for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_14.py","code":"# parse_options: {\"target-version\": \"3.9\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_index_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_15.py","code":"# parse_options: {\"target-version\": \"3.9\"}\n{x := 1, 2, 3}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_16.py","code":"class F(y := list): ...\ndef f():\n class G((yield 1)): ...\n class H((yield from 1)): ...\nasync def f():\n class G((await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_17.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_function_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_18.py","code":"# parse_options: {\"target-version\": \"3.13\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_19.py","code":"# parse_options: { \"target-version\": \"3.8\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/walrus_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_20.py","code":"# This only tests the call arguments and not the expression before the opening parenthesis.\n\n# Simple\ncall()\ncall(x, y)\ncall(x, y,) # Trailing comma\ncall(x=1, y=2)\ncall(*x)\ncall(**x)\n\n# Order\ncall(x, y=1)\ncall(x, *y)\ncall(x, **y)\ncall(x=1, *y)\ncall(x=1, **y)\ncall(*x, **y)\ncall(*x, y, z)\ncall(**x, y=1, z=2)\ncall(*x1, *x2, **y1, **y2)\ncall(x=1, **y, z=1)\n\n# Keyword expression\ncall(x=1 if True else 2)\ncall(x=await y)\ncall(x=lambda y: y)\ncall(x=(y := 1))\n\n# Yield expression\ncall((yield x))\ncall((yield from x))\n\n# Named expression\ncall(x := 1)\ncall(x := 1 for i in iter)\n\n# Starred expressions\ncall(*x and y)\ncall(*x | y)\ncall(*await x)\ncall(*lambda x: x)\ncall(*x if True else y)\n\n# Double starred\ncall(**x)\ncall(**x and y)\ncall(**await x)\ncall(**x if True else y)\ncall(**(yield x))\ncall(**lambda x: x)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/arguments.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_21.py","code":"# Simple\n{}\n{1: 2}\n{1: 2, a: 1, b: 'hello'}\n\n# Mixed indentations\n{\n}\n{\n 1:\n 2,\n 3\n :4\n}\n\n# Nested\n{{1: 2}: {3: {4: 5}}}\n\n# Lambda expressions\n{lambda x: x: 1}\n{'A': lambda p: None, 'B': C,}\n\n# Named expressions\n{(x := 1): y}\n{(x := 1): (y := 2)}\n\n# Double star unpacking\n{**d}\n{a: b, **d}\n{**a, **b}\n{\"a\": \"b\", **c, \"d\": \"e\"}\n{1: 2, **{'nested': 'dict'}}\n{x * 1: y ** 2, **call()}\n# Here, `not` isn't allowed but parentheses resets the precedence\n{**(not x)}\n\n# Random expressions\n{1: x if True else y}\n{x if True else y: y for x in range(10) for y in range(10)}\n{{1, 2}: 3, x: {1: 2,},}\n{(x): (y), (z): (a)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/dictionary.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_22.py","code":"(x for target in iter)\n(x async for target in iter)\n(x for target in iter if x in y if a and b if c)\n(x for target1 in iter1 if x and y for target2 in iter2 if a > b)\n(x for target1 in iter1 if x and y async for target2 in iter2 if a > b)\n\n# Named expression\n(x := y + 1 for y in z)\n\n# If expression\n(x if y else y for y in z)\n\n# Arguments\n\" \".join(\n sql\n for sql in (\n \"LIMIT %d\" % limit if limit else None,\n (\"OFFSET %d\" % offset) if offset else None,\n )\n)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/generator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_23.py","code":"# Simple lists\n[]\n[1]\n[1,]\n[1, 2, 3]\n[1, 2, 3,]\n\n# Mixed with indentations\n[\n]\n[\n 1\n]\n[\n 1,\n 2,\n]\n\n# Nested\n[[[1]]]\n[[1, 2], [3, 4]]\n\n# Named expression\n[x := 2]\n[x := 2,]\n[1, x := 2, 3]\n\n# Star expression\n[1, *x, 3]\n[1, *x | y, 3]\n\n# Random expressions\n[1 + 2, [1, 2, 3, 4], (a, b + c, d), {a, b, c}, {a: 1}, x := 2]\n[call1(call2(value.attr()) for element in iter)]\n[item in xs]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/list.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_24.py","code":"(name := 0)\n(name := (x * y))\n(name := 1 + 1)\n(name := (*x, y))\n(name := x if True else y)\n(name := lambda x: x)\n(name := (yield x))\n(name := (yield from x))","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/named.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_25.py","code":"(expr)\n(expr)()\n(expr)()()()\n\n(a and b or c)\n(lambda x: x)\n(x := 2)\n(yield x)\n(yield from x)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/parenthesized.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_26.py","code":"# Simple sets\n{}\n{1}\n{1,}\n{1, 2, 3}\n{1, 2, 3,}\n\n# Mixed with indentations\n{\n}\n{\n 1\n}\n{\n 1,\n 2,\n}\n\n# Nested\n{{1}}\n{{1, 2}, {3, 4}}\n\n# Named expression\n{x := 2}\n{1, x := 2, 3}\n{1, (x := 2),}\n\n# Star expression\n{1, *x, 3}\n{1, *x | y, 3}\n\n# Random expressions\n{1 + 2, (a, b), {1, 2, 3}, {a: b, **d}}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/set.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_27.py","code":"# Various combinations\nx[:]\nx[1:]\nx[:2]\nx[1:2]\nx[::]\nx[1::]\nx[:2:]\nx[1:2:]\nx[::3]\nx[1::3]\nx[:2:3]\nx[1:2:3]\n\n# Named expression\nx[y := 2]\nx[(y := 2):]\nx[y := 2,]\n\n# These are two separate slice elements\nx[1,:2,]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/slice.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_28.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_29.py","code":"# With parentheses\n()\n(())\n((()), ())\n(a,)\n(a, b)\n(a, b,)\n((a, b))\n\n# Without parentheses\na,\na, b\na, b,\n\n# Starred expression\n*a,\na, *b\n*a | b, *await x, (), *()\n(*a,)\n(a, *b)\n(*a | b, *await x, (), *())\n\n# Named expression\n(x := 1,)\n(x, y := 2)\n(x, y := 2, z)\nx, (y := 2), z\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_30.py","code":"# Simple\n-1\n+1\n~1\nnot x\n\n# Multiple\n---1\n-+~1\nnot-+~1\nnot not x\n\n# Precedence check\n- await 1\n+ await 1 ** -2\n~(1, 2)\n-1 + 2\n\n# Precedence check for `not` operator because it is higher than other unary operators\nnot a and b or not c | d and not e\nnot (x := 1)\nnot a | (not b)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/unary_op.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_31.py","code":"yield\nyield x\nyield x + 1\nyield x and y\nyield call()\nyield [1, 2]\nyield {3, 4}\nyield {x: 5}\nyield x, y\nyield (x, y)\nyield x == y\nyield (x := 1)\nyield x, *y\nyield *x,\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_32.py","code":"yield from x\nyield from x + 1\nyield from x and y\nyield from call()\nyield from [1, 2]\nyield from {3, 4}\nyield from {x: 5}\nyield from (x, y)\nyield from x == y\nyield from (x := 1)\nyield from (x, *x | y)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield_from.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_33.py","code":"@function_decorator\ndef test():\n pass\n\n\n@class_decorator\nclass Test:\n pass\n\n\n@decorator\ndef f(): ...\n\n\n@a.b.c\ndef f(): ...\n\n\n@a\n@a.b.c\ndef f(): ...\n\n\n@a\n@1 | 2\n@a.b.c\nclass T: ...\n\n\n@x := 1\n@x if True else y\n@lambda x: x\n@x and y\n@(yield x)\n@(*x, *y)\ndef f(): ...\n\n\n# This is not multiple decorators on the same line but rather a binary (`@`) expression\n@x @y\ndef foo(): ...\n\n\n@x\n\n\n@y\n\n\ndef foo(): ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/other/decorator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_34.py","code":"# These test cases specifically tests out parsing a list of with items that start with a\n# left parenthesis. This makes parsing ambiguous as to whether the left parenthesis is to\n# parenthesize the with items or part of a parenthesized expression. It's not to test the\n# with statement itself.\n\n# The following sections basically separates between which node does the\n# start parenthesis belongs to.\n\n# Parenthesized with items\n# ------------------------\n#\n# - The opening parenthesis belongs to the with statement.\n# - The range of the first with item shouldn't include the parenthesis.\nwith (item): ...\nwith (item,): ... # with a trailing comma\nwith (((item))): ...\nwith (item1, item2): ...\nwith (item1, item2,): ... # with a trailing comma\nwith ((item1), (item2), item3 as f, (item4)): ...\nwith ((item1, item2), item3): ...\nwith ((x, y) as f): ...\nwith (item1 as f1, item2 as f2): ...\nwith (item1 as f1, item2 as f2,): ... # with a trailing comma\nwith (item == 10,): ...\nwith ((item := 10)): ...\nwith ((item := 10,)): ...\nwith ((*item,)): ...\nwith ((item1 := 10), item2): ...\nwith (item1 as f, (item2 := 10)): ...\nwith (foo()): ...\nwith (foo(),): ...\nwith (foo() as f): ...\nwith (f\"{item := 42}\"): ...\nwith (f\"{(item := 42)}\"): ...\nwith ((x for x in range(10)), item): ...\nwith (item, (x for x in range(10))): ...\nwith (item, (x for x in range(10)), item): ...\nwith (data[1:2]): ...\nwith (data[1:2] as f): ...\nwith ((x for x in iter) as y): ...\n\n# Parenthesized expression\n# ------------------------\n#\n# - The opening parenthesis belongs to the context expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (item) as f: ...\nwith (item := 10): ...\nwith (item := 10) as f: ...\nwith ( item := 1 ): ...\nwith (item1 := 42), item2: ...\nwith (root + filename).read(): ... # Postfix expression\nwith (root + filename).read() as f: ... # Postfix expression\nwith (foo)(): ... # Postfix expression\nwith (foo)() as f: ... # Postfix expression\nwith (foo()) as f: ...\nwith (data[1:2]) as f: ...\nwith (1, 2, 3)[0]: ... # Postfix expression\nwith (1, 2, 3)[0] as f: ... # Postfix expression\nwith (item1), (item2): ...\nwith (open('a.py')), (open('b.py')): ...\nwith (yield x): ...\nwith ((yield x)): ...\nwith (yield from x): ...\nwith ((yield from x)): ...\nwith (yield x) as f: ...\nwith (yield x,) as f: ...\n\n\n# Tuple expression\n# ----------------\n#\n# - This is a sub-case of the parenthesized expression and requires transforming the list of\n# with items from the speculative parsing to a single with item containing a tuple expression.\n# - The opening parenthesis belongs to the tuple expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (): ...\nwith () as f: ...\nwith (item := 42,): ...\nwith (1, item := 2): ...\nwith (item1 := 10, item2): ...\nwith (item1, item2 := 2, item3) as f: ...\nwith (item,) as f: ...\nwith (*item,): ...\nwith (*item,) as f: ...\nwith (item1, item2) as f: ...\nwith (item1, item2,) as f: ...\nwith (item1, item2), item3: ...\nwith ((item1, item2), item3) as f: ...\nwith (item1,), item2, (item3, item4) as f: ...\nwith (item1, item2) as f1, item3 as f2: ...\nwith (item1, *item2): ...\nwith (item1, *item2) as f: ...\nwith (item1 := 10, *item2): ...\nwith ((item1 := 10), *item2): ...\n\n\n# Parenthesized generator expression\n# ----------------------------------\n#\n# - The opening parenthesis belongs to the generator expression\n# - The range of the with item should include the parenthesis\nwith (x for x in range(10)): ...\nwith (x async for x in range(10)): ...\nwith (x for x in range(10)), item: ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/ambiguous_lpar_with_items.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_35.py","code":"if 1: 10\nelif 2: 20\nelse: 30\n\nif True:\n 1\n ...\nif x < 1:\n ...\nelse:\n pass\n\nif a:\n pass\nelif b:\n ...\n\nif a and b:\n ...\nelif True:\n ...\nelif c:\n ...\nelif d:\n ...\nelse:\n f()\n\n# Valid test expression\nif a := b: ...\nelif a := b: ...\nif lambda x: x: ...\nelif lambda x: x: ...\nif await x: ...\nelif await x: ...\nif (yield x): ...\nelif (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/if.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_36.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_37.py","code":"return\nreturn x\nreturn *x, *y\nreturn (x := 1)\nreturn None\nreturn x and y\nreturn 1 < 2\nreturn 1, 2,\nreturn call()\nreturn attr.value()\nreturn await x\nreturn lambda x: y\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/return.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_38.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_39.py","code":"while x:\n ...\n\nwhile (x > 1) and y:\n pass\nelse:\n ...\n\nwhile x and y:\n ...\n print('Hello World!')\n\nelse:\n print('Olá, Mundo!')\n ...\n\nwhile a := b: ...\nwhile (a := b) and c: ...\nwhile lambda x: x: ...\nwhile await x: ...\n\nif True:\n while x:\n pass\n else:\n pass\nelse:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/while.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.13","idiom_id":"annotated","pep":"593","introduced_in":"3.9","form":"modern","file":"annotated/modern_01.py","code":"\"\"\"\nTests the typing.Annotated special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#annotated\n\n# > The first argument to Annotated must be a valid type\n\nfrom dataclasses import InitVar, dataclass\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Literal,\n NotRequired,\n Required,\n TypeAlias,\n TypeVar,\n TypedDict,\n Union,\n)\n\nT = TypeVar(\"T\")\n\n\nGood1: Annotated[Union[int, str], \"\"]\nGood2: Annotated[int | None, \"\"]\nGood3: Annotated[list[int], \"\"]\nGood4: Annotated[Any, \"\"]\nGood5: Annotated[tuple[int, ...] | list[int], \"\"]\nGood6: Annotated[Callable[..., int], \"\"]\nGood7: Annotated[\"int | str\", \"\"]\nGood8: Annotated[list[\"int | str\"], \"\"]\n\n\nBad1: Annotated[[int, str], \"\"] # E: invalid type expression\nBad2: Annotated[((int, str),), \"\"] # E: invalid type expression\nBad3: Annotated[[int for i in range(1)], \"\"] # E: invalid type expression\nBad4: Annotated[{\"a\": \"b\"}, \"\"] # E: invalid type expression\nBad5: Annotated[(lambda: int)(), \"\"] # E: invalid type expression\nBad6: Annotated[[int][0], \"\"] # E: invalid type expression\nBad7: Annotated[int if 1 < 3 else str, \"\"] # E: invalid type expression\nBad8: Annotated[var1, \"\"] # E: invalid type expression\nBad9: Annotated[True, \"\"] # E: invalid type expression\nBad10: Annotated[1, \"\"] # E: invalid type expression\nBad11: Annotated[list or set, \"\"] # E: invalid type expression\nBad12: Annotated[f\"{'int'}\", \"\"] # E: invalid type expression\n\n\n# > Multiple type annotations are supported (Annotated supports variadic arguments):\n\nMulti1: Annotated[int | str, 3, \"\"]\nMulti2: Annotated[int | str, 3, \"\", lambda x: x, max(1, 2)]\n\n# > Annotated must be called with at least two arguments ( Annotated[int] is not valid)\n\nBad13: Annotated[int] # E: requires at least two arguments\n\n\n# > Annotated types can be nested\n\nNested1: list[Annotated[dict[str, Annotated[str, \"\"]], \"\"]]\nNested2: Annotated[list[Annotated[dict[str, Annotated[Literal[1, 2, 3], \"\"]], \"\"]], \"\"]\n\n\n# > Annotated is not type compatible with type or type[T]\nSmallInt: TypeAlias = Annotated[int, \"\"]\n\nnot_type1: type[Any] = Annotated[int, \"\"] # E\nnot_type2: type[Any] = SmallInt # E\n\n\ndef func4(x: type[T]) -> T:\n return x()\n\n\nfunc4(Annotated[str, \"\"]) # E\nfunc4(SmallInt) # E\n\n\n# > An attempt to call Annotated (whether parameterized or not) should be\n# > treated as a type error by type checkers.\n\nAnnotated() # E\nAnnotated[int, \"\"]() # E\nSmallInt(1) # E\n\n\nclass ClassA:\n a: ClassVar[Annotated[int, \"\"]] = 1\n b: Annotated[ClassVar[int], \"\"] = 1\n c: Final[Annotated[int, \"\"]] = 1\n d: Annotated[Final[int], \"\"] = 1\n\n\n@dataclass\nclass ClassB:\n a: InitVar[Annotated[int, \"\"]]\n b: Annotated[InitVar[int], \"\"]\n\n\nclass ClassC(TypedDict):\n a: Annotated[Required[int], \"\"]\n b: Required[Annotated[int, \"\"]]\n c: Annotated[NotRequired[int], \"\"]\n d: NotRequired[Annotated[int, \"\"]]\n\n\nTA1: TypeAlias = Annotated[int | str, \"\"]\nTA2 = Annotated[Literal[1, 2], \"\"]\nTA3 = Annotated[T, \"\"]\n","source":"typing_tests","origin":"conformance/tests/qualifiers_annotated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_07.py","code":"\"\"\"\nTests the handling of builtins.type[T].\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#type\n\n\nfrom typing import Any, Callable, Generic, Type, TypeAlias, TypeVar, assert_type\n\n\nclass User:\n ...\n\n\nclass BasicUser(User):\n ...\n\n\nclass ProUser(User):\n ...\n\n\nclass TeamUser(User):\n ...\n\n\ndef func1(user_class: type) -> User:\n return user_class()\n\n\ndef func2(user_class: type[User]) -> User:\n return user_class()\n\n\nU = TypeVar(\"U\", bound=User)\n\n\ndef func3(user_class: type[U]) -> U:\n return user_class()\n\n\nassert_type(func1(TeamUser), User)\nassert_type(func2(TeamUser), User)\nassert_type(func3(TeamUser), TeamUser)\n\n\n# > Note that it is legal to use a union of classes as the parameter for type[].\n\n\ndef func4(user_class: type[BasicUser | ProUser]) -> User:\n return user_class()\n\n\nassert_type(func4(BasicUser), User)\nassert_type(func4(ProUser), User)\nfunc4(TeamUser) # E\n\n\n# > Any other special constructs like Callable are not allowed as an argument to type.\n\nT = TypeVar(\"T\")\n\n\ndef func5(x: type[T]) -> None:\n pass\n\n\nfunc5(User) # OK\nfunc5(tuple) # OK\nfunc5(Callable) # E\n\n\n# > When type is parameterized it requires exactly one parameter. Plain type\n# > without brackets, the root of Python’s metaclass hierarchy, is equivalent to type[Any].\n\nbad_type1: type[int, str] # E\n\n\nclass MyMetaA(type):\n ...\n\n\ndef func6(a: type, b: type[Any]):\n assert_type(a, type[Any])\n a = b # OK\n b = a # OK\n a = type # OK\n b = type # OK\n\n\n# > Regarding the behavior of type[Any] (or type), accessing attributes of a\n# > variable with this type only provides attributes and methods defined by\n# > type (for example, __repr__() and __mro__). Such a variable can be called\n# > with arbitrary arguments, and the return type is Any.\n\n\ndef func7(a: type, b: type[Any], c: Type, d: Type[Any]):\n assert_type(a.__mro__, tuple[type, ...])\n assert_type(a.unknown, Any)\n assert_type(a.unknown(), Any)\n\n assert_type(b.__mro__, tuple[type, ...])\n assert_type(b.unknown, Any)\n assert_type(b.unknown(), Any)\n\n assert_type(c.__mro__, tuple[type, ...])\n assert_type(c.unknown, Any)\n assert_type(c.unknown(), Any)\n\n assert_type(d.__mro__, tuple[type, ...])\n assert_type(d.unknown, Any)\n assert_type(d.unknown(), Any)\n\n\ndef func8(a: type[object], b: Type[object]):\n assert_type(a.__name__, str)\n a.unknown # E\n\n assert_type(b.__name__, str)\n b.unknown # E\n\n\n# > type is covariant in its parameter, because type[Derived] is a subtype of type[Base]:\n\n\ndef func9(pro_user_class: type[ProUser]):\n assert_type(func3(pro_user_class), ProUser)\n\n\nTA1: TypeAlias = Type\nTA2: TypeAlias = Type[Any]\nTA3: TypeAlias = type\nTA4: TypeAlias = type[Any]\n\n\ndef func10(a: TA1, b: TA2, c: TA3, d: TA4):\n assert_type(a, type[Any])\n assert_type(b, type[Any])\n assert_type(c, type[Any])\n assert_type(d, type[Any])\n\n\nTA1.unknown # E\nTA2.unknown # E\nTA3.unknown # E\nTA4.unknown # E\n\nTA7: TypeAlias = type[T]\nTA8: TypeAlias = Type[T]\n\n\ndef func11(t1: TA7[T]) -> T:\n return t1()\n\n\ndef func12(t1: TA8[T]) -> T:\n return t1()\n\n\nassert_type(func11(int), int)\nassert_type(func12(int), int)\n\n\ndef func13(v: type):\n x1: Callable[..., Any] = v # OK\n x2: Callable[[int, int], int] = v # OK\n x3: object = v # OK\n x4: type = v # OK\n x5: type[int] = v # OK\n x6: type[Any] = v # OK\n\n\nclass ClassA(Generic[T]):\n def method1(self, v: type) -> type[T]:\n return v # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_type.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_08.py","code":"\"\"\"\nTests the handling of builtins.tuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#tuple-type-form\n\n# > The type of a tuple can be expressed by listing the element types.\nfrom typing import Literal\n\n\nt1: tuple[int] = (1,) # OK\nt1 = (1, 2) # E\nt2: tuple[int, int] = (1, 2) # OK\nt2 = (1,) # E\nt2 = (1, \"\") # E\n\n\ndef func1() -> tuple[Literal[1], Literal[2]]:\n return (1, 2)\n\n\n# > The empty tuple can be typed as tuple[()].\n\nt10: tuple[()] = () # OK\nt10 = (1,) # E\n\n\ndef func2() -> list[tuple[()]]:\n return [(), (), ()]\n\n\n# > Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis.\nt20: tuple[int, ...] = () # OK\nt20 = (1,) # OK\nt20 = (1, 2, 3, 4) # OK\nt20 = (1, 2, 3, \"\") # E\n\n\nt30: tuple[int, ...] # OK\nt31: tuple[int, int, ...] # E\nt32: tuple[...] # E\nt33: tuple[..., int] # E\nt34: tuple[int, ..., int] # E\nt35: tuple[*tuple[str], ...] # E\nt36: tuple[*tuple[str, ...], ...] # E\n","source":"typing_tests","origin":"conformance/tests/tuples_type_form.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_01.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a base class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Generic, TypeVar, dataclass_transform\n\nT = TypeVar(\"T\")\n\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelBase:\n not_a_field: str\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n def __init__(self, not_a_field: str) -> None:\n self.not_a_field = not_a_field\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen dataclass cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass GenericModelBase(Generic[T]):\n not_a_field: T\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass GenericCustomer(GenericModelBase[int]):\n id: int = model_field()\n\n\ngc_1 = GenericCustomer(id=3)\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelBaseFrozen:\n not_a_field: str\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_02.py","code":"\"\"\"\nTests the dataclass_transform mechanism supports the \"converter\" parameter\nin a field specifier class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#converters\n\nfrom typing import (\n Any,\n Callable,\n TypeVar,\n dataclass_transform,\n overload,\n)\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n\ndef model_field(\n *,\n converter: Callable[[S], T],\n default: S | None = None,\n default_factory: Callable[[], S] | None = None,\n) -> T:\n raise NotImplementedError\n\n\n@dataclass_transform(field_specifiers=(model_field,))\nclass ModelBase:\n ...\n\n\n# > The converter must be a callable that must accept a single positional\n# > argument (but may accept other optional arguments, which are ignored for\n# > typing purposes).\n\n\ndef bad_converter1() -> int:\n return 0\n\n\ndef bad_converter2(*, x: int) -> int:\n return 0\n\n\nclass DC1(ModelBase):\n field1: int = model_field(converter=bad_converter1) # E\n field2: int = model_field(converter=bad_converter2) # E\n\n\n# > The type of the first positional parameter provides the type of the\n# > synthesized __init__ parameter for the field.\n\n# > The return type of the callable must be assignable to the field’s\n# > declared type.\n\n\ndef converter_simple(s: str) -> int:\n return int(s)\n\n\ndef converter_with_param_before_args(s: str, *args: int, **kwargs: int) -> int:\n return int(s)\n\n\ndef converter_with_args(*args: str) -> int:\n return int(args[0])\n\n\n@overload\ndef overloaded_converter(s: str) -> int:\n ...\n\n\n@overload\ndef overloaded_converter(s: list[str]) -> int:\n ...\n\n\ndef overloaded_converter(s: str | list[str], *args: str) -> int | str:\n return 0\n\n\nclass ConverterClass:\n @overload\n def __init__(self, val: str) -> None:\n ...\n\n @overload\n def __init__(self, val: bytes) -> None:\n ...\n\n def __init__(self, val: str | bytes) -> None:\n pass\n\n\nclass DC2(ModelBase):\n field0: int = model_field(converter=converter_simple)\n field1: int = model_field(converter=converter_with_param_before_args)\n field2: int = model_field(converter=converter_with_args)\n field3: ConverterClass = model_field(converter=ConverterClass)\n field4: int = model_field(converter=overloaded_converter)\n field5: dict[str, str] = model_field(converter=dict, default=())\n\n\nDC2(1, \"f1\", \"f2\", b\"f3\", []) # E\nDC2(\"f0\", \"f1\", \"f2\", 1, []) # E\nDC2(\"f0\", \"f1\", \"f2\", \"f3\", 3j) # E\n\n\ndc1 = DC2(\"f0\", \"f1\", \"f2\", b\"f6\", [])\n\ndc1.field0 = \"f1\"\ndc1.field3 = \"f6\"\ndc1.field3 = b\"f6\"\n\ndc1.field0 = 1 # E\ndc1.field3 = 1 # E\n\ndc2 = DC2(\"f0\", \"f1\", \"f2\", \"f6\", \"1\", ((\"a\", \"1\"), (\"b\", \"2\")))\n\n\n# > If default or default_factory are provided, the type of the default value\n# > should be assignable to the first positional parameter of the converter.\n\n\nclass DC3(ModelBase):\n field0: int = model_field(converter=converter_simple, default=\"\")\n field1: int = model_field(converter=converter_simple, default=1) # E\n\n field2: int = model_field(converter=converter_simple, default_factory=str)\n field3: int = model_field(converter=converter_simple, default_factory=int) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_converter.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_03.py","code":"\"\"\"\nTests the dataclass_transform mechanism honors implicit default values\nin field parameters.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#field-specifier-parameters\n\nfrom typing import Any, Callable, Literal, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n# > Field specifier functions can use overloads that implicitly specify the\n# > value of init using a literal bool value type (Literal[False] or Literal[True]).\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any],\n init: Literal[False] = False,\n) -> Any:\n ...\n\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: None = None,\n init: Literal[True] = True,\n) -> Any:\n ...\n\n\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any] | None = None,\n init: bool = True,\n) -> Any:\n ...\n\n\ndef field2(*, init: bool = False, kw_only: bool = True) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(kw_only_default=True, field_specifiers=(field1, field2))\ndef create_model(*, init: bool = True) -> Callable[[type[T]], type[T]]:\n raise NotImplementedError\n\n\n@create_model()\nclass CustomerModel1:\n id: int = field1(resolver=lambda: 0)\n name: str = field1(default=\"Voldemort\")\n\n\nCustomerModel1()\nCustomerModel1(name=\"hi\")\n\n# This should generate an error because \"id\" is not\n# supposed to be part of the init function.\nCustomerModel1(id=1, name=\"hi\") # E\n\n\n@create_model()\nclass CustomerModel2:\n id: int = field2()\n name: str = field2(init=True)\n\n\n# This should generate an error because kw_only is True\n# by default for field2.\nCustomerModel2(1) # E\n\nCustomerModel2(name=\"Fred\")\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_field.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_04.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a decorator function.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Callable, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n\n@overload\n@dataclass_transform(kw_only_default=True, order_default=True)\ndef create_model(cls: T) -> T:\n ...\n\n\n@overload\ndef create_model(\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n) -> Callable[[T], T]:\n ...\n\n\ndef create_model(*args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n\n@create_model(kw_only=False, order=False)\nclass Customer1:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2Subclass(Customer2):\n salary: float\n\n\nc1_1 = Customer1(id=3, name=\"Sue\")\nc1_1.id = 4\n\nc1_2 = Customer1(3, \"Sue\")\nc1_2.name = \"Susan\"\n\n# This should generate an error because of a type mismatch.\nc1_2.name = 3 # E\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\n# This should generate an error because salary is not\n# a defined field.\nc1_3 = Customer1(id=3, name=\"Sue\", salary=40000) # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_2 = Customer2(0, \"John\") # E\n\nv2 = c2_1 < c2_2\n\n\n@dataclass_transform(kw_only_default=True, order_default=True, frozen_default=True)\ndef create_model_frozen(cls: T) -> T:\n raise NotImplementedError\n\n\n@create_model_frozen\nclass Customer3:\n id: int\n name: str\n\n\n# This should generate an error because a non-frozen class\n# cannot inherit from a frozen class.\n@create_model # E[Customer3Subclass]\nclass Customer3Subclass(Customer3): # E[Customer3Subclass]\n age: int\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_func.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_05.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a metaclass.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\n\nfrom typing import Any, dataclass_transform\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelMeta(type):\n not_a_field: str\n\n def __init__(self, *args, **kwargs) -> None:\n self.not_a_field: str = \"not a field\"\n\n\nclass ModelBase(metaclass=ModelMeta):\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen class cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1, frozen=False): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\n# OK (other_name is optional).\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelMetaFrozen(type):\n pass\n\n\nclass ModelBaseFrozen(metaclass=ModelMetaFrozen):\n ...\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_meta.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_07.py","code":"\"\"\"\nTests the handling of descriptors within a dataclass.\n\"\"\"\n\n# This portion of the dataclass spec is under-specified in the documentation,\n# but its behavior can be determined from the runtime implementation.\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, TypeVar, assert_type, overload\n\nT = TypeVar(\"T\")\n\n\nclass Desc1:\n @overload\n def __get__(self, __obj: None, __owner: Any) -> \"Desc1\":\n ...\n\n @overload\n def __get__(self, __obj: object, __owner: Any) -> int:\n ...\n\n def __get__(self, __obj: object | None, __owner: Any) -> \"int | Desc1\":\n raise NotImplementedError\n\n def __set__(self, __obj: object, __value: int) -> None:\n ...\n\n\n@dataclass\nclass DC1:\n y: Desc1 = Desc1()\n\n\ndc1 = DC1(3)\n\nassert_type(dc1.y, int)\nassert_type(DC1.y, Desc1)\n\n\nclass Desc2(Generic[T]):\n @overload\n def __get__(self, instance: None, owner: Any) -> list[T]:\n ...\n\n @overload\n def __get__(self, instance: object, owner: Any) -> T:\n ...\n\n def __get__(self, instance: object | None, owner: Any) -> list[T] | T:\n raise NotImplementedError\n\n\n@dataclass\nclass DC2:\n x: Desc2[int]\n y: Desc2[str]\n z: Desc2[str] = Desc2()\n\n\nassert_type(DC2.x, list[int])\nassert_type(DC2.y, list[str])\nassert_type(DC2.z, list[str])\n\ndc2 = DC2(Desc2(), Desc2(), Desc2())\nassert_type(dc2.x, int)\nassert_type(dc2.y, str)\nassert_type(dc2.z, str)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_descriptors.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_08.py","code":"\"\"\"\nTests validation of frozen dataclass instances.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#frozen-instances\n\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass DC1:\n a: float\n b: str\n\ndc1 = DC1(1, \"\")\n\ndc1.a = 1 # E: dataclass is frozen\ndc1.b = \"\" # E: dataclass is frozen\n\n\n# This should generate an error because a non-frozen dataclass\n# cannot inherit from a frozen dataclass.\n@dataclass # E[DC2]\nclass DC2(DC1): # E[DC2]\n pass\n\n@dataclass\nclass DC3:\n a: int\n\n# This should generate an error because a frozen dataclass\n# cannot inherit from a non-frozen dataclass.\n@dataclass(frozen=True) # E[DC4]\nclass DC4(DC3): # E[DC4]\n pass\n\n\n@dataclass(frozen=True)\nclass DC1Child(DC1):\n # This should be allowed because attributes within a frozen\n # dataclass are covariant rather than invariant.\n a: int\n","source":"typing_tests","origin":"conformance/tests/dataclasses_frozen.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_09.py","code":"\"\"\"\nTests the synthesis of the __hash__ method in a dataclass.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Callable, Hashable, assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n\n\nassert_type(DC1.__hash__, None)\n\n# These should generate errors because DC1 isn't hashable.\nDC1(0).__hash__() # E\nv1: Hashable = DC1(0) # E\n\n\n@dataclass(eq=True, frozen=True)\nclass DC2:\n a: int\n\n\ndc2_hash: Callable[..., int] = DC2.__hash__ # OK\nDC2(0).__hash__() # OK\nv2: Hashable = DC2(0) # OK\n\n\n@dataclass(eq=True)\nclass DC3:\n a: int\n\n\nassert_type(DC3.__hash__, None)\n\n# These should generate errors because DC3 isn't hashable.\nDC3(0).__hash__() # E\nv3: Hashable = DC3(0) # E\n\n\n@dataclass(frozen=True)\nclass DC4:\n a: int\n\n\ndc4_hash: Callable[..., int] = DC4.__hash__ # OK\nDC4(0).__hash__() # OK\nv4: Hashable = DC4(0) # OK\n\n\n@dataclass(eq=True, unsafe_hash=True)\nclass DC5:\n a: int\n\n\ndc5_hash: Callable[..., int] = DC5.__hash__ # OK\nDC5(0).__hash__() # OK\nv5: Hashable = DC5(0) # OK\n\n\n@dataclass(eq=True)\nclass DC6:\n a: int\n\n def __hash__(self) -> int:\n return 0\n\n\ndc6_hash: Callable[..., int] = DC6.__hash__ # OK\nDC6(0).__hash__() # OK\nv6: Hashable = DC6(0) # OK\n\n\n@dataclass(frozen=True)\nclass DC7:\n a: int\n\n def __eq__(self, other) -> bool:\n return self.a == other.a\n\n\ndc7_hash: Callable[..., int] = DC7.__hash__ # OK\nDC7(0).__hash__() # OK\nv7: Hashable = DC7(0) # OK\n","source":"typing_tests","origin":"conformance/tests/dataclasses_hash.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_10.py","code":"\"\"\"\nTests inheritance rules for dataclasses.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#inheritance\n\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar\n\n\n@dataclass\nclass DC1:\n a: int\n b: str = \"\"\n\n\n@dataclass\nclass DC2(DC1):\n b: str = \"\"\n a: int = 1\n\n\ndc2_1 = DC2(1, \"\")\n\ndc2_2 = DC2()\n\n\n@dataclass\nclass DC3:\n x: float = 15.0\n y: str = \"\"\n\n\n@dataclass\nclass DC4(DC3):\n z: tuple[int] = (10,)\n x: float = 15\n\n\ndc4_1 = DC4(0.0, \"\", (1,))\n\n\n@dataclass\nclass DC5:\n # While this generates an error at runtime for the stdlib dataclass,\n # other libraries that use dataclass_transform don't have similar\n # restrictions. It is therefore not required that a type checker\n # report an error here.\n x: list[int] = [] # E?\n\n\n@dataclass\nclass DC6:\n x: int\n y: ClassVar[int] = 1\n\n\n@dataclass\nclass DC7(DC6):\n # This should generate an error because a ClassVar cannot override\n # an instance variable of the same name.\n x: ClassVar[int] # E\n\n # This should generate an error because an instance variable cannot\n # override a class variable of the same name.\n y: int # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_11.py","code":"\"\"\"\nTests the keyword-only feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY, field\n\n\n@dataclass\nclass DC1:\n a: str\n _: KW_ONLY\n b: int = 0\n\n\nDC1(\"hi\")\nDC1(a=\"hi\")\nDC1(a=\"hi\", b=1)\nDC1(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC1(\"hi\", 1) # E\n\n\n@dataclass\nclass DC2:\n b: int = field(kw_only=True, default=3)\n a: str\n\n\nDC2(\"hi\")\nDC2(a=\"hi\")\nDC2(a=\"hi\", b=1)\nDC2(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC2(\"hi\", 1) # E\n\n\n@dataclass(kw_only=True)\nclass DC3:\n a: str = field(kw_only=False)\n b: int = 0\n\n\nDC3(\"hi\")\nDC3(a=\"hi\")\nDC3(a=\"hi\", b=1)\nDC3(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC3(\"hi\", 1) # E\n\n\n@dataclass\nclass DC4(DC3):\n c: float\n\n\nDC4(\"\", 0.2, b=3)\nDC4(a=\"\", b=3, c=0.2)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_kwonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_12.py","code":"\"\"\"\nTests the match_args feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY\nfrom typing import assert_type, Literal\n\n# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method\n\n@dataclass(match_args=True)\nclass DC1:\n x: int\n _: KW_ONLY\n y: str\n\nassert_type(DC1.__match_args__, tuple[Literal['x']])\n\n# The match_args default is True\n\n@dataclass\nclass DC2:\n x: int\n\nassert_type(DC2.__match_args__, tuple[Literal['x']])\n\n# __match_args__ is created even if __init__() is not generated\n\n@dataclass(match_args=True, init=False)\nclass DC3:\n x: int = 0\n\nassert_type(DC3.__match_args__, tuple[Literal['x']])\n\n# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.\n\n@dataclass(match_args=False)\nclass DC4:\n x: int\n\nDC4.__match_args__ # E\n\n@dataclass(match_args=True)\nclass DC5:\n __match_args__ = ()\n x: int\n\nassert_type(DC5.__match_args__, tuple[()])\n","source":"typing_tests","origin":"conformance/tests/dataclasses_match_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_13.py","code":"\"\"\"\nTests the synthesized comparison methods for dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass DC1:\n a: str\n b: int\n\n\n@dataclass(order=True)\nclass DC2:\n a: str\n b: int\n\n\ndc1_1 = DC1(\"\", 0)\ndc1_2 = DC1(\"\", 0)\n\nif dc1_1 < dc1_2:\n pass\n\nif dc1_1 <= dc1_2:\n pass\n\nif dc1_1 > dc1_2:\n pass\n\nif dc1_1 >= dc1_2:\n pass\n\nif dc1_1 == dc1_2:\n pass\n\nif dc1_1 != dc1_2:\n pass\n\nif dc1_1 == None:\n pass\n\nif dc1_1 != None:\n pass\n\ndc2_1 = DC2(\"hi\", 2)\n\n# This should generate an error because the types are\n# incompatible.\nif dc1_1 < dc2_1: # E:\n pass\n\nif dc1_1 != dc2_1:\n pass\n","source":"typing_tests","origin":"conformance/tests/dataclasses_order.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_14.py","code":"\"\"\"\nTests type checking of the __post_init__ method in a dataclass.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#post-init-processing\n\nfrom dataclasses import InitVar, dataclass, field, replace\nfrom typing import assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n b: int\n x: InitVar[int]\n c: int\n y: InitVar[str]\n\n def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y\n pass\n\n\ndc1 = DC1(1, 2, 3, 4, \"\")\n\nassert_type(dc1.a, int)\nassert_type(dc1.b, int)\nassert_type(dc1.c, int)\nprint(dc1.x) # E: cannot access InitVar\nprint(dc1.y) # E: cannot access InitVar\n\n@dataclass\nclass DC2:\n x: InitVar[int]\n y: InitVar[str]\n\n def __post_init__(self, x: int) -> None: # E: missing y\n pass\n\n\n@dataclass\nclass DC3:\n _name: InitVar[str] = field()\n name: str = field(init=False)\n\n def __post_init__(self, _name: str):\n ...\n\n\n@dataclass\nclass DC4(DC3):\n _age: InitVar[int] = field()\n age: int = field(init=False)\n\n def __post_init__(self, _name: str, _age: int):\n ...\n","source":"typing_tests","origin":"conformance/tests/dataclasses_postinit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_15.py","code":"\"\"\"\nTests the slots functionality of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass\n\n# This should generate an error because __slots__ is already defined.\n@dataclass(slots=True) # E[DC1]\nclass DC1: # E[DC1]\n x: int\n\n __slots__ = ()\n\n\n@dataclass(slots=True)\nclass DC2:\n x: int\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass(slots=False)\nclass DC3:\n x: int\n\n __slots__ = (\"x\",)\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass\nclass DC4:\n __slots__ = (\"y\", \"x\")\n x: int\n y: str\n\n\nDC4(1, \"bar\")\n\n\n@dataclass(slots=True)\nclass DC5:\n a: int\n\n\nDC5.__slots__\nDC5(1).__slots__\n\n\n@dataclass\nclass DC6:\n a: int\n\n\n# This should generate an error because __slots__ is not defined.\nDC6.__slots__ # E\n\n# This should generate an error because __slots__ is not defined.\nDC6(1).__slots__ # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_slots.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_16.py","code":"\"\"\"\nTests basic handling of the dataclass factory.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html\n# Also, see https://peps.python.org/pep-0557/\n\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar, assert_type\nimport sys\n\nT = TypeVar(\"T\")\n\n\n@dataclass(order=True)\nclass InventoryItem:\n x = 0\n name: str\n unit_price: float\n quantity_on_hand: int = 0\n\n def total_cost(self) -> float:\n return self.unit_price * self.quantity_on_hand\n\n\nv1 = InventoryItem(\"soap\", 2.3)\n\n\nclass InventoryItemInitProto(Protocol):\n def __call__(\n self, name: str, unit_price: float, quantity_on_hand: int = ...\n ) -> None: ...\n\n\n# Validate the type of the synthesized __init__ method.\nx1: InventoryItemInitProto = v1.__init__\n\n# Make sure the following additional methods were synthesized.\nprint(v1.__repr__)\nprint(v1.__eq__)\nprint(v1.__ne__)\nprint(v1.__lt__)\nprint(v1.__le__)\nprint(v1.__gt__)\nprint(v1.__ge__)\n\nassert_type(v1.name, str)\nassert_type(v1.unit_price, float)\nassert_type(v1.quantity_on_hand, int)\n\nv2 = InventoryItem(\"name\") # E: missing unit_price\nv3 = InventoryItem(\"name\", \"price\") # E: incorrect type for unit_price\nv4 = InventoryItem(\"name\", 3.1, 3, 4) # E: too many arguments\n\n\n# > TypeError will be raised if a field without a default value follows a\n# > field with a default value. This is true either when this occurs in a\n# > single class, or as a result of class inheritance.\n@dataclass # E[DC1]\nclass DC1:\n a: int = 0 # E[DC1]: field with default should follow a field with no default.\n b: int # E[DC1]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC2]\nclass DC2:\n a: int = field(default=1) # E[DC2]: field with default should follow a field with no default.\n b: int # E[DC2]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC3]\nclass DC3:\n a: InitVar[int] = 0 # E[DC3]: field with default should follow a field with no default.\n b: int # E[DC3]: field with no default cannot follow field with default.\n\n\n@dataclass\nclass DC4:\n a: int = field(init=False)\n b: int\n\n\nv5 = DC4(0)\nv6 = DC4(0, 1) # E: too many parameters\n\n\n@dataclass\nclass DC5:\n a: int = field(default_factory=str) # E: type mismatch\n\n\ndef f(s: str) -> int:\n return int(s)\n\n\n@dataclass\nclass DC6:\n a: ClassVar[int] = 0\n b: str\n c: Callable[[str], int] = f\n\n\ndc6 = DC6(\"\")\nassert_type(dc6.a, int)\nassert_type(DC6.a, int)\nassert_type(dc6.b, str)\nassert_type(dc6.c, Callable[[str], int])\n\n\n@dataclass\nclass DC7:\n x: int\n\n\n@dataclass(init=False)\nclass DC8(DC7):\n y: int\n\n def __init__(self, a: DC7, y: int):\n self.__dict__ = a.__dict__\n self.y = y\n\n\na = DC7(3)\nb = DC8(a, 5)\n\n# This should generate an error because there is an extra parameter\nDC7(3, 4) # E\n\n# This should generate an error because there is one too few parameters\nDC8(a) # E\n\n\n@dataclass\nclass DC9:\n a: str = field(init=False, default=\"s\")\n b: bool = field()\n\n\n@dataclass\nclass DC10(DC9):\n a: str = field()\n b: bool = field()\n\n\n@dataclass(init=False)\nclass DC11:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC11(3)\n\n\n@dataclass(init=True)\nclass DC12:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC12(3)\n\n\n@dataclass(init=False)\nclass DC13:\n x: int\n x_squared: int\n\n\n# This should generate an error because there is no matching\n# override __init__ method and no synthesized __init__.\nDC13(3) # E\n\n\n@dataclass\nclass DC14:\n prop_1: str = field(init=False)\n prop_2: str = field(default=\"hello\")\n prop_3: str = field(default_factory=lambda: \"hello\")\n\n\n@dataclass\nclass DC15(DC14):\n prop_2: str = \"\"\n\n\ndc15 = DC15(prop_2=\"test\")\n\nassert_type(dc15.prop_1, str)\nassert_type(dc15.prop_2, str)\nassert_type(dc15.prop_3, str)\n\n\nclass DataclassProto(Protocol):\n __dataclass_fields__: ClassVar[dict[str, Any]]\n\n\nv7: DataclassProto = dc15\n\n\n@dataclass\nclass DC16(Generic[T]):\n value: T\n\n\nassert_type(DC16(1), DC16[int])\n\n\nclass DC17(DC16[str]):\n pass\n\n\nassert_type(DC17(\"\"), DC17)\n\n\n@dataclass\nclass DC18:\n x: int = field()\n # This may generate a type checker error because an unannotated field\n # will result in a runtime exception.\n y = field() # E?\n\n\n# > Dataclass fields may be conditional, via checks of the same\n# > statically-known conditions that a type-checker understands elsewhere,\n# > such as Python version:\n\n@dataclass\nclass DC19:\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nDC19(1, 2)\nDC19(1, 2, 3) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"deprecated-decorator","pep":"702","introduced_in":"3.13","form":"modern","file":"deprecated-decorator/modern_01.py","code":"\"\"\"\nTests the warnings.deprecated function.\n\"\"\"\n\n# pyright: reportDeprecated=true\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#deprecated\n# See also https://peps.python.org/pep-0702/\n\nfrom typing import Protocol, override\nfrom typing_extensions import deprecated\n\n# > Type checkers should produce a diagnostic whenever they encounter a usage of an object\n# > marked as deprecated. [...] For deprecated classes and functions, this includes:\n\n# > * `from` imports\n\nfrom _directives_deprecated_library import Ham # E: Use of deprecated class Ham\nimport _directives_deprecated_library as library\n\n\n# > * References through module, class, or instance attributes\n\nlibrary.norwegian_blue(1) # E: Use of deprecated function norwegian_blue\nmap(library.norwegian_blue, [1, 2, 3]) # E: Use of deprecated function norwegian_blue\n\n\n# > For deprecated overloads, this includes all calls that resolve to the deprecated overload.\n\nlibrary.foo(1) # E: Use of deprecated overload for foo\nlibrary.foo(\"x\") # OK\n\n\nham = Ham() # E?: OK (already reported above)\n\n\n# > * Any syntax that indirectly triggers a call to the function.\n\nspam = library.Spam()\n\n_ = spam + 1 # E: Use of deprecated method Spam.__add__\nspam += 1 # E: Use of deprecated method Spam.__add__\n\nspam.greasy # E: Use of deprecated property Spam.greasy\nspam.shape # OK\n\nspam.shape = \"cube\" # E: Use of deprecated property setter Spam.shape\nspam.shape += \"cube\" # E: Use of deprecated property setter Spam.shape\n\n\nclass Invocable:\n @deprecated(\"Deprecated\")\n def __call__(self) -> None:\n ...\n\n\ninvocable = Invocable()\ninvocable() # E: Use of deprecated method __call__\n\n\n# > * Any usage of deprecated objects in their defining module\n\n\n@deprecated(\"Deprecated\")\ndef lorem() -> None:\n ...\n\n\nlorem() # E: Use of deprecated function lorem\n\n\n# > There are additional scenarios where deprecations could come into play.\n# > For example, an object may implement a `typing.Protocol`,\n# > but one of the methods required for protocol compliance is deprecated.\n# > As scenarios such as this one appear complex and relatively unlikely to come up in practice,\n# > this PEP does not mandate that type checkers detect them.\n\n\nclass SupportsFoo1(Protocol):\n @deprecated(\"Deprecated\")\n def foo(self) -> None:\n ...\n\n def bar(self) -> None:\n ...\n\n\nclass FooConcrete1(SupportsFoo1):\n @override\n def foo(self) -> None: # E?: Implementation of deprecated method foo\n ...\n\n def bar(self) -> None:\n ...\n\n\ndef foo_it(f: SupportsFoo1) -> None:\n f.foo() # E: Use of deprecated method foo\n f.bar()\n\n\nclass SupportsFoo2(Protocol):\n def foo(self) -> None:\n ...\n\n\nclass FooConcrete2:\n @deprecated(\"Deprecated\")\n def foo(self) -> None:\n ...\n\n\ndef takes_foo(f: SupportsFoo2) -> None:\n ...\n\n\ndef caller(c: FooConcrete2) -> None:\n takes_foo(\n c\n ) # E?: FooConcrete2 is a SupportsFoo2, but only because of a deprecated method\n","source":"typing_tests","origin":"conformance/tests/directives_deprecated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_01.py","code":"\"\"\"\nTests the handling of ClassVar and Final in dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import assert_type, ClassVar, Final\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#dataclass-semantics\n\n# > A final class variable on a dataclass must be explicitly annotated as\n# e.g. x: ClassVar[Final[int]] = 3.\n\n\n@dataclass\nclass D:\n final_no_default: Final[int]\n final_with_default: Final[str] = \"foo\"\n final_classvar: ClassVar[Final[int]] = 4\n # we don't require support for Final[ClassVar[...]] because the dataclasses\n # runtime implementation won't recognize it as a ClassVar either\n\n\n# An explicitly marked ClassVar can be accessed on the class:\nassert_type(D.final_classvar, int)\n\n# ...but not assigned to, because it's Final:\nD.final_classvar = 10 # E: can't assign to final attribute\n\n# A non-ClassVar attribute (with or without default) is a dataclass field:\nd = D(final_no_default=1, final_with_default=\"bar\")\nassert_type(d.final_no_default, int)\nassert_type(d.final_with_default, str)\n\n# ... but can't be assigned to (on the class or on an instance):\nd.final_no_default = 10 # E: can't assign to final attribute\nd.final_with_default = \"baz\" # E: can't assign to final attribute\nD.final_no_default = 10 # E: can't assign to final attribute\nD.final_with_default = \"baz\" # E: can't assign to final attribute\n","source":"typing_tests","origin":"conformance/tests/dataclasses_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_02.py","code":"\"\"\"\nTests the typing.Final special form.\n\"\"\"\n\nfrom typing import ClassVar, Final, Literal, NamedTuple, TypedDict, assert_type\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#id1\n\nID1: Final[int] = 1\n\nID2: Final = 1\nassert_type(ID2, Literal[1])\n\n# > If the right hand side is omitted, there must be an explicit type argument to Final.\n\nBAD1: Final # E: missing assignment\n\nBAD2: Final[str, int] = \"\" # E: only one type argument allowed\n\n# > There can be at most one final declaration per module or class for a given\n# > attribute.\n\n# > As self.id: Final = 1 (also optionally with a type in square brackets).\n# > This is allowed only in __init__ methods, so that the final instance\n# > attribute is assigned only once when an instance is created.\n\n\nclass ClassA:\n ID1: Final = 1\n\n # > In class bodies and stub files you can omit the right hand side and just\n # > write ID: Final[float]. If the right hand side is omitted, there must be\n # > an explicit type argument to Final.\n ID2: Final # E: missing initialization\n\n # > A final attribute declared in a class body without an initializer must\n # > be initialized in the __init__ method (except in stub files):\n ID3: Final[int] # E: missing initialization\n\n ID4: Final[int] # OK because initialized in __init__\n\n ID5: Final[int] = 0\n\n ID6: Final[int]\n\n ID7: Final[int] = 0\n\n def __init__(self, cond: bool) -> None:\n self.id1: Final = 1\n self.id2: Final[int] = 1\n\n self.ID4 = 1\n\n self.ID5 = 0 # E: Already initialized\n\n if cond:\n self.ID6 = 1\n else:\n self.ID6 = 2\n\n def method1(self) -> None:\n self.id3: Final = 1 # E: not allowed outside of __init__ method.\n self.id4: Final[int] = 1 # E: not allowed outside of __init__ method.\n\n self.ID7 = 0 # E: cannot modify Final value\n\n self.ID7 += 1 # E: cannot modify Final value\n\n\nRATE: Final = 3000\nRATE = 300 # E: Cannot redefine Final value\n\n# > There can’t be separate class-level and instance-level constants\n# > with the same name.\n\n\nclass ClassB:\n DEFAULT_ID: Final = 0\n\n\nClassB.DEFAULT_ID = 0 # E: Cannot redefined value\n\n\n# > A type checker should prevent final attributes from being overridden in a subclass:\n\n\nclass ClassC:\n BORDER_WIDTH: Final = 2.5\n\n __private: Final = 0\n\n\nclass ClassCChild(ClassC):\n BORDER_WIDTH = 2.5 # E: Cannot override Final value\n\n __private = 0 # OK\n\n\n# > Type checkers should infer a final attribute that is initialized in a class\n# > body as being a class variable. Variables should not be annotated with both\n# > ClassVar and Final. (Except in a dataclass; see dataclasses_final.py.)\n\n\nclass ClassD:\n VALUE1: Final = 1\n\n VALUE2: ClassVar[Final] = 1 # E: Final cannot be used with ClassVar\n VALUE3: Final[ClassVar] = 1 # E: Final cannot be used with ClassVar\n\n\nClassD.VALUE1 # OK\n\n\n# > Final may only be used as the outermost type in assignments or variable\n# > annotations. Using it in any other position is an error. In particular,\n# > Final can’t be used in annotations for function arguments.\n\nx: list[Final[int]] = [] # E\n\n\ndef func1(x: Final[list[int]]) -> None: # E\n ...\n\n\n# > ``Final`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithFinal(TypedDict):\n a: int\n b: Final[int] # E: Final not allowed in a TypedDict\n\n\nclass NTWithFinal(NamedTuple):\n a: int\n b: Final[int] # E: Final not allowed in a NamedTuple\n\n\n# > Type checkers should treat uses of a final name that was initialized with\n# > a literal as if it was replaced by the literal. For example, the following\n# > should be allowed:\n\nX: Final = \"x\"\nY: Final = \"y\"\nN = NamedTuple(\"N\", [(X, int), (Y, int)])\n\nN(x=3, y=4) # OK\nN(a=1) # E\nN(x=\"\", y=\"\") # E\n\n\ndef func2() -> None:\n global ID1\n\n ID1 = 2 # E: cannot modify Final value\n\n x: Final = 3\n\n x += 1 # E: cannot modify Final value\n\n a = (x := 4) # E: cannot modify Final value\n\n for x in [1, 2, 3]: # E: cannot modify Final value\n pass\n\n with open(\"FileName\") as x: # E: cannot modify Final value\n pass\n\n (a, x) = (1, 2) # E: cannot modify Final value\n\n\n# > If a module declares a ``Final`` variable and another module imports that\n# > variable in an import statement by name or wildcard, the imported symbol\n# > inherits the ``Final`` type qualifier. Any attempt to assign a different value\n# > to this symbol should be flagged as an error by a type checker.\n\n\nfrom _qualifiers_final_annotation_1 import TEN\n\nTEN = 9 # E: Cannot redefine Final value\n\nfrom _qualifiers_final_annotation_2 import *\n\nPI = 3.14159 # E: Cannot redefine Final value\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_03.py","code":"\"\"\"\nTests the @final decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#final\n\nfrom typing import final, overload\nfrom _qualifiers_final_decorator import Base3, Base4\n\n# > A type checker should prohibit any class decorated with @final from being\n# > subclassed and any method decorated with @final from being overridden in a\n# > subclass. The method decorator version may be used with all of instance\n# > methods, class methods, static methods, and properties.\n\n\n@final\nclass Base1:\n ...\n\n\nclass Derived1(Base1): # E: Cannot inherit from final class \"Base\"\n ...\n\n\nclass Base2:\n @final\n def method1(self) -> None:\n pass\n\n @final\n @classmethod\n def method2(cls) -> None:\n pass\n\n @final\n @staticmethod\n def method3() -> None:\n pass\n\n # > For overloaded methods, @final should be placed on the implementation.\n\n @overload\n def method4(self, x: int) -> int:\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @final\n def method4(self, x: int | str) -> int | str:\n return 0\n\n\nclass Derived2(Base2):\n def method1(self) -> None: # E\n pass\n\n @classmethod # E[method2]\n def method2(cls) -> None: # E[method2]\n pass\n\n @staticmethod # E[method3]\n def method3() -> None: # E[method3]\n pass\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n def method4(self, x: int | str) -> int | str: # E[method4]\n return 0\n\n\nclass Derived3(Base3):\n @overload # E[Derived3]\n def method(self, x: int) -> int: # E[Derived3]\n ...\n\n @overload # E[Derived3-2]\n @final # E[Derived3-2]: should be applied only to implementation\n def method(self, x: str) -> str: # E[Derived3-2]\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived3]\n return 0\n\n\nclass Derived4(Base4):\n @overload # E[Derived4]\n def method(self, x: int) -> int: # E[Derived4]\n ...\n\n @overload\n def method(self, x: str) -> str:\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived4]\n return 0\n\n\nclass Base5_1:\n ...\n\n\nclass Base5_2:\n @final\n def method(self, v: int) -> None:\n ...\n\n\n# Test multiple inheritance case.\nclass Derived5(Base5_1, Base5_2):\n def method(self) -> None: # E\n ...\n\n\n# > It is an error to use @final on a non-method function.\n\n\n@final # E[func]: not allowed on non-method function.\ndef func1() -> int: # E[func]\n return 0\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_decorator.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_04.py","code":"\"\"\"\nTests the use of Final values when used with TypedDicts.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#use-of-final-values-and-literal-types\n\nfrom typing import Final, Literal, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\n# > Type checkers should allow final names (PEP 591) with string values to be\n# > used instead of string literals in operations on TypedDict objects.\nYEAR: Final = \"year\"\n\nm: Movie = {\"name\": \"Alien\", \"year\": 1979}\nyears_since_epoch = m[YEAR] - 1970\n\n\n# > An expression with a suitable literal type (PEP 586) can be used instead of\n# > a literal value.\ndef get_value(movie: Movie, key: Literal[\"year\", \"name\"]) -> int | str:\n return movie[key]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"literal-string","pep":"675","introduced_in":"3.11","form":"modern","file":"literal-string/modern_01.py","code":"\"\"\"\nTests handling of the LiteralString special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#literalstring\n\n\nfrom typing import (\n Any,\n Generic,\n Literal,\n LiteralString,\n Sequence,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nvariable_annotation: LiteralString\n\n\ndef my_function(literal_string: LiteralString) -> LiteralString:\n raise NotImplementedError\n\n\nclass Foo:\n my_attribute: LiteralString = \"\"\n\n\ntype_argument: list[LiteralString]\n\nT = TypeVar(\"T\", bound=LiteralString)\n\n\nbad_union: Literal[\"hello\", LiteralString] # E\nbad_nesting: Literal[LiteralString] # E\n\n\ndef func1(a: Literal[\"one\"], b: Literal[\"two\"]):\n x1: LiteralString = a\n\n x2: Literal[\"\"] = b # E\n\n\ndef func2(a: LiteralString, b: LiteralString, non_literal: str):\n # > Addition: x + y is of type LiteralString if both x and y are compatible with LiteralString.\n assert_type(a + b, LiteralString)\n\n # > Joining: sep.join(xs) is of type LiteralString if sep’s type is\n # > compatible with LiteralString and xs’s type is compatible with Iterable[LiteralString].\n assert_type(\",\".join((a, b)), LiteralString)\n assert_type(\",\".join((a, non_literal)), str)\n\n # > In-place addition: If s has type LiteralString and x has type compatible with\n # > LiteralString, then s += x preserves s’s type as LiteralString.\n a += \"hello\"\n b += a\n\n # > String formatting: An f-string has type LiteralString if and only if its constituent\n # > expressions are literal strings. s.format(...) has type LiteralString if and only if\n # > s and the arguments have types compatible with LiteralString.\n assert_type(f\"{a} {b}\", LiteralString)\n\n x1: LiteralString = f\"{a} {non_literal}\" # E\n\n assert_type(a + non_literal, str)\n\n # > LiteralString is compatible with the type str\n x2: str = a\n\n # > Other literal types, such as literal integers, are not compatible with LiteralString.\n x3: LiteralString = 3 # E\n x4: LiteralString = b\"test\" # E\n\n\n# > Conditional statements and expressions work as expected.\ndef condition1() -> bool:\n raise NotImplementedError\n\n\ndef return_literal_string() -> LiteralString:\n return \"foo\" if condition1() else \"bar\" # OK\n\n\ndef return_literal_str2(literal_string: LiteralString) -> LiteralString:\n return \"foo\" if condition1() else literal_string # OK\n\n\ndef return_literal_str3() -> LiteralString:\n result: LiteralString\n if condition1():\n result = \"foo\"\n else:\n result = \"bar\"\n\n return result # OK\n\n\n# > TypeVars can be bound to LiteralString.\nTLiteral = TypeVar(\"TLiteral\", bound=LiteralString)\n\n\ndef literal_identity(s: TLiteral) -> TLiteral:\n return s\n\n\ndef func3(s: Literal[\"hello\"]):\n y = literal_identity(s)\n assert_type(y, Literal[\"hello\"])\n\n\ndef func4(s: LiteralString):\n y2 = literal_identity(s)\n assert_type(y2, LiteralString)\n\n\ndef func5(s: str):\n literal_identity(s) # E\n\n\n# > LiteralString can be used as a type argument for generic classes.\nclass Container(Generic[T]):\n def __init__(self, value: T) -> None:\n self.value = value\n\n\ndef func6(s: LiteralString):\n x: Container[LiteralString] = Container(s) # OK\n\n\ndef func7(s: str):\n x_error: Container[LiteralString] = Container(s) # E\n\n\n# > Standard containers like List work as expected.\nxs: list[LiteralString] = [\"foo\", \"bar\", \"baz\"]\n\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\n\n@overload\ndef func8(x: Literal[\"foo\"]) -> C:\n ...\n\n\n@overload\ndef func8(x: LiteralString) -> B:\n ...\n\n\n@overload\ndef func8(x: str) -> A:\n ...\n\n\ndef func8(x: Any) -> Any:\n raise NotImplementedError\n\n\ndef call_func8(x: str) -> None:\n assert_type(func8(\"foo\"), C) # First overload\n assert_type(func8(\"bar\"), B) # Second overload\n assert_type(func8(x), A) # Third overload\n\n\ndef func9(val: list[LiteralString]):\n x1: list[str] = val # E\n\n\ndef func10(val: Sequence[LiteralString]):\n x1: Sequence[str] = val # OK\n","source":"typing_tests","origin":"conformance/tests/literals_literalstring.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_04.py","code":"\"\"\"\nTests interactions between Literal types and other typing features.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#interactions-with-other-types-and-features\nfrom enum import Enum\nfrom typing import IO, Any, Final, Generic, Literal, TypeVar, LiteralString, assert_type, overload\n\n\ndef func1(v: tuple[int, str, list[bool]], a: Literal[0], b: Literal[5], c: Literal[-5]):\n assert_type(v[a], int)\n assert_type(v[2], list[bool])\n\n v[b] # E: index out of range\n v[c] # E: index out of range\n v[4] # E: index out of range\n v[-4] # E: index out of range\n\n\n_PathType = str | bytes | int\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"r\", \"w\", \"a\", \"x\", \"r+\", \"w+\", \"a+\", \"x+\"],\n) -> IO[str]:\n ...\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"rb\", \"wb\", \"ab\", \"xb\", \"r+b\", \"w+b\", \"a+b\", \"x+b\"],\n) -> IO[bytes]:\n ...\n\n\n@overload\ndef open(path: _PathType, mode: str) -> IO[Any]:\n ...\n\n\ndef open(path: _PathType, mode: Any) -> Any:\n raise NotImplementedError\n\n\nassert_type(open(\"path\", \"r\"), IO[str])\nassert_type(open(\"path\", \"wb\"), IO[bytes])\nassert_type(open(\"path\", \"other\"), IO[Any])\n\n\nA = TypeVar(\"A\", bound=int)\nB = TypeVar(\"B\", bound=int)\nC = TypeVar(\"C\", bound=int)\n\n\nclass Matrix(Generic[A, B]):\n def __add__(self, other: \"Matrix[A, B]\") -> \"Matrix[A, B]\":\n raise NotImplementedError\n\n def __matmul__(self, other: \"Matrix[B, C]\") -> \"Matrix[A, C]\":\n raise NotImplementedError\n\n def transpose(self) -> \"Matrix[B, A]\":\n raise NotImplementedError\n\n\ndef func2(a: Matrix[Literal[2], Literal[3]], b: Matrix[Literal[3], Literal[7]]):\n c = a @ b\n assert_type(c, Matrix[Literal[2], Literal[7]])\n\n\nT = TypeVar(\"T\", Literal[\"a\"], Literal[\"b\"], Literal[\"c\"])\nS = TypeVar(\"S\", bound=Literal[\"foo\"])\n\n\nclass Status(Enum):\n SUCCESS = 0\n INVALID_DATA = 1\n FATAL_ERROR = 2\n\n\ndef parse_status1(s: str | Status) -> None:\n if s is Status.SUCCESS:\n assert_type(s, Literal[Status.SUCCESS])\n elif s is Status.INVALID_DATA:\n assert_type(s, Literal[Status.INVALID_DATA])\n elif s is Status.FATAL_ERROR:\n assert_type(s, Literal[Status.FATAL_ERROR])\n else:\n assert_type(s, str)\n\n\n# > Type checkers may optionally perform additional analysis for both\n# > enum and non-enum Literal types beyond what is described in the section above.\n#\n# > For example, it may be useful to perform narrowing based on things\n# > like containment or equality checks:\n\ndef expects_bad_status(status: Literal[\"MALFORMED\", \"ABORTED\"]):\n ...\n\n\ndef expects_pending_status(status: Literal[\"PENDING\"]):\n ...\n\n\ndef parse_status2(status: LiteralString) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n\n# Narrowing `str` to `Literal` strings is unsound given the possiblity of\n# user-defined `str` subclasses that could have custom equality semantics,\n# but is explicitly listed by the spec as optional analysis that type checkers\n# may perform.\ndef parse_status3(status: str) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n\nfinal_val1: Final = 3\nassert_type(final_val1, Literal[3])\n\nfinal_val2: Final = True\nassert_type(final_val2, Literal[True])\n","source":"typing_tests","origin":"conformance/tests/literals_interactions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_05.py","code":"\"\"\"\nTests legal and illegal parameterizations of Literal.\n\"\"\"\n\n# > Literal must be parameterized with at least one type.\n\nfrom typing import Any, Literal, TypeVar\nfrom enum import Enum\n\n\nclass Color(Enum):\n RED = 0\n GREEN = 1\n BLUE = 2\n\n\ngood1: Literal[26]\ngood2: Literal[0x1A]\ngood3: Literal[-4]\ngood4: Literal[+5]\ngood5: Literal[\"hello world\"]\ngood6: Literal[b\"hello world\"]\ngood7: Literal[\"hello world\"]\ngood8: Literal[True]\ngood9: Literal[Color.RED]\ngood10: Literal[None]\n\nReadOnlyMode = Literal[\"r\", \"r+\"]\nWriteAndTruncateMode = Literal[\"w\", \"w+\", \"wt\", \"w+t\"]\nWriteNoTruncateMode = Literal[\"r+\", \"r+t\"]\nAppendMode = Literal[\"a\", \"a+\", \"at\", \"a+t\"]\n\nAllModes = Literal[ReadOnlyMode, WriteAndTruncateMode, WriteNoTruncateMode, AppendMode]\n\ngood11: Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n\nvariable = 3\nT = TypeVar(\"T\")\n\n# > Arbitrary expressions [are illegal]\nbad1: Literal[3 + 4] # E\nbad2: Literal[\"foo\".replace(\"o\", \"b\")] # E\nbad3: Literal[4 + 3j] # E\nbad4: Literal[~5] # E\nbad5: Literal[not False] # E\nbad6: Literal[(1, \"foo\", \"bar\")] # E\nbad7: Literal[{\"a\": \"b\", \"c\": \"d\"}] # E\nbad8: Literal[int] # E\nbad9: Literal[variable] # E\nbad10: Literal[T] # E\nbad11: Literal[3.14] # E\nbad12: Literal[Any] # E\nbad13: Literal[...] # E\n\n\ndef my_function(x: Literal[1 + 2]) -> int: # E\n return x * 3\n\n\nx: Literal # E\ny: Literal[my_function] = my_function # E\n\n\ndef func2(a: Literal[Color.RED]):\n x1: Literal[\"Color.RED\"] = a # E\n\n x2: \"Literal[Color.RED]\" = a # OK\n","source":"typing_tests","origin":"conformance/tests/literals_parameterizations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_06.py","code":"\"\"\"\nTests the semantics of the Literal special form.\n\"\"\"\n\nfrom typing import Literal\nfrom typing import Literal as L\n\n\nv1: Literal[3] = 3\nv2: Literal[3] = 4 # E\n\nv3: L[-3] = -3\n\n\n# > Literal[20] and Literal[0x14] are equivalent\ndef func1(a: Literal[20], b: Literal[0x14], c: Literal[0b10100]):\n x1: Literal[0x14] = a\n x2: Literal[0x14] = b\n x3: Literal[0x14] = c\n\n\n# > Literal[0] and Literal[False] are not equivalent\ndef func2(a: Literal[0], b: Literal[False]):\n x1: Literal[False] = a # E\n x2: Literal[0] = b # E\n\n\n# > Given some value v that is a member of type T, the type Literal[v] shall\n# > be treated as a subtype of T. For example, Literal[3] is a subtype of int.\ndef func3(a: L[3, 4, 5]):\n b = a.__add__(3)\n c = a + 3\n a += 3 # E\n\n\n# > When a Literal is parameterized with more than one value, it’s treated\n# > as exactly equivalent to the union of those types.\ndef func4(a: L[None, 3] | L[3, \"foo\", b\"bar\", True]):\n x1: Literal[3, b\"bar\", True, \"foo\", None] = a\n a = x1\n","source":"typing_tests","origin":"conformance/tests/literals_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"override-decorator","pep":"698","introduced_in":"3.12","form":"modern","file":"override-decorator/modern_01.py","code":"\"\"\"\nTests the typing.override decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#override\n\nfrom typing import Any, Callable, overload, override\n\n\ndef wrapper(func: Callable[..., Any], /) -> Any:\n def wrapped(*args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n return wrapped\n\n\nclass ParentA:\n def method1(self) -> int:\n return 1\n\n @overload\n def method2(self, x: int) -> int:\n ...\n\n @overload\n def method2(self, x: str) -> str:\n ...\n\n def method2(self, x: int | str) -> int | str:\n return 0\n\n def method5(self):\n pass\n\n\nclass ChildA(ParentA):\n @override\n def method1(self) -> int: # OK\n return 2\n\n @overload\n def method2(self, x: int) -> int:\n ...\n\n @overload\n def method2(self, x: str) -> str:\n ...\n\n def method2(self, x: int | str) -> int | str: # OK\n return 0\n\n @override # E[method3]\n def method3(self) -> int: # E[method3]: no matching signature in ancestor\n return 1\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @override # E[method4]\n def method4(self, x: int | str) -> int | str: # E[method4]: no matching signature in ancestor\n return 0\n\n @override\n @wrapper\n def method5(self): # OK\n pass\n\n # > The @override decorator should be permitted anywhere a type checker\n # > considers a method to be a valid override, which typically includes not\n # > only normal methods but also @property, @staticmethod, and @classmethod.\n\n @staticmethod\n @override # E[static_method1]\n def static_method1() -> int: # E[static_method1]: no matching signature in ancestor\n return 1\n\n @classmethod\n @override # E[class_method1]\n def class_method1(cls) -> int: # E[class_method1]: no matching signature in ancestor\n return 1\n\n @property\n @override # E[property1]\n def property1(self) -> int: # E[property1]: no matching signature in ancestor\n return 1\n\n\n# Test the case where the parent derives from Any\n\nclass ParentB(Any):\n pass\n\n\nclass ChildB(ParentB):\n @override\n def method1(self) -> None: # OK\n pass\n\n\n# > When type checkers encounter a method decorated with @typing.override they\n# > should treat it as a type error unless that method is overriding a method or\n# > attribute in some ancestor class, and the type of the overriding method is\n# > assignable to the type of the overridden method.\n\n# ``__init__`` and ``__new__`` are normally exempt from override compatibility\n# checks, since constructors are not subject to the Liskov substitution\n# principle. However, when they are explicitly decorated with ``@override`` the\n# decorator's assignability check should still be honored.\n# See https://github.com/python/typing/issues/2222\n\n\nclass ParentC:\n def __init__(self, x: int) -> None: ...\n\n def __new__(cls, x: int) -> \"ParentC\":\n raise NotImplementedError\n\n\nclass ChildC1(ParentC):\n @override\n def __init__(self, x: int) -> None: ... # OK\n\n @override\n def __new__(cls, x: int) -> \"ChildC1\": # OK\n raise NotImplementedError\n\n\nclass ChildC2(ParentC):\n @override # E[init]\n def __init__(self, x: str) -> None: ... # E[init]: not assignable to \"ParentC.__init__\"\n\n @override # E[new]\n def __new__(cls, x: str) -> \"ChildC2\": # E[new]: not assignable to \"ParentC.__new__\"\n raise NotImplementedError\n\n\n# Without ``@override`` an incompatible constructor signature is allowed, since\n# ``__init__`` and ``__new__`` are exempt from the usual override checks.\n\n\nclass ChildC3(ParentC):\n def __init__(self, x: str) -> None: ... # OK\n\n def __new__(cls, x: str) -> \"ChildC3\": # OK\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/classes_override.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_01.py","code":"\"\"\"\nTests basic usage of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#paramspec-variables\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeAlias\n\nP = ParamSpec(\"P\") # OK\nWrongName = ParamSpec(\"NotIt\") # E: name inconsistency\n\n\n# > Valid use locations\n\nTA1: TypeAlias = P # E\n\nTA2: TypeAlias = Callable[P, None] # OK\nTA3: TypeAlias = Callable[Concatenate[int, P], None] # OK\nTA4: TypeAlias = Callable[..., None] # OK\nTA5: TypeAlias = Callable[..., None] # OK\n\n\ndef func1(x: P) -> P: # E\n raise NotImplementedError\n\n\ndef func2(x: Concatenate[int, P]) -> int: # E\n raise NotImplementedError\n\n\ndef func3(x: list[P]) -> None: # E\n ...\n\n\ndef func4(x: Callable[[int, str], P]) -> None: # E\n ...\n\n\ndef func5(*args: P, **kwargs: P) -> None: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_02.py","code":"\"\"\"\nTests the usage of a ParamSpec and its components (P.args, P.kwargs).\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#the-components-of-a-paramspec\n\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef puts_p_into_scope1(f: Callable[P, int]) -> None:\n def inner(*args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def mixed_up(*args: P.kwargs, **kwargs: P.args) -> None: # E\n pass\n\n def misplaced1(x: P.args) -> None: # E\n pass\n\n def bad_kwargs1(*args: P.args, **kwargs: P.args) -> None: # E\n pass\n\n def bad_kwargs2(*args: P.args, **kwargs: Any) -> None: # E\n pass\n\n\ndef out_of_scope(*args: P.args, **kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef puts_p_into_scope2(f: Callable[P, int]) -> None:\n stored_args: P.args # E\n stored_kwargs: P.kwargs # E\n\n def just_args(*args: P.args) -> None: # E\n pass\n\n def just_kwargs(**kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef decorator(f: Callable[P, int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n assert_type(f(*args, **kwargs), int) # OK\n\n f(*kwargs, **args) # E\n\n f(1, *args, **kwargs) # E\n\n return foo # OK\n\n\ndef add(f: Callable[P, int]) -> Callable[Concatenate[str, P], None]:\n def foo(s: str, *args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def bar(*args: P.args, s: str, **kwargs: P.kwargs) -> None: # E\n pass\n\n return foo # OK\n\n\ndef remove(f: Callable[Concatenate[int, P], int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n f(1, *args, **kwargs) # OK\n\n f(*args, 1, **kwargs) # E\n\n f(*args, **kwargs) # E\n\n return foo # OK\n\n\ndef outer(f: Callable[P, None]) -> Callable[P, None]:\n def foo(x: int, *args: P.args, **kwargs: P.kwargs) -> None:\n f(*args, **kwargs)\n\n def bar(*args: P.args, **kwargs: P.kwargs) -> None:\n foo(1, *args, **kwargs) # OK\n foo(x=1, *args, **kwargs) # E\n\n return bar\n\n\ndef twice(f: Callable[P, int], *args: P.args, **kwargs: P.kwargs) -> int:\n return f(*args, **kwargs) + f(*args, **kwargs)\n\n\ndef a_int_b_str(a: int, b: str) -> int:\n return 0\n\n\ntwice(a_int_b_str, 1, \"A\") # OK\ntwice(a_int_b_str, b=\"A\", a=1) # OK\ntwice(a_int_b_str, \"A\", 1) # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_components.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_03.py","code":"\"\"\"\nTests semantics of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#semantics\n\n\nfrom typing import Callable, Concatenate, Generic, ParamSpec, TypeVar, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef changes_return_type_to_str(x: Callable[P, int]) -> Callable[P, str]:\n raise NotImplementedError\n\n\ndef returns_int(a: str, b: bool, /) -> int:\n raise NotImplementedError\n\n\nf1 = changes_return_type_to_str(returns_int)\nassert_type(f1, Callable[[str, bool], str])\n\nv1 = f1(\"A\", True) # OK\nassert_type(v1, str)\nf1(a=\"A\", b=True) # E: positional-only\nf1(\"A\", \"A\") # E: wrong type\n\n\ndef func1(x: Callable[P, int], y: Callable[P, int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\ndef x_y(x: int, y: str) -> int:\n raise NotImplementedError\n\n\ndef y_x(y: int, x: str) -> int:\n raise NotImplementedError\n\n\nf2 = func1(x_y, x_y)\nassert_type(f2(1, \"\"), bool)\nassert_type(f2(y=\"\", x=1), bool)\n\nf3 = func1(x_y, y_x) # E?: Could return (a: int, b: str, /) -> bool\n# (a callable with two positional-only parameters)\n# This works because both callables have types that are\n# behavioral subtypes of Callable[[int, str], int]\n# Also OK for type checkers to reject this.\n\n\ndef keyword_only_x(*, x: int) -> int:\n raise NotImplementedError\n\n\ndef keyword_only_y(*, y: int) -> int:\n raise NotImplementedError\n\n\nfunc1(keyword_only_x, keyword_only_y) # E\n\n\nU = TypeVar(\"U\")\n\n\nclass Y(Generic[U, P]):\n f: Callable[P, str]\n prop: U\n\n def __init__(self, f: Callable[P, str], prop: U) -> None:\n self.f = f\n self.prop = prop\n\n\ndef callback_a(q: int, /) -> str:\n raise NotImplementedError\n\n\ndef func(x: int) -> None:\n y1 = Y(callback_a, x)\n assert_type(y1, Y[int, [int]])\n y2 = y1.f\n assert_type(y2, Callable[[int], str])\n\n\ndef bar(x: int, *args: bool) -> int:\n raise NotImplementedError\n\n\ndef add(x: Callable[P, int]) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\na1 = add(bar) # Should return (a: str, /, x: int, *args: bool) -> bool\nassert_type(a1(\"\", 1, False, True), bool)\nassert_type(a1(\"\", x=1), bool)\na1(1, x=1) # E\n\n\ndef remove(x: Callable[Concatenate[int, P], int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\nr1 = remove(bar) # Should return (*args: bool) -> bool\nassert_type(r1(False, True, True), bool)\nassert_type(r1(), bool)\nr1(1) # E\n\n\ndef transform(\n x: Callable[Concatenate[int, P], int]\n) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\nt1 = transform(bar) # Should return (a: str, /, *args: bool) -> bool\nassert_type(t1(\"\", True, False, True), bool)\nassert_type(t1(\"\"), bool)\nt1(1) # E\n\n\ndef expects_int_first(x: Callable[Concatenate[int, P], int]) -> None:\n ...\n\n\n@expects_int_first # E\ndef one(x: str) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef two(*, x: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef three(**kwargs: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # OK\ndef four(*args: int) -> int:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_04.py","code":"\"\"\"\nTests the handling of a ParamSpec specialization.\n\"\"\"\n\nfrom typing import Any, Callable, Concatenate, Generic, ParamSpec, TypeVar, cast\n\n\nT = TypeVar(\"T\")\nP1 = ParamSpec(\"P1\")\nP2 = ParamSpec(\"P2\")\n\n\nclass ClassA(Generic[T, P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\nclass ClassB(ClassA[T, P1], Generic[T, P1, P2]):\n f1: Callable[P1, int] = cast(Any, \"\")\n f2: Callable[P2, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\ndef func20(x: ClassA[int, P2]) -> str: # OK\n return \"\"\n\n\ndef func21(x: ClassA[int, Concatenate[int, P2]]) -> str: # OK\n return \"\"\n\n\ndef func22(x: ClassB[int, [int, bool], ...]) -> str: # OK\n return \"\"\n\n\ndef func23(x: ClassA[int, ...]) -> str: # OK\n return \"\"\n\n\ndef func24(x: ClassB[int, [], []]) -> str: # OK\n return \"\"\n\n\ndef func25(x: ClassA[int, int]) -> str: # E\n return \"\"\n\n\nclass ClassC(Generic[P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n\n\ndef func30(x: ClassC[[int, str, bool]]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n\n\ndef func31(x: ClassC[int, str, bool]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_05.py","code":"\"\"\"\nTests variance of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance-inference\n\n\nfrom typing import Callable, Generic, ParamSpec\n\n\nclass InvariantParamSpec[**InOutP]:\n a: Callable[InOutP, None]\n\nin_out_obj: InvariantParamSpec[object] = InvariantParamSpec[int]() # E\nin_out_int: InvariantParamSpec[int] = InvariantParamSpec[object]() # E\n\n\nclass ContravariantParamSpec[**InP]:\n def f(self, *args: InP.args, **kwargs: InP.kwargs): ...\n\nin_obj: ContravariantParamSpec[object] = ContravariantParamSpec[int]() # E\nin_int: ContravariantParamSpec[int] = ContravariantParamSpec[object]() # OK\n\n\nclass CovariantParamSpec[**OutP]:\n def f(self, fn: Callable[OutP, None]) -> None:\n raise NotImplementedError\n\n\nout_int: CovariantParamSpec[int] = CovariantParamSpec[object]() # E\nout_obj: CovariantParamSpec[object] = CovariantParamSpec[int]() # OK\n\n# cases involving keyword-only, positional-only parameters, parameter names, defaults and differing callable arities\nclass Box[T]:\n t: T\n\n def __init__(self, t: T): ...\n\n\ndef f(a: int): ...\ndef kw(*, a: int): ...\ndef pos(a: int, /): ...\ndef names(b: int): ...\ndef default(a: int = 1): ...\ndef arity(a: int, b: str): ...\n\n\nclass InitP[**P]: # contravariant\n def __init__(self, fn: Callable[P, None]): ...\n\n def usage(self) -> Callable[P, None]:\n \"\"\"infer contravariance\"\"\"\n raise NotImplementedError\n\n\n# `InitP` produces a `Callable[P, None]`, so a replacement is only safe if it\n# accepts every call form that `InitP[(a: int)]` accepts.\nin_box = Box(InitP(f))\n\nin_kw_p = InitP(kw)\nin_box.t = in_kw_p # E\nin_pos_p = InitP(pos)\nin_box.t = in_pos_p # E\nin_names_p = InitP(names)\nin_box.t = in_names_p # E\nin_default_p = InitP(default)\nin_box.t = in_default_p # OK\nin_arity_p = InitP(arity)\nin_box.t = in_arity_p # E\n\n\nclass OutitP[**P]: # covariant\n def __init__(self, fn: Callable[P, None]): ...\n\n def usage(self, fn: Callable[P, None]):\n \"\"\"infer covariance\"\"\"\n\n\n# `OutitP` consumes a `Callable[P, None]`, so the safe direction is reversed: a\n# replacement is only safe if `Callable[(a: int), None]` can be passed to it.\nout_box = Box(OutitP(f))\n\nout_kw_p = OutitP(kw)\nout_box.t = out_kw_p # OK\nout_pos_p = OutitP(pos)\nout_box.t = out_pos_p # OK\nout_names_p = OutitP(names)\nout_box.t = out_names_p # E\nout_default_p = OutitP(default)\nout_box.t = out_default_p # E\nout_arity_p = OutitP(arity)\nout_box.t = out_arity_p # E\n\n\n# old style\nP = ParamSpec(\"P\") # OK\nInP = ParamSpec(\"InP\", contravariant=True) # OK\nOutP = ParamSpec(\"OutP\", covariant=True) # OK\nInferP = ParamSpec(\"InferP\", infer_variance=True) # OK\nInvP1 = ParamSpec(\"InvP1\", covariant=True, contravariant=True) # E\nInvP2 = ParamSpec(\"InvP2\", covariant=True, infer_variance=True) # E\nInvP3 = ParamSpec(\"InvP3\", contravariant=True, infer_variance=True) # E\n\nclass InvariantParamSpecOld(Generic[P]):\n def f(self, fn: Callable[P, None]) -> Callable[P, None]: # OK\n raise NotImplementedError\n\nin_out_old: InvariantParamSpecOld[int]\nin_out_old = InvariantParamSpecOld[int]() # OK\nin_out_old = InvariantParamSpecOld[bool]() # E\nin_out_old = InvariantParamSpecOld[object]() # E\n\nclass ContravariantParamSpecOld(Generic[InP]):\n def in_f(self) -> Callable[InP, None]: # OK\n raise NotImplementedError\n\n def out_f(self, fn: Callable[InP, None]) -> None: # E\n raise NotImplementedError\n\n\nin_obj_old: ContravariantParamSpecOld[object] = ContravariantParamSpecOld[int]() # E\nin_int_old: ContravariantParamSpecOld[int] = ContravariantParamSpecOld[object]() # OK\n\n\nclass CovariantParamSpecOld(Generic[OutP]):\n def in_f(self) -> Callable[OutP, None]: # E\n raise NotImplementedError\n def out_f(self, fn: Callable[OutP, None]) -> None: # OK\n raise NotImplementedError\n\n\nout_int_old: CovariantParamSpecOld[int] = CovariantParamSpecOld[object]() # E\nout_obj_old: CovariantParamSpecOld[object] = CovariantParamSpecOld[int]() # OK\n\n\n# `infer_variance=True` on a traditional `ParamSpec`\nclass InferredContravariantParamSpecOld(Generic[InferP]):\n def in_f(self) -> Callable[InferP, None]: # OK\n raise NotImplementedError\n\n\ninfer_in_obj_old: InferredContravariantParamSpecOld[object] = InferredContravariantParamSpecOld[int]() # E\ninfer_in_int_old: InferredContravariantParamSpecOld[int] = InferredContravariantParamSpecOld[object]() # OK\n\n\nclass InferredCovariantParamSpecOld(Generic[InferP]):\n def out_f(self, fn: Callable[InferP, None]) -> None: # OK\n raise NotImplementedError\n\n\ninfer_out_int_old: InferredCovariantParamSpecOld[int] = InferredCovariantParamSpecOld[object]() # E\ninfer_out_obj_old: InferredCovariantParamSpecOld[object] = InferredCovariantParamSpecOld[int]() # OK\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_01.py","code":"\"\"\"\nTests handling of callback protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#callback-protocols\n\nfrom typing import Any, Callable, ParamSpec, Protocol, TypeVar, cast, overload\n\nInputT = TypeVar(\"InputT\", contravariant=True)\nOutputT = TypeVar(\"OutputT\", covariant=True)\n\n\nclass Proto1(Protocol):\n def __call__(self, *vals: bytes, max_len: int | None = None) -> list[bytes]:\n ...\n\n\ndef cb1_good1(*vals: bytes, max_len: int | None = None) -> list[bytes]:\n return []\n\n\ndef cb1_bad1(*vals: bytes, max_items: int | None) -> list[bytes]:\n return []\n\n\ndef cb1_bad2(*vals: bytes) -> list[bytes]:\n return []\n\n\ndef cb1_bad3(*vals: bytes, max_len: str | None) -> list[bytes]:\n return []\n\n\ncb1: Proto1 = cb1_good1 # OK\ncb1 = cb1_bad1 # E: different names\ncb1 = cb1_bad2 # E: parameter types\ncb1 = cb1_bad3 # E: default argument\n\n\nclass Proto2(Protocol):\n def __call__(self, *vals: bytes, **kwargs: str) -> None:\n pass\n\n\ndef cb2_good1(*a: bytes, **b: str):\n pass\n\n\ndef cb2_bad1(*a: bytes):\n pass\n\n\ndef cb2_bad2(*a: str, **b: str):\n pass\n\n\ndef cb2_bad3(*a: bytes, **b: bytes):\n pass\n\n\ndef cb2_bad4(**b: str):\n pass\n\n\ncb2: Proto2 = cb2_good1 # OK\n\ncb2 = cb2_bad1 # E: missing **kwargs\ncb2 = cb2_bad2 # E: parameter type\ncb2 = cb2_bad3 # E: parameter type\ncb2 = cb2_bad4 # E: missing parameter\n\n\nclass Proto3(Protocol):\n def __call__(self) -> None:\n pass\n\n\ncb3: Proto3 = cb2_good1 # OK\ncb3 = cb2_bad1 # OK\ncb3 = cb2_bad2 # OK\ncb3 = cb2_bad3 # OK\ncb3 = cb2_bad4 # OK\n\n\n# A callback protocol with other attributes.\nclass Proto4(Protocol):\n other_attribute: int\n\n def __call__(self, x: int) -> None:\n pass\n\n\ndef cb4_bad1(x: int) -> None:\n pass\n\n\nvar4: Proto4 = cb4_bad1 # E: missing attribute\n\n\nclass Proto5(Protocol):\n def __call__(self, *, a: int, b: str) -> int:\n ...\n\n\ndef cb5_good1(a: int, b: str) -> int:\n return 0\n\n\ncb5: Proto5 = cb5_good1 # OK\n\n\nclass NotProto6:\n def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]:\n return []\n\n\ndef cb6_bad1(*vals: bytes, max_len: int | None = None) -> list[bytes]:\n return []\n\n\ncb6: NotProto6 = cb6_bad1 # E: NotProto6 isn't a protocol class\n\n\nclass Proto7(Protocol[InputT, OutputT]):\n def __call__(self, inputs: InputT) -> OutputT:\n ...\n\n\nclass Class7_1:\n # Test for unannotated parameter.\n def __call__(self, inputs) -> int:\n return 5\n\n\ncb7_1: Proto7[int, int] = Class7_1() # OK\n\n\nclass Class7_2:\n # Test for parameter with type Any.\n def __call__(self, inputs: Any) -> int:\n return 5\n\n\ncb7_2: Proto7[int, int] = Class7_2() # OK\n\n\nclass Proto8(Protocol):\n @overload\n def __call__(self, x: int) -> int:\n ...\n\n @overload\n def __call__(self, x: str) -> str:\n ...\n\n def __call__(self, x: Any) -> Any:\n ...\n\n\ndef cb8_good1(x: Any) -> Any:\n return x\n\n\ndef cb8_bad1(x: int) -> Any:\n return x\n\n\ncb8: Proto8 = cb8_good1 # OK\ncb8 = cb8_bad1 # E: parameter type\n\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\", covariant=True)\n\n\nclass Proto9[**P, R](Protocol):\n other_attribute: int\n\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\ndef decorator1(f: Callable[P, R]) -> Proto9[P, R]:\n converted = cast(Proto9[P, R], f)\n converted.other_attribute = 1\n converted.other_attribute = \"str\" # E: incompatible type\n converted.xxx = 3 # E: unknown attribute\n return converted\n\n\n@decorator1\ndef cb9_good(x: int) -> str:\n return \"\"\n\n\nprint(cb9_good.other_attribute) # OK\nprint(cb9_good.other_attribute2) # E: unknown attribute\n\ncb9_good(x=3)\n\n\nclass Proto10(Protocol):\n __name__: str\n __module__: str\n __qualname__: str\n __annotations__: dict[str, Any]\n\n def __call__(self) -> None:\n ...\n\n\ndef cb10_good() -> None:\n pass\n\n\ncb10: Proto10 = cb10_good # OK\n\n\nclass Proto11(Protocol):\n def __call__(self, x: int, /, y: str) -> Any:\n ...\n\n\ndef cb11_good1(x: int, /, y: str, z: None = None) -> Any:\n raise NotImplementedError\n\n\ndef cb11_good2(x: int, y: str, z: None = None) -> Any:\n raise NotImplementedError\n\n\ndef cb11_bad1(x: int, y: str, /) -> Any:\n raise NotImplementedError\n\n\ncb11: Proto11 = cb11_good1 # OK\ncb11 = cb11_good2 # OK\ncb11 = cb11_bad1 # E: y is position-only\n\n\nclass Proto12(Protocol):\n def __call__(self, *args: Any, kwarg0: Any, kwarg1: Any) -> None:\n ...\n\n\ndef cb12_good1(*args: Any, kwarg0: Any, kwarg1: Any) -> None:\n pass\n\n\ndef cb12_good2(*args: Any, **kwargs: Any) -> None:\n pass\n\n\ndef cb12_bad1(*args: Any, kwarg0: Any) -> None:\n pass\n\n\ncb12: Proto12 = cb12_good1 # OK\ncb12 = cb12_good2 # OK\ncb12 = cb12_bad1 # E: missing kwarg1\n\n\nclass Proto13_Default(Protocol):\n # Callback with positional parameter with default arg value\n def __call__(self, path: str = ...) -> str:\n ...\n\n\nclass Proto13_NoDefault(Protocol):\n # Callback with positional parameter but no default arg value\n def __call__(self, path: str) -> str:\n ...\n\n\ndef cb13_default(path: str = \"\") -> str:\n return \"\"\n\n\ndef cb13_no_default(path: str) -> str:\n return \"\"\n\n\ncb13_1: Proto13_Default = cb13_default # OK\ncb13_2: Proto13_Default = cb13_no_default # E: no default\n\ncb13_3: Proto13_NoDefault = cb13_default # OK\ncb13_4: Proto13_NoDefault = cb13_no_default # OK\n\n\nclass Proto14_Default(Protocol):\n # Callback with keyword parameter with default arg value\n def __call__(self, *, path: str = ...) -> str:\n ...\n\n\nclass Proto14_NoDefault(Protocol):\n # Callback with keyword parameter with no default arg value\n def __call__(self, *, path: str) -> str:\n ...\n\n\ndef cb14_default(*, path: str = \"\") -> str:\n return \"\"\n\n\ndef cb14_no_default(*, path: str) -> str:\n return \"\"\n\n\ncb14_1: Proto14_Default = cb14_default # OK\ncb14_2: Proto14_Default = cb14_no_default # E: no default\ncb14_3: Proto14_NoDefault = cb14_default # OK\ncb14_4: Proto14_NoDefault = cb14_no_default # OK\n","source":"typing_tests","origin":"conformance/tests/callables_protocol.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_02.py","code":"\"\"\"\nTests the handling of class objects as implementations of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#type-and-class-objects-vs-protocols\n\n# > Variables and parameters annotated with Type[Proto] accept only concrete\n# (non-protocol) subtypes of Proto.\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Protocol\n\n\nclass Proto(Protocol):\n @abstractmethod\n def meth(self) -> int:\n ...\n\n\nclass Concrete:\n def meth(self) -> int:\n return 42\n\n\ndef fun(cls: type[Proto]) -> int:\n return cls().meth() # OK\n\n\nfun(Proto) # E\nfun(Concrete) # OK\n\n\nvar: type[Proto]\nvar = Proto # E\nvar = Concrete # OK\nvar().meth() # OK\n\n\n# > A class object is considered an implementation of a protocol if accessing\n# > all members on it results in types compatible with the protocol members.\n\n\nclass ProtoA1(Protocol):\n def method1(self, x: int) -> int:\n ...\n\n\nclass ProtoA2(Protocol):\n def method1(_self, self: Any, x: int) -> int:\n ...\n\n\nclass ConcreteA:\n def method1(self, x: int) -> int:\n return 0\n\n\npa1: ProtoA1 = ConcreteA # E: signatures don't match\npa2: ProtoA2 = ConcreteA # OK\n\n\nclass ProtoB1(Protocol):\n @property\n def prop1(self) -> int:\n ...\n\n\nclass ConcreteB:\n @property\n def prop1(self) -> int:\n return 0\n\n\npb1: ProtoB1 = ConcreteB # E\n\n\nclass ProtoC1(Protocol):\n attr1: ClassVar[int]\n\n\nclass ProtoC2(Protocol):\n attr1: int\n\n\nclass ConcreteC1:\n attr1: ClassVar[int] = 1\n\n\nclass ConcreteC2:\n attr1: int = 1\n\n\nclass CMeta(type):\n attr1: int\n\n def __init__(self, *args, **kwargs) -> None:\n self.attr1: int = 1\n\n\nclass ConcreteC3(metaclass=CMeta):\n pass\n\n\npc1: ProtoC1 = ConcreteC1 # E\npc2: ProtoC2 = ConcreteC1 # OK\npc3: ProtoC1 = ConcreteC2 # E\npc4: ProtoC2 = ConcreteC2 # E\npc5: ProtoC1 = ConcreteC3 # E?: Explicit ClassVar matching is unspecified\npc6: ProtoC2 = ConcreteC3 # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_class_objects.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_03.py","code":"\"\"\"\nTests the basic definition rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#defining-a-protocol\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Iterable, NamedTuple, Protocol, Sequence\nfrom dataclasses import dataclass\n\n\nclass SupportsClose(Protocol):\n def close(self) -> None:\n ...\n\n\nclass Resource:\n def close(self) -> None:\n pass\n\n\ndef close_all(things: Iterable[SupportsClose]) -> None:\n for t in things:\n t.close()\n\n\nf = open(\"foo.txt\")\nr = Resource()\nclose_all([f, r]) # OK\nclose_all([1]) # E: 'int' has no 'close' method\n\n\nclass Example(Protocol):\n def first(self) -> int: # This is a protocol member\n return 42\n\n @abstractmethod\n def second(self) -> int: # Method without a default implementation\n raise NotImplementedError\n\n # > Static methods, class methods, and properties are equally allowed in protocols.\n\n @staticmethod\n def third() -> int:\n ...\n\n @classmethod\n def fourth(cls) -> int:\n ...\n\n @property\n def fifth(self) -> int:\n ...\n\n\n# > To define a protocol variable, one can use PEP 526 variable annotations\n# > in the class body. Additional attributes only defined in the body of a\n# > method by assignment via self are not allowed.\n\n\nclass Template(Protocol):\n name: str # This is a protocol member\n value: int = 0 # This one too (with default)\n\n def method(self) -> None:\n self.name = \"name\" # OK\n self.temp: list[int] = [] # E: use of self variables not allowed\n\n\nclass Concrete:\n def __init__(self, name: str, value: int) -> None:\n self.name = name\n self.value = value\n\n def method(self) -> None:\n return\n\n\nvar: Template = Concrete(\"value\", 42) # OK\n\n\n# > To distinguish between protocol class variables and protocol instance\n# > variables, the special ClassVar annotation should be used as specified\n# > by PEP 526. By default, protocol variables as defined above are considered\n# > readable and writable. To define a read-only protocol variable, one can\n# > use an (abstract) property.\n\n\nclass Template2(Protocol):\n val1: ClassVar[Sequence[int]]\n\n\nclass Concrete2_Good1:\n val1: ClassVar[Sequence[int]] = [2]\n\n\nclass Concrete2_Bad1:\n ...\n\n\nclass Concrete2_Bad2:\n val1: Sequence[float] = [2]\n\n\nclass Concrete2_Bad3:\n val1: list[int] = [2]\n\n\nclass Concrete2_Bad4:\n val1: Sequence[int] = [2]\n\n\nv2_good1: Template2 = Concrete2_Good1() # OK\nv2_bad1: Template2 = Concrete2_Bad1() # E\nv2_bad2: Template2 = Concrete2_Bad2() # E\nv2_bad3: Template2 = Concrete2_Bad3() # E\nv2_bad4: Template2 = Concrete2_Bad4() # E?: Explicit ClassVar matching is unspecified\n\n\nclass Template3(Protocol):\n val1: Sequence[int]\n\n\nclass Concrete3_Good1:\n val1: Sequence[int] = [0]\n\n\nclass Concrete3_Good2:\n def __init__(self) -> None:\n self.val1: Sequence[int] = [0]\n\n\nclass Concrete3_Bad1:\n ...\n\n\nclass Concrete3_Bad2:\n val1: ClassVar[Sequence[int]] = [0]\n\n\nclass Concrete3_Bad3:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete3_Bad4:\n val1: Sequence[float] = [0]\n\n\nclass Concrete3_Bad5:\n val1: list[int] = [0]\n\n\nv3_good1: Template3 = Concrete3_Good1() # OK\nv3_bad1: Template3 = Concrete3_Bad1() # E\nv3_bad2: Template3 = Concrete3_Bad2() # E\nv3_bad3: Template3 = Concrete3_Bad3() # E\nv3_bad4: Template3 = Concrete3_Bad4() # E\nv3_bad5: Template3 = Concrete3_Bad5() # E\n\n\nclass Template4(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n\nclass Concrete4_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete4_Good2:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete4_Good3:\n val1: Sequence[float] = [0]\n\n\nclass Concrete4_Good4:\n val1: Sequence[int] = [0]\n\n\nclass Concrete4_Good5:\n val1: list[float] = [0]\n\n\nclass Concrete4_Good6(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete4_Good7:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete4_Bad1:\n def val1(self) -> Sequence[int]: # Not a property\n return [0]\n\n\nclass Concrete4_Bad2:\n ...\n\n\nv4_good1: Template4 = Concrete4_Good1() # OK\nv4_good2: Template4 = Concrete4_Good2() # OK\nv4_good3: Template4 = Concrete4_Good3() # OK\nv4_good4: Template4 = Concrete4_Good4() # OK\nv4_good5: Template4 = Concrete4_Good5() # OK\nv4_good6: Template4 = Concrete4_Good6() # OK\nv4_good7: Template4 = Concrete4_Good7() # OK\nv4_bad1: Template4 = Concrete4_Bad1() # E\nv4_bad2: Template4 = Concrete4_Bad2() # E\n\n\nclass Template5(Protocol):\n def method1(self, a: int, b: int) -> float:\n ...\n\n\nclass Concrete5_Good1:\n def method1(self, a: float, b: float) -> int:\n return 0\n\n\nclass Concrete5_Good2:\n def method1(self, *args: float, **kwargs: float) -> Any:\n return 0.0\n\n\nclass Concrete5_Good3:\n def method1(self, a, b) -> Any:\n return 0.0\n\n\nclass Concrete5_Good4:\n @classmethod\n def method1(cls, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Good5:\n @staticmethod\n def method1(a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad1:\n def method1(self, a, c) -> int:\n return 0\n\n\nclass Concrete5_Bad2:\n def method1(self, a: int, c: int) -> int:\n return 0\n\n\nclass Concrete5_Bad3:\n def method1(self, *, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad4:\n def method1(self, a: int, b: int, /) -> float:\n return 0\n\n\nclass Concrete5_Bad5:\n @staticmethod\n def method1(self, a: int, b: int) -> float:\n return 0\n\n\nv5_good1: Template5 = Concrete5_Good1() # OK\nv5_good2: Template5 = Concrete5_Good2() # OK\nv5_good3: Template5 = Concrete5_Good3() # OK\nv5_good4: Template5 = Concrete5_Good4() # OK\nv5_good5: Template5 = Concrete5_Good5() # OK\nv5_bad1: Template5 = Concrete5_Bad1() # E\nv5_bad2: Template5 = Concrete5_Bad2() # E\nv5_bad3: Template5 = Concrete5_Bad3() # E\nv5_bad4: Template5 = Concrete5_Bad4() # E\nv5_bad5: Template5 = Concrete5_Bad5() # E\n\n\nclass Template6(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n ...\n\n\nclass Concrete6_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n pass\n\n\nclass Concrete6_Good2:\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete6_Good3:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete6_Bad1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete6_Bad2(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=True)\nclass Concrete6_Bad3:\n val1: Sequence[float] = (0,)\n\n\nv6_good1: Template6 = Concrete6_Good1() # OK\nv6_good2: Template6 = Concrete6_Good2() # OK\nv6_good3: Template6 = Concrete6_Good3() # OK\nv6_bad1: Template6 = Concrete6_Bad1() # E\nv6_bad2: Template6 = Concrete6_Bad2() # E: named tuple is immutable\nv6_bad3: Template6 = Concrete6_Bad3() # E: dataclass is frozen\n\n\n# The specification leaves two possible interpretations of a ClassVar protocol\n# member. One interpretation requires the implementing attribute to be explicitly\n# declared with ClassVar. The other interpretation imposes only structural\n# requirements: the attribute must be readable and writable on the class object\n# and readable on instances of the class. Both interpretations therefore require\n# the following assignments to be rejected.\n\n\nclass Template7(Protocol):\n val1: ClassVar[int]\n\n\nclass Concrete7_Bad1:\n def __init__(self) -> None:\n self.val1: int = 42\n\n\nclass Concrete7Meta(type):\n val1: int = 42\n\n\nclass Concrete7_Bad2(metaclass=Concrete7Meta):\n pass\n\n\nv7_bad1: Template7 = Concrete7_Bad1() # E: val1 is not readable on the class object\nv7_bad2: Template7 = Concrete7_Bad2() # E: val1 is not readable on instances\n","source":"typing_tests","origin":"conformance/tests/protocols_definition.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_04.py","code":"\"\"\"\nTests the handling of explicit protocol classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#explicitly-declaring-implementation\n\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar, Protocol\n\n\nclass PColor(Protocol):\n @abstractmethod\n def draw(self) -> str:\n ...\n\n def complex_method(self) -> int:\n return 1\n\n\nclass NiceColor(PColor):\n def draw(self) -> str:\n return \"deep blue\"\n\n\nclass BadColor(PColor):\n def draw(self) -> str:\n return super().draw() # E: no default implementation\n\n\nclass ImplicitColor: # Note no 'PColor' base here\n def draw(self) -> str:\n return \"probably gray\"\n\n def complex_method(self) -> int:\n return 0\n\n\nv1: PColor = NiceColor() # OK\nv2: PColor = ImplicitColor() # OK\n\n\nclass RGB(Protocol):\n rgb: tuple[int, int, int]\n other: int\n\n @abstractmethod\n def intensity(self) -> int:\n return 1\n\n def transparency(self) -> int:\n ...\n\n\nclass Point(RGB):\n def __init__(self, red: int, green: int, blue: str) -> None:\n self.rgb = red, green, blue # E: 'blue' must be 'int'\n self.other = 0\n\n\np = Point(0, 0, \"\") # E: Cannot instantiate abstract class\n\n\nclass Proto1(Protocol):\n cm1: ClassVar[int]\n cm2: ClassVar[int] = 0\n\n im1: int\n im2: int = 2\n im3: int\n\n def __init__(self):\n self.im3 = 3\n\n\nclass Proto2(Protocol):\n cm10: int\n\n\nclass Proto3(Proto2, Protocol):\n cm11: int\n\n\nclass Concrete1(Proto1):\n def __init__(self):\n self.im1 = 1\n self.im3 = 3\n\n\nc1 = Concrete1() # E: cannot instantiate abstract class\n\n\nclass Concrete2(Proto1):\n cm1 = 3\n im1 = 0\n\n\nc2 = Concrete2()\n\n\nclass Concrete3(Proto1, Proto3):\n cm1 = 3\n\n def __init__(self):\n self.im1 = 0\n self.cm10 = 10\n self.cm11 = 11\n\n\nc3 = Concrete3()\n\n\nclass Concrete4(Proto1, Proto3):\n cm1 = 3\n cm10 = 3\n\n def __init__(self):\n self.im1 = 3\n self.im10 = 10\n self.cm11 = 3\n\n\nc4 = Concrete4()\n\n\nclass Proto5(Protocol):\n def method1(self) -> int:\n ...\n\n\nclass Concrete5(Proto5):\n pass\n\n\nc5 = Concrete5() # E: cannot instantiate abstract class\n\n\nclass Proto6(Protocol):\n x: int\n\n\nclass Mixin:\n x = 3\n\n\nclass Concrete6(Mixin, Proto6):\n pass\n\n\nclass Proto7(Protocol):\n @abstractmethod\n def method1(self):\n ...\n\n\nclass Mixin7(Proto7, ABC):\n def method1(self) -> None:\n pass\n\n\nclass Concrete7A(Proto7):\n pass\n\n\nc7a = Concrete7A() # E: cannot instantiate abstract class\n\n\nclass Concrete7B(Mixin7, Proto7):\n pass\n\n\nc7b = Concrete7B()\n","source":"typing_tests","origin":"conformance/tests/protocols_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_05.py","code":"\"\"\"\nTests the handling of generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\n\nfrom typing import Callable, Generic, Iterator, Protocol, Self, TypeVar, assert_type\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Iterable(Protocol[T_co]):\n def __iter__(self) -> Iterator[T_co]:\n ...\n\n\n# > Protocol[T, S, ...] is allowed as a shorthand for Protocol, Generic[T, S, ...].\n# In particular, the implicit order of type parameters is dictated by\n# the order in which they appear in the `Protocol` subscript.\n\n\nclass Proto1(Iterable[T_co], Protocol[S, T_co]):\n def method1(self, x: S) -> S:\n ...\n\n\nclass Concrete1:\n def __iter__(self) -> Iterator[int]:\n return (x for x in [1, 2, 3])\n\n def method1(self, x: str) -> str:\n return \"\"\n\n\np1: Proto1[str, int] = Concrete1() # OK\np2: Proto1[int, str] = Concrete1() # E: incompatible type\n\n\n# > It is an error to combine the shorthand with Generic[T, S, ...]\nclass Proto2(Protocol[T_co], Generic[T_co]): # E\n ...\n\n\n# > User-defined generic protocols support explicitly declared variance.\nclass Box(Protocol[T_co]):\n def content(self) -> T_co:\n ...\n\n\ndef func1(box_int: Box[int], box_float: Box[float]):\n v1: Box[float] = box_int # OK\n v2: Box[int] = box_float # E\n\n\nclass Sender(Protocol[T_contra]):\n def send(self, data: T_contra) -> int:\n return 0\n\n\ndef func2(sender_int: Sender[int], sender_float: Sender[float]):\n v1: Sender[int] = sender_float # OK\n v2: Sender[float] = sender_int # E\n\n\nclass AttrProto(Protocol[T]):\n attr: T\n\n\ndef func3(attr_int: AttrProto[int], attr_float: AttrProto[float]):\n v1: AttrProto[float] = attr_int # E\n v2: AttrProto[int] = attr_float # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n# > The self-types in protocols follow the rules for other methods.\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n# > In addition, the first argument in an instance method can be annotated\n# > with a type variable. In this case the return type may use the same\n# > type variable, thus making that method a generic function.\n\n\nT_bounded = TypeVar(\"T_bounded\", bound=\"HasParent\")\n\n\nclass HasParent(Protocol):\n def get_parent(self: T_bounded) -> T_bounded:\n ...\n\n\nGenericHasParent = TypeVar(\"GenericHasParent\", bound=HasParent)\n\n\ndef generic_get_parent(n: GenericHasParent) -> GenericHasParent:\n return n.get_parent()\n\n\nclass ConcreteHasParent:\n def get_parent(self) -> Self:\n return self\n\n\nparent = generic_get_parent(ConcreteHasParent()) # OK\nassert_type(parent, ConcreteHasParent)\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > `Self` is valid within Protocols, similar to its use in classes:\n\n\nclass HasParentProperty(Protocol):\n @property\n def parent(self) -> Self:\n ...\n\n\nclass ConcreteParentProperty:\n @property\n def parent(self) -> Self:\n return self\n\n\nclass InvalidParentProperty:\n @property\n def parent(self) -> HasParentProperty:\n return ConcreteParentProperty()\n\n\nhp1: HasParentProperty = ConcreteParentProperty() # OK\nhp2: HasParentProperty = InvalidParentProperty() # E\n\n\n\nclass HasMethod(Protocol):\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n ...\n\n\nclass ConcreteHasMethod:\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n return \"\"\n\n\nclass InvalidHasMethod:\n def m(self, item: int, callback: Callable[[int], str]) -> str:\n return \"\"\n\n\nhm1: HasMethod = ConcreteHasMethod() # OK\nhm2: HasMethod = InvalidHasMethod() # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > Checking a class for assignability to a protocol: If a protocol uses `Self`\n# > in methods or attribute annotations, then a class `Foo` is assignable\n# > to the protocol if its corresponding methods and attribute annotations use\n# > either `Self` or `Foo` or any of `Foo`'s subclasses.\n\n\nclass HasGreaterThan(Protocol):\n def __gt__(self, other: Self) -> bool:\n ...\n\n\nclass ConcreteGreaterThan1:\n def __gt__(self, other: Self) -> bool:\n return False\n\n\nclass ConcreteGreaterThan2:\n def __gt__(self, other: \"ConcreteGreaterThan2\") -> bool:\n return False\n\n\nclass InvalidGreaterThan:\n def __gt__(self, other: int) -> bool:\n return False\n\n\nhg1: HasGreaterThan = ConcreteGreaterThan1() # OK\nhg2: HasGreaterThan = ConcreteGreaterThan2() # OK\nhg3: HasGreaterThan = InvalidGreaterThan() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_generic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_06.py","code":"\"\"\"\nTests merging and extending of protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#merging-and-extending-protocols\n\nfrom abc import abstractmethod\nfrom typing import Protocol\nfrom collections.abc import Sized\n\n\nclass SizedAndClosable1(Sized, Protocol):\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable2(Protocol):\n def __len__(self) -> int:\n ...\n\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable3(SizedAndClosable1): # Note: not a protocol\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete1:\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete2:\n def close(self) -> None:\n pass\n\n\ns1: SizedAndClosable1 = SCConcrete1() # OK\ns2: SizedAndClosable2 = SCConcrete1() # OK\ns3: SizedAndClosable1 = SizedAndClosable3() # OK\ns4: SizedAndClosable2 = SizedAndClosable3() # OK\ns5: Sized = SCConcrete1() # OK\n\ns6: SizedAndClosable1 = SCConcrete2() # E: doesn't implement `__len__`\ns7: SizedAndClosable2 = SCConcrete2() # E: doesn't implement `__len__`\ns8: SizedAndClosable3 = SCConcrete2() # E: SizedAndClosable3 is not a protocol\n\n\ndef func1(s1: SizedAndClosable1, s2: SizedAndClosable2):\n # > The two definitions of SizedAndClosable are equivalent.\n v1: SizedAndClosable2 = s1\n v2: SizedAndClosable1 = s2\n\n\n# > If Protocol is included in the base class list, all the other base classes\n# > must be protocols.\n\n\nclass BadProto(SizedAndClosable3, Protocol): # E: SizedAndClosable3 is not a protocol\n ...\n\n\n# > Without this base, the class is “downgraded” to a regular ABC that\n# > cannot be used with structural subtyping.\nclass SizedAndClosable4(SizedAndClosable1):\n def __len__(self) -> int:\n return 0\n\n @abstractmethod\n def close(self) -> None:\n raise NotImplementedError\n\n\nx = SizedAndClosable4() # E: cannot instantiate abstract class\ny: SizedAndClosable4 = SCConcrete1() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_merging.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_07.py","code":"\"\"\"\nTests the handling of modules as the implementation of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#modules-as-implementations-of-protocols\n\n# > A module object is accepted where a protocol is expected if the public\n# > interface of the given module is compatible with the expected protocol.\n\nimport _protocols_modules1\nimport _protocols_modules2\nfrom typing import Protocol\n\n\nclass Options1(Protocol):\n timeout: int\n one_flag: bool\n other_flag: bool\n\n\nclass Options2(Protocol):\n timeout: str\n\n\nop1: Options1 = _protocols_modules1 # OK\nop2: Options2 = _protocols_modules1 # E\n\n\nclass Reporter1(Protocol):\n def on_error(self, x: int) -> None:\n ...\n\n def on_success(self) -> None:\n ...\n\n\nclass Reporter2(Protocol):\n def on_error(self, x: int) -> int:\n ...\n\n\nclass Reporter3(Protocol):\n def not_implemented(self, x: int) -> int:\n ...\n\n\nrp1: Reporter1 = _protocols_modules2 # OK\nrp2: Reporter2 = _protocols_modules2 # E\nrp3: Reporter3 = _protocols_modules2 # E\n","source":"typing_tests","origin":"conformance/tests/protocols_modules.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_08.py","code":"\"\"\"\nTests the handling of recursive protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#recursive-protocols\n\n\nfrom typing import Generic, Iterable, Never, Protocol, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Traversable(Protocol):\n def leaves(self) -> Iterable[\"Traversable\"]:\n ...\n\n\nclass SimpleTree:\n def leaves(self) -> list[\"SimpleTree\"]:\n return []\n\n\nroot: Traversable = SimpleTree() # OK\n\n\nclass Tree(Generic[T]):\n def leaves(self) -> list[\"Tree[T]\"]:\n return []\n\n\ndef walk(graph: Traversable) -> None:\n pass\n\n\ntree: Tree[float] = Tree()\nwalk(tree) # OK\n\n\nclass ProtoA(Protocol[T_co, T_contra]):\n def method1(self) -> \"ProtoA[T_co, T_contra]\":\n ...\n\n @classmethod\n def method2(cls, value: T_contra) -> None:\n ...\n\n\nclass ProtoB(Protocol[T_co, T_contra]):\n def method3(self) -> ProtoA[T_co, T_contra]:\n ...\n\n\nclass ImplA:\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls, value: int) -> None:\n pass\n\n\nclass ImplB:\n def method3(self) -> ImplA:\n return ImplA()\n\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls: type[ProtoB[object, T]], value: list[T]) -> None:\n pass\n\n\ndef func1(x: ProtoA[Never, T]) -> T:\n raise NotImplementedError\n\n\nv1 = func1(ImplB())\nassert_type(v1, list[int])\n","source":"typing_tests","origin":"conformance/tests/protocols_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_09.py","code":"\"\"\"\nTests the handling of the @runtime_checkable decorator for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#runtime-checkable-decorator-and-narrowing-types-by-isinstance\n\n# > A protocol can be used as a second argument in isinstance() and\n# > issubclass() only if it is explicitly opt-in by @runtime_checkable decorator.\n\nfrom typing import Any, Protocol, runtime_checkable\n\n\nclass Proto1(Protocol):\n name: str\n\n\n@runtime_checkable\nclass Proto2(Protocol):\n name: str\n\n\ndef func1(a: Any):\n if isinstance(a, Proto1): # E: not runtime_checkable\n return\n\n if isinstance(a, Proto2): # OK\n return\n\n\n# > isinstance() can be used with both data and non-data protocols, while\n# > issubclass() can be used only with non-data protocols.\n\n\n@runtime_checkable\nclass DataProtocol(Protocol):\n name: str\n\n def method1(self) -> int:\n ...\n\n\n@runtime_checkable\nclass NonDataProtocol(Protocol):\n def method1(self) -> int:\n ...\n\n\ndef func2(a: Any):\n if isinstance(a, DataProtocol): # OK\n return\n\n if isinstance(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, DataProtocol): # E\n return\n\n if issubclass(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, (NonDataProtocol, DataProtocol)): # E\n return\n\n\n# > Type checkers should reject an isinstance() or issubclass() call if there\n# > is an unsafe overlap between the type of the first argument and the protocol.\n\n\n@runtime_checkable\nclass Proto3(Protocol):\n def method1(self, a: int) -> int:\n ...\n\n\nclass Concrete3A:\n def method1(self, a: str) -> None:\n pass\n\n\nclass Concrete3B:\n method1: int = 1\n\n\ndef func3():\n if isinstance(Concrete3A(), Proto2): # OK\n pass\n\n if isinstance(Concrete3A(), Proto3): # E: unsafe overlap\n pass\n\n if isinstance(Concrete3B(), (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n\n if issubclass(Concrete3A, (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n","source":"typing_tests","origin":"conformance/tests/protocols_runtime_checkable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_10.py","code":"\"\"\"\nTests the handling of annotated \"self\" parameters in a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n\nfrom typing import Generic, Protocol, Self, TypeVar\n\n\nC = TypeVar(\"C\", bound=\"Copyable\")\n\n\nclass Copyable(Protocol):\n def copy(self: C) -> C:\n return self\n\n\nclass One:\n def copy(self) -> \"One\":\n return One()\n\n\nT = TypeVar(\"T\", bound=\"Other\")\n\n\nclass Other:\n def copy(self: T) -> T:\n return self\n\n\nc: Copyable\nc = One() # OK\nc = Other() # OK\n\n\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT2_co = TypeVar(\"T2_co\", covariant=True)\n\n\nclass P1Parent(Protocol[T2_co]):\n def f0(self, /) -> Self:\n ...\n\n\nclass P1Child(P1Parent[T2_co], Protocol[T2_co]):\n ...\n\n\nclass C1(Generic[T1_co]):\n def f0(self, /) -> Self:\n return self\n\n\na1: P1Parent[str] = C1[str]()\nb1: P1Child[str] = C1[str]()\n\n\nclass P2Parent(Protocol[T1_co]):\n def f0(self, right: Self, /) -> \"P2Parent[T1_co]\":\n return right\n\n\nclass P2Child(P2Parent[T1_co], Protocol[T1_co]):\n ...\n\n\nclass C2(Generic[T2_co]):\n def f0(self, other: Self) -> \"C2[T2_co]\":\n return other\n\n\na2: P2Parent[str] = C2[str]() # OK\nb2: P2Child[str] = C2[str]() # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_self.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_11.py","code":"\"\"\"\nTests subtyping rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#subtyping-relationships-with-other-types\n\n# > Protocols cannot be instantiated.\n\nfrom typing import Hashable, Iterable, Protocol, Sequence, TypeVar\n\n\nclass Proto1(Protocol):\n pass\n\n\np1 = Proto1() # E: protocol cannot be instantiated\n\n\n# > A protocol is never a subtype of a concrete type.\n\n# > A concrete type X is a subtype of protocol P if and only if X implements\n# > all protocol members of P with compatible types. In other words, subtyping\n# > with respect to a protocol is always structural.\n\n\nclass Proto2(Protocol):\n def method1(self) -> None:\n ...\n\n\nclass Concrete2:\n def method1(self) -> None:\n pass\n\n\ndef func1(p2: Proto2, c2: Concrete2):\n v1: Proto2 = c2 # OK\n v2: Concrete2 = p2 # E\n\n\n# > A protocol P1 is a subtype of another protocol P2 if P1 defines all\n# > protocol members of P2 with compatible types.\n\n\nclass Proto3(Protocol):\n def method1(self) -> None:\n ...\n\n def method2(self) -> None:\n ...\n\n\ndef func2(p2: Proto2, p3: Proto3):\n v1: Proto2 = p3 # OK\n v2: Proto3 = p2 # E\n\n\n# > Generic protocols follow the rules for generic abstract classes, except\n# > for using structural compatibility instead of compatibility defined by\n# > inheritance relationships.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n\nclass Proto4(Protocol[S, T]):\n def method1(self, a: S, b: T) -> tuple[S, T]:\n ...\n\n\nclass Proto5(Protocol[T]):\n def method1(self, a: T, b: T) -> tuple[T, T]:\n ...\n\n\ndef func3(p4_int: Proto4[int, int], p5_int: Proto5[int]):\n v1: Proto4[int, int] = p5_int # OK\n v2: Proto5[int] = p4_int # OK\n v3: Proto4[int, float] = p5_int # E\n v4: Proto5[float] = p4_int # E\n\n\nS_co = TypeVar(\"S_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Proto6(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\nclass Proto7(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\ndef func4(p6: Proto6[float, float]):\n v1: Proto7[object, int] = p6 # OK\n v2: Proto7[float, float] = p6 # OK\n v3: Proto7[complex, int] = p6 # OK\n\n v4: Proto7[int, float] = p6 # E\n v5: Proto7[float, object] = p6 # E\n\n\n# > Unions of protocol classes behaves the same way as for non-protocol classes.\n\n\nclass SupportsExit(Protocol):\n def exit(self) -> int:\n ...\n\n\nclass SupportsQuit(Protocol):\n def quit(self) -> int | None:\n ...\n\n\ndef finish(task: SupportsExit | SupportsQuit) -> int:\n return 0\n\n\nclass DefaultJob:\n def quit(self) -> int:\n return 0\n\n\nfinish(DefaultJob()) # OK\n\n\n# > One can use multiple inheritance to define an intersection of protocols.\n\n\nclass HashableFloats(Iterable[float], Hashable, Protocol):\n pass\n\n\ndef cached_func(args: HashableFloats) -> float:\n return 0.0\n\n\ncached_func((1, 2, 3)) # OK, tuple is both hashable and iterable\n","source":"typing_tests","origin":"conformance/tests/protocols_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_12.py","code":"\"\"\"\nTests type variable variance inference for generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\nfrom typing import Protocol, TypeVar\nfrom typing_extensions import ParamSpec\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", bound=int)\nT3 = TypeVar(\"T3\", bytes, str)\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT1_contra = TypeVar(\"T1_contra\", contravariant=True)\nP = ParamSpec(\"P\", contravariant=True)\nR = TypeVar(\"R\", covariant=True)\n\n# > Type checkers will warn if the inferred variance is different from the\n# > declared variance.\n\n\nclass AnotherBox(Protocol[T1]): # E: T should be covariant\n def content(self) -> T1:\n ...\n\n\nclass Protocol1(Protocol[T1, T2, T3]): # OK\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1 | T2:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n def m4(self) -> T3:\n ...\n\n\nclass Protocol2(Protocol[T1, T2, T3]): # E: T3 should be contravariant\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n\nclass Protocol3(Protocol[T1_co]):\n def m1(self) -> None:\n pass\n\n\nclass Protocol4(Protocol[T1]): # E: T1 should be contravariant\n def m1(self, p0: T1) -> None:\n ...\n\n\nclass Protocol5(Protocol[T1_co]): # E[covariant_in_input+]\n def m1(self, p0: T1_co) -> None: # E[covariant_in_input+]\n ...\n\n\nclass Protocol6(Protocol[T1]): # E: T1 should be covariant\n def m1(self) -> T1:\n ...\n\n\nclass Protocol7(Protocol[T1_contra]): # E[contravariant_in_output+]\n def m1(self) -> T1_contra: # E[contravariant_in_output+]\n ...\n\n\nclass Protocol8(Protocol[T1]): # OK\n def m1(self) -> T1:\n ...\n\n def m2(self, p1: T1) -> None:\n pass\n\n\nclass Callback(Protocol[P, R]): # OK\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\nclass Protocol9(Protocol[T1_co]): # OK\n @property\n def prop1(self) -> T1_co:\n ...\n\n\nclass Protocol10(Protocol[T1_co]): # OK\n def m1(self) -> type[T1_co]:\n ...\n\n\nclass Protocol11(Protocol[T1]): # OK\n x: T1 | None\n\n\nclass Protocol12(Protocol[T1]): # E: T1 should be covariant\n # __init__ method is exempt from variance calculations.\n def __init__(self, x: T1) -> None:\n ...\n\n\nclass Protocol13(Protocol[T1_contra]): # OK\n def m1(self: \"Protocol13[T1_contra]\", x: T1_contra) -> None:\n ...\n\n @classmethod\n def m2(cls: \"type[Protocol13[T1_contra]]\") -> None:\n ...\n\n\nclass Protocol14(Protocol[T1]): # OK\n def m1(self) -> list[T1]:\n ...\n","source":"typing_tests","origin":"conformance/tests/protocols_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_01.py","code":"\"\"\"\nTests typing.ReadOnly qualifier introduced in PEP 705.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Annotated, NotRequired, Required, TypedDict\nfrom typing_extensions import ReadOnly\n\n\n# > The ``typing.ReadOnly`` type qualifier is used to indicate that an item\n# > declared in a ``TypedDict`` definition may not be mutated (added, modified,\n# > or removed).\n\n\nclass Band(TypedDict):\n name: str\n members: ReadOnly[list[str]]\n\n\nb1: Band = {\"name\": \"blur\", \"members\": []}\n\nb1[\"name\"] = \"Blur\" # OK\nb1[\"members\"] = [\"Damon Albarn\"] # E\nb1[\"members\"].append(\"Damon Albarn\") # OK\n\n\n# > The :pep:`alternative functional syntax <589#alternative-syntax>` for\n# > TypedDict also supports the new type qualifier.\n\nBand2 = TypedDict(\"Band2\", {\"name\": str, \"members\": ReadOnly[list[str]]})\n\nb2: Band2 = {\"name\": \"blur\", \"members\": []}\n\nb2[\"name\"] = \"Blur\" # OK\nb2[\"members\"] = [\"Damon Albarn\"] # E\nb2[\"members\"].append(\"Damon Albarn\") # OK\n\n\n# > ``ReadOnly[]`` can be used with ``Required[]``, ``NotRequired[]`` and\n# > ``Annotated[]``, in any nesting order.\n\n\nclass Movie1(TypedDict):\n title: ReadOnly[Required[str]] # OK\n year: ReadOnly[NotRequired[Annotated[int, \"\"]]] # OK\n\n\nm1: Movie1 = {\"title\": \"\", \"year\": 1991}\nm1[\"title\"] = \"\" # E\nm1[\"year\"] = 1992 # E\n\n\nclass Movie2(TypedDict):\n title: Required[ReadOnly[str]] # OK\n year: Annotated[NotRequired[ReadOnly[int]], \"\"] # OK\n\n\nm2: Movie2 = {\"title\": \"\", \"year\": 1991}\nm2[\"title\"] = \"\" # E\nm2[\"year\"] = 1992 # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_02.py","code":"\"\"\"\nTests type consistency rules for TypedDict with ReadOnly items.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Any, Collection, NotRequired, Required, TypedDict\nfrom typing_extensions import ReadOnly\n\n# > A TypedDict type ``A`` is consistent with TypedDict ``B`` if ``A`` is\n# > structurally compatible with ``B``. This is true if and only if all of\n# > the following are satisfied:\n\n# > For each item in ``B``, ``A`` has the corresponding key, unless the item\n# > in ``B`` is read-only, not required, and of top value type\n# > (``ReadOnly[NotRequired[object]]``).\n\n\nclass A1(TypedDict):\n x: Required[int]\n\n\nclass B1(TypedDict):\n x: Required[int]\n y: NotRequired[str]\n\n\nclass C1(TypedDict):\n x: Required[int]\n y: ReadOnly[NotRequired[str]]\n\n\ndef func1(a: A1, b: B1, c: C1):\n v1: A1 = b # OK\n v2: A1 = c # OK\n\n v3: B1 = a # E\n v4: B1 = c # E\n\n v5: C1 = a # E\n v6: C1 = b # OK\n\n\n# > For each item in ``B``, if ``A`` has the corresponding key, the\n# > corresponding value type in ``A`` is consistent with the value type in ``B``.\n\n# (This is the same rule that applies to TypedDicts without read-only items,\n# so we will skip this redundant test.)\n\n# > For each non-read-only item in ``B``, its value type is consistent with\n# > the corresponding value type in ``A``.\n\n# (This is the same rule that applies to TypedDicts without read-only items,\n# so we will skip this redundant test.)\n\n# > For each required key in ``B``, the corresponding key is required in ``A``.\n\n# (This is the same rule that applies to TypedDicts without read-only items,\n# so we will skip this redundant test.)\n\n# > For each non-required key in ``B``, if the item is not read-only in ``B``,\n# > the corresponding key is not required in ``A``.\n\n\nclass A2(TypedDict):\n x: NotRequired[ReadOnly[str]]\n\n\nclass B2(TypedDict):\n x: NotRequired[str]\n\n\nclass C2(TypedDict):\n x: Required[str]\n\n\ndef func2(a: A2, b: B2, c: C2):\n v1: A2 = b # OK\n v2: A2 = c # OK\n\n v3: B2 = a # E\n v4: B2 = c # E\n\n v5: C2 = a # E\n v6: C2 = b # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_03.py","code":"\"\"\"\nTests inheritance rules involving typing.ReadOnly.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Collection, NotRequired, Required, TypedDict\nfrom typing_extensions import ReadOnly\n\n# > Subclasses can redeclare read-only items as non-read-only, allowing them\n# > to be mutated.\n\n\nclass NamedDict(TypedDict):\n name: ReadOnly[str]\n\n\nclass Album1(NamedDict):\n name: str\n year: int\n\n\na1: Album1 = {\"name\": \"Flood\", \"year\": 1990}\na1[\"year\"] = 1973 # OK\na1[\"name\"] = \"Dark Side Of The Moon\" # OK\n\n\n# > If a read-only item is not redeclared, it remains read-only.\n\n\nclass Album2(NamedDict):\n year: int\n\n\na2: Album2 = {\"name\": \"Flood\", \"year\": 1990}\na2[\"name\"] = \"Dark Side Of The Moon\" # E\n\n\n# > Subclasses can narrow value types of read-only items.\n\n\nclass AlbumCollection(TypedDict):\n albums: ReadOnly[Collection[Album1]]\n alt: ReadOnly[list[str | int]]\n\n\nclass RecordShop(AlbumCollection):\n name: str\n albums: ReadOnly[list[Album1]] # OK\n alt: ReadOnly[list[str]] # E\n\n\n# > Subclasses can require items that are read-only but not required in the\n# > superclass.\n\n\nclass OptionalName(TypedDict):\n name: ReadOnly[NotRequired[str]]\n\n\nclass RequiredName(OptionalName):\n name: ReadOnly[Required[str]] # OK\n\n\nd: RequiredName = {} # E\n\n\n# > Subclasses can combine these rules.\n\n\nclass OptionalIdent(TypedDict):\n ident: ReadOnly[NotRequired[str | int]]\n\n\nclass User(OptionalIdent):\n ident: str # Required, mutable, and not an int\n\n\nu: User\nu = {\"ident\": \"\"} # OK\nu[\"ident\"] = \"\" # OK\nu[\"ident\"] = 3 # E\nu = {\"ident\": 3} # E\nu = {} # E\n\n\nclass F1(TypedDict):\n a: Required[int]\n b: ReadOnly[NotRequired[int]]\n c: ReadOnly[Required[int]]\n\n\nclass F3(F1):\n a: ReadOnly[int] # E\n\n\nclass F4(F1):\n a: NotRequired[int] # E\n\n\nclass F5(F1):\n b: ReadOnly[Required[int]] # OK\n\n\nclass F6(F1):\n c: ReadOnly[NotRequired[int]] # E\n\n\nclass TD_A1(TypedDict):\n x: int\n y: ReadOnly[int]\n\n\nclass TD_A2(TypedDict):\n x: float\n y: ReadOnly[float]\n\n\nclass TD_A(TD_A1, TD_A2): ... # E: x is incompatible\n\n\nclass TD_B1(TypedDict):\n x: ReadOnly[NotRequired[int]]\n y: ReadOnly[Required[int]]\n\n\nclass TD_B2(TypedDict):\n x: ReadOnly[Required[int]]\n y: ReadOnly[NotRequired[int]]\n\n\nclass TD_B(TD_B1, TD_B2): ... # E: x is incompatible\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_04.py","code":"\"\"\"\nTests the use of unpacked TypedDicts with read-only items when used to annotate\na **kwargs parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Protocol, TypedDict, Unpack\nfrom typing_extensions import ReadOnly\n\n# > :pep:`692` introduced ``Unpack`` to annotate ``**kwargs`` with a\n# > ``TypedDict``. Marking one or more of the items of a ``TypedDict`` used\n# > in this way as read-only will have no effect on the type signature of\n# > the method. However, it *will* prevent the item from being modified in\n# > the body of the function.\n\n\nclass Args(TypedDict):\n key1: int\n key2: str\n\n\nclass ReadOnlyArgs(TypedDict):\n key1: ReadOnly[int]\n key2: ReadOnly[str]\n\n\nclass Function(Protocol):\n def __call__(self, **kwargs: Unpack[Args]) -> None: ...\n\n\ndef impl(**kwargs: Unpack[ReadOnlyArgs]) -> None:\n kwargs[\"key1\"] = 3 # E\n\n\nfn: Function = impl # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_05.py","code":"\"\"\"\nTests inheritance rules involving the update method for TypedDicts\nthat contain read-only items.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Never, NotRequired, TypedDict\nfrom typing_extensions import ReadOnly\n\n# > In addition to existing type checking rules, type checkers should error if\n# > a TypedDict with a read-only item is updated with another TypedDict that\n# > declares that key.\n\n\nclass A(TypedDict):\n x: ReadOnly[int]\n y: int\n\n\na1: A = {\"x\": 1, \"y\": 2}\na2: A = {\"x\": 3, \"y\": 4}\na1.update(a2) # E\n\n# > Unless the declared value is of bottom type (:data:`~typing.Never`).\n\n\nclass B(TypedDict):\n x: NotRequired[Never]\n y: ReadOnly[int]\n\n\ndef update_a(a: A, b: B) -> None:\n a.update(b) # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_update.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"required-notrequired","pep":"655","introduced_in":"3.11","form":"modern","file":"required-notrequired/modern_01.py","code":"\"\"\"\nTests the Required and NotRequired special forms.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#required-and-notrequired\n\nfrom typing import Annotated, NotRequired, Required, TypedDict\n\n\n# Required and NotRequired are valid only within a TypedDict.\nclass NotTypedDict:\n x: Required[int] # E: Required not allowed in this context\n\n\ndef func1(\n x: NotRequired[int], # E: NotRequired not allowed in this context\n) -> None:\n pass\n\n\nclass TD1(TypedDict, total=False):\n a: int\n\n\nclass TD2(TD1, total=True):\n b: int\n\n\nclass TD3(TypedDict):\n a: NotRequired[int]\n b: Required[int]\n\n\nclass TD4(TypedDict, total=False):\n a: int\n b: Required[int]\n\n\nclass TD5(TypedDict, total=True):\n a: NotRequired[int]\n b: int\n\n\ntd3: TD3 = {\"b\": 0}\ntd4: TD4 = {\"b\": 0}\ntd5: TD5 = {\"b\": 0}\n\n# These are all equivalent types, so they should be\n# bidirectionally type compatible.\ntd3 = td4\ntd3 = td5\ntd4 = td3\ntd4 = td5\ntd5 = td3\ntd5 = td4\n\n\nclass TD6(TypedDict):\n a: Required[Required[int]] # E: Nesting not allowed\n b: Required[NotRequired[int]] # E: Nesting not allowed\n\n\nclass TD7(TypedDict):\n # > Required[] and NotRequired[] can be used with Annotated[], in any nesting order.\n x: Annotated[Required[int], \"\"]\n y: Required[Annotated[int, \"\"]]\n z: Annotated[Required[Annotated[int, \"\"]], \"\"]\n\n\nRecursiveMovie = TypedDict(\n \"RecursiveMovie\", {\"title\": Required[str], \"predecessor\": NotRequired[\"RecursiveMovie\"]}\n)\n\nmovie: RecursiveMovie = {\"title\": \"Beethoven 3\", \"predecessor\": {\"title\": \"Beethoven 2\"}}\n","source":"typing_tests","origin":"conformance/tests/typeddicts_required.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_01.py","code":"\"\"\"\nTests for advanced or special-case usage of the typing.Self type.\n\"\"\"\n\nfrom typing import assert_type, Self\n\n\nclass ParentA:\n # Test for property that returns Self.\n @property\n def prop1(self) -> Self:\n raise NotImplementedError\n\nclass ChildA(ParentA):\n ...\n\n\nassert_type(ParentA().prop1, ParentA)\nassert_type(ChildA().prop1, ChildA)\n\n\n# Test for a child that accesses an attribute within a parent\n# whose type is annotated using Self.\nclass ParentB:\n a: list[Self]\n\n @classmethod\n def method1(cls) -> Self:\n raise NotImplementedError\n\nclass ChildB(ParentB):\n b: int = 0\n\n def method2(self) -> None:\n assert_type(self, Self)\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = self.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(self.method1(), Self)\n\n @classmethod\n def method3(cls) -> None:\n assert_type(cls, type[Self])\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = cls.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(cls.method1(), Self)\n","source":"typing_tests","origin":"conformance/tests/generics_self_advanced.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_02.py","code":"\"\"\"\nTests for usage of the typing.Self type with attributes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-attribute-annotations\n\nfrom typing import TypeVar, Generic, Self\nfrom dataclasses import dataclass\n\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass LinkedList(Generic[T]):\n value: T\n next: Self | None = None\n\n\n@dataclass\nclass OrdinalLinkedList(LinkedList[int]):\n def ordinal_value(self) -> str:\n return str(self.value)\n\n\n# This should result in a type error.\nxs = OrdinalLinkedList(value=1, next=LinkedList[int](value=2)) # E\n\nif xs.next is not None:\n xs.next = OrdinalLinkedList(value=3, next=None) # OK\n\n # This should result in a type error.\n xs.next = LinkedList[int](value=3, next=None) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_attributes.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_03.py","code":"\"\"\"\nTests for basic usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#self.\n\nfrom typing import Callable, Generic, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n\nclass Shape:\n def set_scale(self, scale: float) -> Self:\n assert_type(self, Self)\n self.scale = scale\n return self\n\n def method2(self) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n def method3(self) -> \"Shape\":\n return self\n\n @classmethod\n def from_config(cls, config: dict[str, float]) -> Self:\n assert_type(cls, type[Self])\n return cls()\n\n @classmethod\n def cls_method2(cls) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n @classmethod\n def cls_method3(cls) -> \"Shape\":\n return cls()\n\n def difference(self, other: Self) -> float:\n assert_type(other, Self)\n return 0.0\n\n def apply(self, f: Callable[[Self], None]) -> None:\n return f(self)\n\n\nclass Circle(Shape):\n pass\n\n\nassert_type(Shape().set_scale(1.0), Shape)\nassert_type(Circle().set_scale(1.0), Circle)\n\nassert_type(Shape.from_config({}), Shape)\nassert_type(Circle.from_config({}), Circle)\n\n\nclass Container(Generic[T]):\n value: T\n\n def __init__(self, value: T) -> None:\n self.value = value\n\n def set_value(self, value: T) -> Self:\n raise NotImplementedError\n\n # This should generate an error because Self isn't subscriptable.\n def foo(self, other: Self[int]) -> None: # E\n pass\n\n\ndef object_with_concrete_type(\n int_container: Container[int], str_container: Container[str]\n) -> None:\n assert_type(int_container.set_value(42), Container[int])\n assert_type(str_container.set_value(\"hello\"), Container[str])\n\n\ndef object_with_generic_type(\n container: Container[T],\n value: T,\n) -> Container[T]:\n val = container.set_value(value)\n assert_type(val, Container[T])\n return val\n","source":"typing_tests","origin":"conformance/tests/generics_self_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_04.py","code":"\"\"\"\nTests for usage of the typing.Self type with protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n\nfrom typing import Protocol, Self, assert_type\n\n\nclass ShapeProtocol(Protocol):\n def set_scale(self, scale: float) -> Self:\n ...\n\n\nclass ReturnSelf:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> Self:\n self.scale = scale\n return self\n\n\nclass ReturnConcreteShape:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> \"ReturnConcreteShape\":\n self.scale = scale\n return self\n\n\nclass BadReturnType:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> int:\n self.scale = scale\n return 42\n\n\nclass ReturnDifferentClass:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> ReturnConcreteShape:\n return ReturnConcreteShape()\n\n\ndef accepts_shape(shape: ShapeProtocol) -> None:\n y = shape.set_scale(0.5)\n assert_type(y, ShapeProtocol)\n\n\ndef main(\n return_self_shape: ReturnSelf,\n return_concrete_shape: ReturnConcreteShape,\n bad_return_type: BadReturnType,\n return_different_class: ReturnDifferentClass,\n) -> None:\n accepts_shape(return_self_shape) # OK\n accepts_shape(return_concrete_shape) # OK\n\n # This should generate a type error.\n accepts_shape(bad_return_type) # E\n\n # Not OK because it returns a non-subclass.\n accepts_shape(return_different_class) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_protocols.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_05.py","code":"\"\"\"\nTests for valid and invalid usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#valid-locations-for-self\n\nfrom typing import Any, Callable, Generic, Self, TypeAlias, TypeVar\n\nclass ReturnsSelf:\n def foo(self) -> Self: # Accepted\n return self\n\n @classmethod\n def bar(cls) -> Self: # Accepted\n return cls(1)\n\n def __new__(cls, value: int) -> Self: # Accepted\n return cls(1)\n\n def explicitly_use_self(self: Self) -> Self: # Accepted\n return self\n\n # Accepted (Self can be nested within other types)\n def returns_list(self) -> list[Self]:\n return []\n\n # Accepted (Self can be nested within other types)\n @classmethod\n def return_cls(cls) -> type[Self]:\n return cls\n\nclass Child(ReturnsSelf):\n # Accepted (we can override a method that uses Self annotations)\n def foo(self) -> Self:\n return self\n\nclass TakesSelf:\n def foo(self, other: Self) -> bool: # Accepted\n return True\n\nclass Recursive:\n # Accepted (treated as an @property returning ``Self | None``)\n next: Self | None\n\nclass CallableAttribute:\n def foo(self) -> int:\n return 0\n\n # Accepted (treated as an @property returning the Callable type)\n bar: Callable[[Self], int] = foo\n\nclass HasNestedFunction:\n x: int = 42\n\n def foo(self) -> None:\n\n # Accepted (Self is bound to HasNestedFunction).\n def nested(z: int, inner_self: Self) -> Self:\n print(z)\n print(inner_self.x)\n return inner_self\n\n nested(42, self) # OK\n\n\nclass Outer:\n class Inner:\n def foo(self) -> Self: # Accepted (Self is bound to Inner)\n return self\n\n\n# This should generate an error.\ndef foo(bar: Self) -> Self: ... # E: not within a class\n\n# This should generate an error.\nbar: Self # E: not within a class\n\nTFoo2 = TypeVar(\"TFoo2\", bound=\"Foo2\")\n\nclass Foo2:\n # Rejected (Self is treated as unknown).\n def has_existing_self_annotation(self: TFoo2) -> Self: # E\n raise NotImplementedError\n\nclass Foo3:\n def return_concrete_type(self) -> Self:\n return Foo3() # E (see FooChild below for rationale)\n\nclass Foo3Child(Foo3):\n child_value: int = 42\n\n def child_method(self) -> None:\n y = self.return_concrete_type()\n y.child_value\n\nT = TypeVar(\"T\")\n\nclass Bar(Generic[T]):\n def bar(self) -> T:\n raise NotImplementedError\n\n# This should generate an error.\nclass Baz(Bar[Self]): ... # E\n\nclass Baz2(Self): ... # E\n\n# This should generate an error.\nTupleSelf: TypeAlias = tuple[Self] # E\n\nclass Base:\n @staticmethod\n # This should generate an error.\n def make() -> Self: # E\n raise NotImplementedError\n\n @staticmethod\n # This should generate an error.\n def return_parameter(foo: Self) -> Self: # E\n raise NotImplementedError\n\nclass MyMetaclass(type):\n # This should generate an error.\n def __new__(cls, *args: Any) -> Self: # E\n raise NotImplementedError\n\n # This should generate an error.\n def __mul__(cls, count: int) -> list[Self]: # E\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_self_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_01.py","code":"\"\"\"\nTests explicit type aliases defined with `TypeAlias`.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#typealias\n\nfrom typing import Any, Callable, Concatenate, Literal, ParamSpec, TypeVar, Union, assert_type\nfrom typing import TypeAlias as TA\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1: TA = Union[int, str]\nGoodTypeAlias2: TA = int | None\nGoodTypeAlias3: TA = list[GoodTypeAlias2]\nGoodTypeAlias4: TA = list[T]\nGoodTypeAlias5: TA = tuple[T, ...] | list[T]\nGoodTypeAlias6: TA = tuple[int, int, S, T]\nGoodTypeAlias7: TA = Callable[..., int]\nGoodTypeAlias8: TA = Callable[[int, T], T]\nGoodTypeAlias9: TA = Callable[Concatenate[int, P], R]\nGoodTypeAlias10: TA = Any\nGoodTypeAlias11: TA = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12: TA = Callable[P, None]\nGoodTypeAlias13: TA = \"int | str\"\nGoodTypeAlias14: TA = list[\"int | str\"]\nGoodTypeAlias15: TA = Literal[3, 4, 5, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12,\n p13: GoodTypeAlias13,\n p14: GoodTypeAlias14,\n p15: GoodTypeAlias15,\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, Callable[..., None])\n assert_type(p13, int | str)\n assert_type(p14, list[int | str])\n assert_type(p15, Literal[3, 4, 5, None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be allowed as type aliases.\nBadTypeAlias1: TA = eval(\"\".join(map(chr, [105, 110, 116]))) # E\nBadTypeAlias2: TA = [int, str] # E\nBadTypeAlias3: TA = ((int, str),) # E\nBadTypeAlias4: TA = [int for i in range(1)] # E\nBadTypeAlias5: TA = {\"a\": \"b\"} # E\nBadTypeAlias6: TA = (lambda: int)() # E\nBadTypeAlias7: TA = [int][0] # E\nBadTypeAlias8: TA = int if 1 < 3 else str # E\nBadTypeAlias9: TA = var1 # E\nBadTypeAlias10: TA = True # E\nBadTypeAlias11: TA = 1 # E\nBadTypeAlias12: TA = list or set # E\nBadTypeAlias13: TA = f\"{'int'}\" # E\n\n\nListAlias: TA = list\nListOrSetAlias: TA = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2: ListAlias[int] # E: already specialized\nx3 = ListOrSetAlias() # E: cannot instantiate union\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_02.py","code":"\"\"\"\nTests recursive (self-referential) type aliases.\n\"\"\"\n\n# The typing specification doesn't mandate support for recursive\n# (self-referential) type aliases prior to PEP 695, but it also\n# doesn't indicates that they shouldn't work.\n# Most type checkers now support them, and many libraries and code\n# bases have started to rely on them.\n# PEP 695 formally mandates that recursive type aliases work.\n\nfrom typing import Mapping, TypeAlias, TypeVar, Union\n\nJson = Union[None, int, str, float, list[\"Json\"], dict[str, \"Json\"]]\n\nj1: Json = [1, {\"a\": 1}] # OK\nj2: Json = 3.4 # OK\nj3: Json = [1.2, None, [1.2, [\"\"]]] # OK\nj4: Json = {\"a\": 1, \"b\": 3j} # E: incompatible type\nj5: Json = [2, 3j] # E: incompatible type\n\n\n# This type alias should be equivalent to Json.\nJson2 = Union[None, int, str, float, list[\"Json2\"], dict[str, \"Json2\"]]\n\ndef func1(j1: Json) -> Json2:\n return j1\n\n\nRecursiveTuple = str | int | tuple[\"RecursiveTuple\", ...]\n\n\nt1: RecursiveTuple = (1, 1) # OK\nt2: RecursiveTuple = (1, \"1\") # OK\nt3: RecursiveTuple = (1, \"1\", 1, \"2\") # OK\nt4: RecursiveTuple = (1, (\"1\", 1), \"2\") # OK\nt5: RecursiveTuple = (1, (\"1\", 1), (1, (1, 2))) # OK\nt6: RecursiveTuple = (1, (\"1\", 1), (1, (1, [2]))) # E\nt7: RecursiveTuple = (1, [1]) # E\n\n\nRecursiveMapping = str | int | Mapping[str, \"RecursiveMapping\"]\n\nm1: RecursiveMapping = 1 # OK\nm2: RecursiveMapping = \"1\" # OK\nm3: RecursiveMapping = {\"1\": \"1\"} # OK\nm4: RecursiveMapping = {\"1\": \"1\", \"2\": 1} # OK\nm5: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {}} # OK\nm6: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": \"2\", \"2\": {}}} # OK\nm7: RecursiveMapping = {\"1\": [1]} # E\nm8: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": [1, 2]} # E\nm9: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": 1, \"2\": [1, 2, 3]}} # E\n\n\nT1 = TypeVar(\"T1\", str, int)\nT2 = TypeVar(\"T2\")\n\nGenericTypeAlias1 = list[\"GenericTypeAlias1[T1]\" | T1]\nSpecializedTypeAlias1 = GenericTypeAlias1[str]\n\ng1: SpecializedTypeAlias1 = [\"hi\", [\"hi\", \"hi\"]] # OK\ng2: GenericTypeAlias1[str] = [\"hi\", \"bye\", [\"\"], [[\"hi\"]]] # OK\ng3: GenericTypeAlias1[str] = [\"hi\", [2.4]] # E\n\nGenericTypeAlias2 = list[\"GenericTypeAlias2[T1, T2]\" | T1 | T2]\n\ng4: GenericTypeAlias2[str, int] = [[3, [\"hi\"]], \"hi\"] # OK\ng5: GenericTypeAlias2[str, float] = [[3, [\"hi\", 3.4, [3.4]]], \"hi\"] # OK\ng6: GenericTypeAlias2[str, int] = [[3, [\"hi\", 3, [3.4]]], \"hi\"] # E\n\n\nRecursiveUnion: TypeAlias = Union[\"RecursiveUnion\", int] # E: cyclical reference\n\n# On one line because different type checkers report the error on different lines\nMutualReference1: TypeAlias = Union[\"MutualReference2\", int]; MutualReference2: TypeAlias = Union[\"MutualReference1\", str] # E: cyclical reference\n","source":"typing_tests","origin":"conformance/tests/aliases_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-guard","pep":"647","introduced_in":"3.10","form":"modern","file":"type-guard/modern_01.py","code":"\"\"\"\nTests TypeGuard functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeguard\n\nfrom typing import Any, Callable, Protocol, Self, TypeGuard, TypeVar, assert_type\n\n\nT = TypeVar(\"T\")\n\ndef is_two_element_tuple(val: tuple[T, ...]) -> TypeGuard[tuple[T, T]]:\n return len(val) == 2\n\ndef func1(names: tuple[str, ...]):\n if is_two_element_tuple(names):\n assert_type(names, tuple[str, str])\n else:\n assert_type(names, tuple[str, ...])\n\n\ndef is_str_list(val: list[object], allow_empty: bool) -> TypeGuard[list[str]]:\n if len(val) == 0:\n return allow_empty\n return all(isinstance(x, str) for x in val)\n\ndef is_set_of(val: set[Any], type: type[T]) -> TypeGuard[set[T]]:\n return all(isinstance(x, type) for x in val)\n\ndef func2(val: set[object]):\n if is_set_of(val, int):\n assert_type(val, set[int])\n else:\n assert_type(val, set[object])\n\n\nT_A = TypeVar(\"T_A\", bound=\"A\")\n\nclass A:\n def tg_1(self, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @classmethod\n def tg_2(cls, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @staticmethod\n def tg_3(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n def tg4(self, val: object) -> TypeGuard[Self]:\n return isinstance(val, type(self))\n\n def tg5(self: T_A, val: object) -> TypeGuard[T_A]:\n return isinstance(val, type(self))\n\nclass B(A):\n pass\n\n# > Type checkers should assume that type narrowing should be applied to\n# > the expression that is passed as the first positional argument to a\n# > user-defined type guard. If the type guard function accepts more than\n# > one argument, no type narrowing is applied to those additional argument\n# > expressions.\n\ndef func3() -> None:\n val1 = object()\n if A().tg_1(val1):\n assert_type(val1, int)\n\n val2 = object()\n if A().tg_2(val2):\n assert_type(val2, int)\n\n val3 = object()\n if A.tg_2(val3):\n assert_type(val3, int)\n\n val4 = object()\n if A().tg_3(val4):\n assert_type(val4, int)\n\n val5 = object()\n if A.tg_3(val5):\n assert_type(val5, int)\n\n val6 = object()\n if B().tg4(val6):\n assert_type(val6, B)\n\n val7 = object()\n if B().tg4(val7):\n assert_type(val7, B)\n\n\n# > If a type guard function is implemented as an instance method or class\n# > method, the first positional argument maps to the second parameter\n# > (after “self” or “cls”).\n\nclass C:\n # Type checker should emit error here.\n def tg_1(self) -> TypeGuard[int]: # E\n return False\n\n @classmethod\n # Type checker should emit error here.\n def tg_2(cls) -> TypeGuard[int]: # E\n return False\n\n# > ``TypeGuard`` is also valid as the return type of a ``Callable`` type. In that\n# > context, it is treated as a subtype of bool. For example, ``Callable[..., TypeGuard[int]]``\n# > is assignable to ``Callable[..., bool]``.\n\n\ndef takes_callable_bool(f: Callable[[object], bool]) -> None:\n pass\n\n\ndef takes_callable_str(f: Callable[[object], str]) -> None:\n pass\n\n\ndef simple_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ntakes_callable_bool(simple_typeguard) # OK\ntakes_callable_str(simple_typeguard) # E\n\n\nclass CallableBoolProto(Protocol):\n def __call__(self, val: object) -> bool: ...\n\n\nclass CallableStrProto(Protocol):\n def __call__(self, val: object) -> str: ...\n\n\ndef takes_callable_bool_proto(f: CallableBoolProto) -> None:\n pass\n\n\ndef takes_callable_str_proto(f: CallableStrProto) -> None:\n pass\n\n\ntakes_callable_bool_proto(simple_typeguard) # OK\ntakes_callable_str_proto(simple_typeguard) # E\n\n# > Unlike ``TypeGuard``, ``TypeIs`` is invariant in its argument type:\n# > ``TypeIs[B]`` is not a subtype of ``TypeIs[A]``,\n# > even if ``B`` is a subtype of ``A``.\n\ndef takes_int_typeguard(f: Callable[[object], TypeGuard[int]]) -> None:\n pass\n\n\ndef int_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ndef bool_typeguard(val: object) -> TypeGuard[bool]:\n return isinstance(val, bool)\n\n\ntakes_int_typeguard(int_typeguard) # OK\ntakes_int_typeguard(bool_typeguard) # OK\n","source":"typing_tests","origin":"conformance/tests/narrowing_typeguard.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests Callable annotation and parameter annotations for \"def\" statements.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#callable\n\nfrom typing import (\n Any,\n Callable,\n Concatenate,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n assert_type,\n)\n\nT_contra = TypeVar(\"T_contra\", contravariant=True)\nP = ParamSpec(\"P\")\n\n\ndef func1(cb: Callable[[int, str], list[str]]) -> None:\n assert_type(cb(1, \"\"), list[str])\n\n cb(1) # E\n cb(1, 2) # E\n cb(1, \"\", 1) # E\n # Mypy reports two errors, one for each kwarg.\n cb(a=1, b=\"\") # E: bad kwarg 'a'\n\n\ndef func2(cb: Callable[[], dict[str, str]]) -> None:\n assert_type(cb(), dict[str, str])\n\n cb(1) # E\n\n\n# https://typing.readthedocs.io/en/latest/spec/callables.html#meaning-of-in-callable\n\n\n# > The Callable special form supports the use of ... in place of the list of\n# > parameter types. This indicates that the type is consistent with any input\n# > signature.\ndef func3(cb: Callable[..., list[str]]):\n assert_type(cb(), list[str])\n assert_type(cb(\"\"), list[str])\n assert_type(cb(1, \"\"), list[str])\n\n\ndef func4(*args: int, **kwargs: int) -> None:\n assert_type(args, tuple[int, ...])\n assert_type(kwargs, dict[str, int])\n\n\nv1: Callable[int] # E\nv2: Callable[int, int] # E\nv3: Callable[[], [int]] # E\nv4: Callable[int, int, int] # E\nv5: Callable[[...], int] # E\n\n\ndef test_cb1(x: int) -> str:\n return \"\"\n\n\ndef test_cb2() -> str:\n return \"\"\n\n\ncb1: Callable[..., str]\ncb1 = test_cb1 # OK\ncb1 = test_cb2 # OK\n\ncb2: Callable[[], str] = cb1 # OK\n\n# > A ... can also be used with Concatenate. In this case, the parameters prior\n# > to the ... are required to be present in the input signature and be\n# > compatible in kind and type, but any additional parameters are permitted.\n\n\ndef test_cb3(a: int, b: int, c: int) -> str:\n return \"\"\n\n\ndef test_cb4(*, a: int) -> str:\n return \"\"\n\n\ncb3: Callable[Concatenate[int, ...], str]\ncb3 = test_cb1 # OK\ncb3 = test_cb2 # E\ncb3 = test_cb3 # OK\ncb3 = test_cb4 # E\n\n# > If the input signature in a function definition includes both a *args and\n# > **kwargs parameter and both are typed as Any (explicitly or implicitly\n# > because it has no annotation), a type checker should treat this as the\n# > equivalent of `...`. Any other parameters in the signature are unaffected\n# > and are retained as part of the signature.\n\n\nclass Proto1(Protocol):\n def __call__(self, *args: Any, **kwargs: Any) -> None: ...\n\n\nclass Proto2(Protocol):\n def __call__(self, a: int, /, *args, **kwargs) -> None: ...\n\n\nclass Proto3(Protocol):\n def __call__(self, a: int, *args: Any, **kwargs: Any) -> None: ...\n\n\nclass Proto4[**P](Protocol):\n def __call__(self, a: int, *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n\nclass Proto5(Protocol[T_contra]):\n def __call__(self, *args: T_contra, **kwargs: T_contra) -> None: ...\n\n\nclass Proto6(Protocol):\n def __call__(self, a: int, /, *args: Any, k: str, **kwargs: Any) -> None:\n pass\n\n\nclass Proto7(Protocol):\n def __call__(self, a: float, /, b: int, *, k: str, m: str) -> None:\n pass\n\n\nclass Proto8(Protocol):\n def __call__(self) -> None: ...\n\n\ndef func5(\n p1: Proto1,\n p2: Proto2,\n p3: Proto3,\n p4: Proto4[...],\n p5: Proto5[Any],\n p7: Proto7,\n p8: Proto8,\n c1: Callable[..., None],\n c2: Callable[Concatenate[int, ...], None],\n):\n ok1: Callable[..., None] = p1 # OK\n ok2: Proto1 = c1 # OK\n ok3: Callable[..., None] = p5 # OK\n ok4: Proto5[Any] = c1 # OK\n ok5: Callable[Concatenate[int, ...], None] = p2 # OK\n ok6: Proto2 = c2 # OK\n ok7: Callable[..., None] = p3 # OK\n ok8: Proto3 = c1 # OK\n ok9: Proto4[...] = p3 # OK\n ok10: Proto3 = p4 # OK\n ok11: Proto6 = p7 # OK\n\n err1: Proto5[Any] = p8 # E\n\n\n# > The ... syntax can also be used to provide a specialized value for a\n# > ParamSpec in a generic class or type alias.\n\n\nCallback1: TypeAlias = Callable[P, str]\nCallback2: TypeAlias = Callable[Concatenate[int, P], str]\n\n\ndef func6(cb1: Callable[[], str], cb2: Callable[[int], str]) -> None:\n f1: Callback1[...] = cb1 # OK\n f2: Callback2[...] = cb1 # E\n\n f3: Callback1[...] = cb2 # OK\n f4: Callback2[...] = cb2 # OK\n\n\n# > If ... is used with signature concatenation, the ... portion continues\n# > to mean “any conceivable set of parameters that could be compatible”.\n\nCallbackWithInt: TypeAlias = Callable[Concatenate[int, P], str]\nCallbackWithStr: TypeAlias = Callable[Concatenate[str, P], str]\n\n\ndef func7(cb: Callable[[int, str], str]) -> None:\n f1: Callable[Concatenate[int, ...], str] = cb # OK\n f2: Callable[Concatenate[str, ...], str] = cb # E\n f3: CallbackWithInt[...] = cb # OK\n f4: CallbackWithStr[...] = cb # E\n","source":"typing_tests","origin":"conformance/tests/callables_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests subtyping rules for callables.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#subtyping-rules-for-callables\n\nfrom typing import Callable, ParamSpec, Protocol, TypeAlias, overload\n\nP = ParamSpec(\"P\")\n\n# > Callable types are covariant with respect to their return types but\n# > contravariant with respect to their parameter types.\n\n\ndef func1(\n cb1: Callable[[float], int],\n cb2: Callable[[float], float],\n cb3: Callable[[int], int],\n) -> None:\n f1: Callable[[int], float] = cb1 # OK\n f2: Callable[[int], float] = cb2 # OK\n f3: Callable[[int], float] = cb3 # OK\n\n f4: Callable[[float], float] = cb1 # OK\n f5: Callable[[float], float] = cb2 # OK\n f6: Callable[[float], float] = cb3 # E\n\n f7: Callable[[int], int] = cb1 # OK\n f8: Callable[[int], int] = cb2 # E\n f9: Callable[[int], int] = cb3 # OK\n\n\n# > Callable A is a subtype of callable B if all keyword-only parameters in B\n# > are present in A as either keyword-only parameters or standard (positional\n# > or keyword) parameters.\n\n\nclass PosOnly2(Protocol):\n def __call__(self, b: int, a: int, /) -> None: ...\n\n\nclass KwOnly2(Protocol):\n def __call__(self, *, b: int, a: int) -> None: ...\n\n\nclass Standard2(Protocol):\n def __call__(self, a: int, b: int) -> None: ...\n\n\ndef func2(standard: Standard2, pos_only: PosOnly2, kw_only: KwOnly2):\n f1: Standard2 = pos_only # E\n f2: Standard2 = kw_only # E\n\n f3: PosOnly2 = standard # OK\n f4: PosOnly2 = kw_only # E\n\n f5: KwOnly2 = standard # OK\n f6: KwOnly2 = pos_only # E\n\n\n# > If a callable B has a signature with a *args parameter, callable A\n# > must also have a *args parameter to be a subtype of B, and the type of\n# > B’s *args parameter must be a subtype of A’s *args parameter.\n\n\nclass NoArgs3(Protocol):\n def __call__(self) -> None: ...\n\n\nclass IntArgs3(Protocol):\n def __call__(self, *args: int) -> None: ...\n\n\nclass FloatArgs3(Protocol):\n def __call__(self, *args: float) -> None: ...\n\n\ndef func3(no_args: NoArgs3, int_args: IntArgs3, float_args: FloatArgs3):\n f1: NoArgs3 = int_args # OK\n f2: NoArgs3 = float_args # OK\n\n f3: IntArgs3 = no_args # E: missing *args parameter\n f4: IntArgs3 = float_args # OK\n\n f5: FloatArgs3 = no_args # E: missing *args parameter\n f6: FloatArgs3 = int_args # E: float is not subtype of int\n\n\n# > If a callable B has a signature with one or more positional-only parameters,\n# > a callable A is a subtype of B if A has an *args parameter whose type is a\n# > supertype of the types of any otherwise-unmatched positional-only parameters\n# > in B.\n\n\nclass PosOnly4(Protocol):\n def __call__(self, a: int, b: str, /) -> None: ...\n\n\nclass IntArgs4(Protocol):\n def __call__(self, *args: int) -> None: ...\n\n\nclass IntStrArgs4(Protocol):\n def __call__(self, *args: int | str) -> None: ...\n\n\nclass StrArgs4(Protocol):\n def __call__(self, a: int, /, *args: str) -> None: ...\n\n\nclass Standard4(Protocol):\n def __call__(self, a: int, b: str) -> None: ...\n\n\ndef func4(int_args: IntArgs4, int_str_args: IntStrArgs4, str_args: StrArgs4):\n f1: PosOnly4 = int_args # E: str is not subtype of int\n f2: PosOnly4 = int_str_args # OK\n f3: PosOnly4 = str_args # OK\n f4: IntStrArgs4 = str_args # E: int | str is not subtype of str\n f5: IntStrArgs4 = int_args # E: int | str is not subtype of int\n f6: StrArgs4 = int_str_args # OK\n f7: StrArgs4 = int_args # E: str is not subtype of int\n f8: IntArgs4 = int_str_args # OK\n f9: IntArgs4 = str_args # E: int is not subtype of str\n f10: Standard4 = int_str_args # E: keyword parameters a and b missing\n f11: Standard4 = str_args # E: keyword parameter b missing\n\n\n# > If a callable B has a signature with a **kwargs parameter (without an\n# > unpacked TypedDict type annotation), callable A must also have a **kwargs\n# > parameter to be a subtype of B, and the type of B’s **kwargs parameter\n# > must be a subtype of A’s **kwargs parameter.\n\n\nclass NoKwargs5(Protocol):\n def __call__(self) -> None: ...\n\n\nclass IntKwargs5(Protocol):\n def __call__(self, **kwargs: int) -> None: ...\n\n\nclass FloatKwargs5(Protocol):\n def __call__(self, **kwargs: float) -> None: ...\n\n\ndef func5(no_kwargs: NoKwargs5, int_kwargs: IntKwargs5, float_kwargs: FloatKwargs5):\n f1: NoKwargs5 = int_kwargs # OK\n f2: NoKwargs5 = float_kwargs # OK\n\n f3: IntKwargs5 = no_kwargs # E: missing **kwargs parameter\n f4: IntKwargs5 = float_kwargs # OK\n\n f5: FloatKwargs5 = no_kwargs # E: missing **kwargs parameter\n f6: FloatKwargs5 = int_kwargs # E: float is not subtype of int\n\n\n# > If a callable B has a signature with one or more keyword-only parameters,\n# > a callable A is a subtype of B if A has a **kwargs parameter whose type\n# > is a supertype of the types of any otherwise-unmatched keyword-only\n# > parameters in B.\n\n\nclass KwOnly6(Protocol):\n def __call__(self, *, a: int, b: str) -> None: ...\n\n\nclass IntKwargs6(Protocol):\n def __call__(self, **kwargs: int) -> None: ...\n\n\nclass IntStrKwargs6(Protocol):\n def __call__(self, **kwargs: int | str) -> None: ...\n\n\nclass StrKwargs6(Protocol):\n def __call__(self, *, a: int, **kwargs: str) -> None: ...\n\n\nclass Standard6(Protocol):\n def __call__(self, a: int, b: str) -> None: ...\n\n\ndef func6(\n int_kwargs: IntKwargs6, int_str_kwargs: IntStrKwargs6, str_kwargs: StrKwargs6\n):\n f1: KwOnly6 = int_kwargs # E: str is not subtype of int\n f2: KwOnly6 = int_str_kwargs # OK\n f3: KwOnly6 = str_kwargs # OK\n f4: IntStrKwargs6 = str_kwargs # E: int | str is not subtype of str\n f5: IntStrKwargs6 = int_kwargs # E: int | str is not subtype of int\n f6: StrKwargs6 = int_str_kwargs # OK\n f7: StrKwargs6 = int_kwargs # E: str is not subtype of int\n f8: IntKwargs6 = int_str_kwargs # OK\n f9: IntKwargs6 = str_kwargs # E: int is not subtype of str\n f10: Standard6 = int_str_kwargs # E: Does not accept positional arguments\n f11: Standard6 = str_kwargs # E: Does not accept positional arguments\n\n\n# > A signature that includes *args: P.args, **kwargs: P.kwargs is equivalent\n# > to a Callable parameterized by P.\n\n\nclass ProtocolWithP[**P](Protocol):\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n\nTypeAliasWithP: TypeAlias = Callable[P, None]\n\n\ndef func7(proto: ProtocolWithP[P], ta: TypeAliasWithP[P]):\n # These two types are equivalent\n f1: TypeAliasWithP[P] = proto # OK\n f2: ProtocolWithP[P] = ta # OK\n\n\n# > If a callable A has a parameter x with a default argument value and B is\n# > the same as A except that x has no default argument, then A is a subtype\n# > of B. A is also a subtype of C if C is the same as A with parameter x\n# > removed.\n\n\nclass DefaultArg8(Protocol):\n def __call__(self, x: int = 0) -> None: ...\n\n\nclass NoDefaultArg8(Protocol):\n def __call__(self, x: int) -> None: ...\n\n\nclass NoX8(Protocol):\n def __call__(self) -> None: ...\n\n\ndef func8(default_arg: DefaultArg8, no_default_arg: NoDefaultArg8, no_x: NoX8):\n f1: DefaultArg8 = no_default_arg # E\n f2: DefaultArg8 = no_x # E\n\n f3: NoDefaultArg8 = default_arg # OK\n f4: NoDefaultArg8 = no_x # E\n\n f5: NoX8 = default_arg # OK\n f6: NoX8 = no_default_arg # E\n\n\n# > If a callable A is overloaded with two or more signatures, it is a subtype\n# > of callable B if at least one of the overloaded signatures in A is a\n# > subtype of B.\n\n\nclass Overloaded9(Protocol):\n @overload\n def __call__(self, x: int) -> int: ...\n @overload\n def __call__(self, x: str) -> str: ...\n\n\nclass IntArg9(Protocol):\n def __call__(self, x: int) -> int: ...\n\n\nclass StrArg9(Protocol):\n def __call__(self, x: str) -> str: ...\n\n\nclass FloatArg9(Protocol):\n def __call__(self, x: float) -> float: ...\n\n\ndef func9(overloaded: Overloaded9):\n f1: IntArg9 = overloaded # OK\n f2: StrArg9 = overloaded # OK\n f3: FloatArg9 = overloaded # E\n\n\n# > If a callable B is overloaded with two or more signatures, callable A is\n# > a subtype of B if A is a subtype of all of the signatures in B.\n\n\nclass Overloaded10(Protocol):\n @overload\n def __call__(self, x: int, y: str) -> float: ...\n @overload\n def __call__(self, x: str) -> complex: ...\n\n\nclass StrArg10(Protocol):\n def __call__(self, x: str) -> complex: ...\n\n\nclass IntStrArg10(Protocol):\n def __call__(self, x: int | str, y: str = \"\") -> int: ...\n\n\ndef func10(int_str_arg: IntStrArg10, str_arg: StrArg10):\n f1: Overloaded10 = int_str_arg # OK\n f2: Overloaded10 = str_arg # E\n","source":"typing_tests","origin":"conformance/tests/callables_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_24.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_25.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-is","pep":"742","introduced_in":"3.13","form":"modern","file":"type-is/modern_01.py","code":"\"\"\"\nTests TypeIs functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeis\n\nfrom collections.abc import Awaitable\nfrom typing import Any, Callable, Protocol, Self, TypeGuard, TypeVar, assert_type\nfrom typing_extensions import TypeIs\n\n\nT = TypeVar(\"T\")\n\ndef is_two_element_tuple(val: tuple[T, ...]) -> TypeIs[tuple[T, T]]:\n return len(val) == 2\n\ndef func1(names: tuple[str, str] | tuple[str, str, str]):\n if is_two_element_tuple(names):\n assert_type(names, tuple[str, str])\n else:\n assert_type(names, tuple[str, str, str])\n\n\n# > The final narrowed type may be narrower than **R**, due to the constraints of the\n# > argument's previously-known type\n\ndef is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:\n return isinstance(val, Awaitable)\n\nasync def func2(val: int | Awaitable[int]):\n if is_awaitable(val):\n # Not `assert_type(val, Awaitable[int])` because a conformant\n # implementation could allow the possibility that instead it is\n # `int & Awaitable[Any]`, an awaitable subclass of int.\n x: int = await val\n return x\n else:\n # We can't say much here. The strictly correct answer is\n # (int | Awaitable[int]) & ~Awaitable[Any], but conformant implementations\n # may simplify this.\n # But it should definitely remain assignable to `int | Awaitable[int]`.\n y: int | Awaitable[int] = val\n return y\n\n\nT_A = TypeVar(\"T_A\", bound=\"A\")\n\nclass A:\n def tg_1(self, val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n @classmethod\n def tg_2(cls, val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n @staticmethod\n def tg_3(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n def tg4(self, val: object) -> TypeIs[Self]:\n return isinstance(val, type(self))\n\n def tg5(self: T_A, val: object) -> TypeIs[T_A]:\n return isinstance(val, type(self))\n\nclass B(A):\n pass\n\n# > The type narrowing behavior is applied to the first positional argument\n# > passed to the function. The function may accept additional arguments,\n# > but they are not affected by type narrowing.\n\n\ndef func3() -> None:\n val1 = object()\n if A().tg_1(val1):\n assert_type(val1, int)\n\n val2 = object()\n if A().tg_2(val2):\n assert_type(val2, int)\n\n val3 = object()\n if A.tg_2(val3):\n assert_type(val3, int)\n\n val4 = object()\n if A().tg_3(val4):\n assert_type(val4, int)\n\n val5 = object()\n if A.tg_3(val5):\n assert_type(val5, int)\n\n val6 = object()\n if B().tg4(val6):\n assert_type(val6, B)\n\n val7 = object()\n if B().tg4(val7):\n assert_type(val7, B)\n\n\n# > If a type narrowing function\n# > is implemented as an instance method or class method, the first positional\n# > argument maps to the second parameter (after self or cls).\n\nclass C:\n # Type checker should emit error here.\n def tg_1(self) -> TypeIs[int]: # E\n return False\n\n @classmethod\n # Type checker should emit error here.\n def tg_2(cls) -> TypeIs[int]: # E\n return False\n\n# > ``TypeIs`` is also valid as the return type of a callable, for example\n# > in callback protocols and in the ``Callable`` special form. In these\n# > contexts, it is treated as a subtype of bool. For example, ``Callable[..., TypeIs[int]]``\n# > is assignable to ``Callable[..., bool]``.\n\n\ndef takes_callable_bool(f: Callable[[object], bool]) -> None:\n pass\n\n\ndef takes_callable_str(f: Callable[[object], str]) -> None:\n pass\n\n\ndef simple_typeguard(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n\ntakes_callable_bool(simple_typeguard) # OK\ntakes_callable_str(simple_typeguard) # E\n\n\nclass CallableBoolProto(Protocol):\n def __call__(self, val: object) -> bool: ...\n\n\nclass CallableStrProto(Protocol):\n def __call__(self, val: object) -> str: ...\n\n\ndef takes_callable_bool_proto(f: CallableBoolProto) -> None:\n pass\n\n\ndef takes_callable_str_proto(f: CallableStrProto) -> None:\n pass\n\n\ntakes_callable_bool_proto(simple_typeguard) # OK\ntakes_callable_str_proto(simple_typeguard) # E\n\n# TypeIs and TypeGuard are not compatible with each other.\n\ndef takes_typeguard(f: Callable[[object], TypeGuard[int]]) -> None:\n pass\n\ndef takes_typeis(f: Callable[[object], TypeIs[int]]) -> None:\n pass\n\ndef is_int_typeis(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\ndef is_int_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\ntakes_typeguard(is_int_typeguard) # OK\ntakes_typeguard(is_int_typeis) # E\ntakes_typeis(is_int_typeguard) # E\ntakes_typeis(is_int_typeis) # OK\n\n\n# > Unlike ``TypeGuard``, ``TypeIs`` is invariant in its argument type:\n# > ``TypeIs[B]`` is not a subtype of ``TypeIs[A]``,\n# > even if ``B`` is a subtype of ``A``.\n\ndef takes_int_typeis(f: Callable[[object], TypeIs[int]]) -> None:\n pass\n\n\ndef int_typeis(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n\ndef bool_typeis(val: object) -> TypeIs[bool]:\n return isinstance(val, bool)\n\n\ntakes_int_typeis(int_typeis) # OK\ntakes_int_typeis(bool_typeis) # E\n\n# > It is an error to narrow to a type that is not consistent with the input type\n\ndef bad_typeis(x: int) -> TypeIs[str]: # E\n return isinstance(x, str)\n\n\ndef bad_typeis_variance(x: list[object]) -> TypeIs[list[int]]: # E\n return all(isinstance(x, int) for x in x)\n","source":"typing_tests","origin":"conformance/tests/narrowing_typeis.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_15.py","code":"\"\"\"\nTests for basic usage of default values for TypeVar-like's.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#defaults-for-type-parameters.\n\nfrom typing import Any, Callable, Generic, Self, Unpack, assert_type\nfrom typing_extensions import TypeVar, ParamSpec, TypeVarTuple\n\n\nDefaultStrT = TypeVar(\"DefaultStrT\", default=str)\nDefaultIntT = TypeVar(\"DefaultIntT\", default=int)\nDefaultBoolT = TypeVar(\"DefaultBoolT\", default=bool)\nT = TypeVar(\"T\")\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\n\n# > The order for defaults should follow the standard function parameter\n# > rules, so a type parameter with no ``default`` cannot follow one with\n# > a ``default`` value. Doing so may raise a ``TypeError`` at runtime,\n# > and a type checker should flag this as an error.\n\n\nclass NonDefaultFollowsDefault(Generic[DefaultStrT, T]): ... # E: non-default TypeVars cannot follow ones with defaults\n\n\nclass NoNonDefaults(Generic[DefaultStrT, DefaultIntT]):\n x: DefaultStrT\n y: DefaultIntT\n\n\ndef test_no_non_defaults(a: NoNonDefaults, b: NoNonDefaults[str], c: NoNonDefaults[str, int]):\n assert_type(a.x, str)\n assert_type(a.y, int)\n\n assert_type(b.x, str)\n assert_type(b.y, int)\n\n assert_type(c.x, str)\n assert_type(c.y, int)\n\n\nclass OneDefault(Generic[T, DefaultBoolT]):\n x: T\n y: DefaultBoolT\n\n\ndef test_one_default(a: OneDefault[float], b: OneDefault[float, bool]):\n assert_type(a.x, float)\n assert_type(a.y, bool)\n\n assert_type(b.x, float)\n assert_type(b.y, bool)\n\n\nclass AllTheDefaults(Generic[T1, T2, DefaultStrT, DefaultIntT, DefaultBoolT]):\n x1: T1\n x2: T2\n x3: DefaultStrT\n x4: DefaultIntT\n x5: DefaultBoolT\n\n\ndef test_all_the_defaults(\n a: AllTheDefaults,\n b: AllTheDefaults[int], # E: expected 2 arguments to AllTheDefaults\n c: AllTheDefaults[int, complex],\n d: AllTheDefaults[int, complex, str, int, bool],\n e: AllTheDefaults[int, complex, str],\n f: AllTheDefaults[int, complex, str, int],\n g: AllTheDefaults[int, complex, str, int, bool],\n):\n assert_type(a.x1, Any)\n assert_type(a.x2, Any)\n assert_type(a.x3, str)\n assert_type(a.x4, int)\n assert_type(a.x5, bool)\n\n assert_type(c.x1, int)\n assert_type(c.x2, complex)\n assert_type(c.x3, str)\n assert_type(c.x4, int)\n assert_type(c.x5, bool)\n\n assert_type(d.x1, int)\n assert_type(d.x2, complex)\n assert_type(d.x3, str)\n assert_type(d.x4, int)\n assert_type(d.x5, bool)\n\n assert_type(e.x1, int)\n assert_type(e.x2, complex)\n assert_type(e.x3, str)\n assert_type(e.x4, int)\n assert_type(e.x5, bool)\n\n assert_type(f.x1, int)\n assert_type(f.x2, complex)\n assert_type(f.x3, str)\n assert_type(f.x4, int)\n assert_type(f.x5, bool)\n\n assert_type(g.x1, int)\n assert_type(g.x2, complex)\n assert_type(g.x3, str)\n assert_type(g.x4, int)\n assert_type(g.x5, bool)\n\n\n# > ``ParamSpec`` defaults are defined using the same syntax as\n# > ``TypeVar`` \\ s but use a ``list`` of types or an ellipsis\n# > literal \"``...``\" or another in-scope ``ParamSpec``.\n\nDefaultP = ParamSpec(\"DefaultP\", default=[str, int])\n\n\nclass Class_ParamSpec(Generic[DefaultP]):\n x: Callable[DefaultP, None]\n\n\ndef test_param_spec_defaults(a: Class_ParamSpec):\n assert_type(a.x, Callable[[str, int], None])\n assert_type(Class_ParamSpec(), Class_ParamSpec[str, int])\n assert_type(Class_ParamSpec[[bool, bool]](), Class_ParamSpec[bool, bool])\n\n\n# > ``TypeVarTuple`` defaults are defined using the same syntax as\n# > ``TypeVar`` \\ s, but instead of a single type, they use an unpacked tuple\n# > of types or an unpacked, in-scope ``TypeVarTuple`` (see `Scoping Rules`_).\n\nDefaultTs = TypeVarTuple(\"DefaultTs\", default=Unpack[tuple[str, int]])\n\n\nclass Class_TypeVarTuple(Generic[*DefaultTs]):\n x: tuple[*DefaultTs]\n\n\ndef test_type_var_tuple_defaults(a: Class_TypeVarTuple):\n assert_type(a.x, tuple[str, int])\n assert_type(Class_TypeVarTuple(), Class_TypeVarTuple[str, int])\n assert_type(Class_TypeVarTuple[int, bool](), Class_TypeVarTuple[int, bool])\n\n\nAnotherDefaultTs = TypeVarTuple(\"AnotherDefaultTs\", default=Unpack[DefaultTs])\n\n\n# > If both ``bound`` and ``default`` are passed, ``default`` must be a\n# > subtype of ``bound``. If not, the type checker should generate an\n# > error.\n\nOk1 = TypeVar(\"Ok1\", bound=float, default=int) # OK\nInvalid1 = TypeVar(\"Invalid1\", bound=str, default=int) # E: the bound and default are incompatible\n\n# > For constrained ``TypeVar``\\ s, the default needs to be one of the\n# > constraints. A type checker should generate an error even if it is a\n# > subtype of one of the constraints.\n\nOk2 = TypeVar(\"Ok2\", float, str, default=float) # OK\nInvalid2 = TypeVar(\"Invalid2\", float, str, default=int) # E: expected one of float or str got int\n\n\n# > In generic functions, type checkers may use a type parameter's default when the\n# > type parameter cannot be solved to anything. We leave the semantics of this\n# > usage unspecified, as ensuring the ``default`` is returned in every code path\n# > where the type parameter can go unsolved may be too hard to implement. Type\n# > checkers are free to either disallow this case or experiment with implementing\n# > support.\n\nT4 = TypeVar(\"T4\", default=int)\n\n\ndef func1(x: int | set[T4]) -> T4:\n raise NotImplementedError\n\n\nassert_type(func1(0), int) # E[optional-default-use]\nassert_type(func1(0), Any) # E[optional-default-use]\n\n\n# > A ``TypeVar`` that immediately follows a ``TypeVarTuple`` is not allowed\n# > to have a default, because it would be ambiguous whether a type argument\n# > should be bound to the ``TypeVarTuple`` or the defaulted ``TypeVar``.\n\nTs = TypeVarTuple(\"Ts\")\nT5 = TypeVar(\"T5\", default=bool)\n\n\nclass Foo5(Generic[*Ts, T5]): ... # E\n\n\n# > It is allowed to have a ``ParamSpec`` with a default following a\n# > ``TypeVarTuple`` with a default, as there can be no ambiguity between a\n# > type argument for the ``ParamSpec`` and one for the ``TypeVarTuple``.\n\nP = ParamSpec(\"P\", default=[float, bool])\n\n\nclass Foo6(Generic[*Ts, P]):\n x: tuple[*Ts]\n y: Callable[P, None]\n\n\ndef test_foo6(a: Foo6[int, str], b: Foo6[int, str, [bytes]]):\n assert_type(a.x, tuple[int, str])\n assert_type(a.y, Callable[[float, bool], None])\n\n assert_type(b.x, tuple[int, str])\n assert_type(b.y, Callable[[bytes], None])\n\n\n# > Type parameter defaults should be bound by attribute access\n# > (including call and subscript).\n\n\nclass Foo7(Generic[DefaultIntT]):\n def meth(self, /) -> Self:\n return self\n\n attr: DefaultIntT\n\n\nfoo7 = Foo7()\nassert_type(Foo7.meth(foo7), Foo7[int])\nassert_type(Foo7().attr, int)\n","source":"typing_tests","origin":"conformance/tests/generics_defaults.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_16.py","code":"\"\"\"\nTests for type parameter default values that reference other type parameters.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#defaults-for-type-parameters.\n\n# > To use another type parameter as a default the ``default`` and the\n# > type parameter must be the same type (a ``TypeVar``'s default must be\n# > a ``TypeVar``, etc.).\n\nfrom typing import Any, Generic, assert_type\nfrom typing_extensions import TypeVar\n\nDefaultStrT = TypeVar(\"DefaultStrT\", default=str)\nStartT = TypeVar(\"StartT\", default=int)\nStopT = TypeVar(\"StopT\", default=StartT)\nStepT = TypeVar(\"StepT\", default=int | None)\n\n\nclass slice(Generic[StartT, StopT, StepT]): ...\n\n\nassert_type(slice(), slice[int, int, int | None])\nassert_type(slice[str](), slice[str, str, int | None])\nassert_type(slice[str, bool, complex](), slice[str, bool, complex])\n\nT2 = TypeVar(\"T2\", default=DefaultStrT)\n\n\nclass Foo(Generic[DefaultStrT, T2]):\n def __init__(self, a: DefaultStrT, b: T2) -> None: ...\n\n\ndef func1(i: int, s: str) -> None:\n assert_type(Foo(i, s), Foo[int, str])\n Foo[int](i, s) # E: Foo[int, str] cannot be assigned to self: Foo[int, int] in Foo.__init__\n Foo[int](s, i) # E: Foo[str, int] cannot be assigned to self: Foo[int, int] in Foo.__init__\n\n\n# > ``T1`` must be used before ``T2`` in the parameter list of the generic.\n\nS1 = TypeVar(\"S1\")\nS2 = TypeVar(\"S2\", default=S1)\n\n\nclass Foo2(Generic[S1, S2]): ... # OK\n\n\nStart2T = TypeVar(\"Start2T\", default=\"StopT\")\nStop2T = TypeVar(\"Stop2T\", default=int)\n\n\nclass slice2(Generic[Start2T, Stop2T, StepT]): ... # E: bad ordering\n\n\n# > Using a type parameter from an outer scope as a default is not supported.\n\n\nclass Foo3(Generic[S1]):\n class Bar2(Generic[S2]): ... # E\n\n\n# > ``T1``'s bound must be a subtype of ``T2``'s bound.\n\nX1 = TypeVar(\"X1\", bound=int)\nOk1 = TypeVar(\"Ok1\", default=X1, bound=float) # OK\nAlsoOk1 = TypeVar(\"AlsoOk1\", default=X1, bound=int) # OK\nInvalid1 = TypeVar(\"Invalid1\", default=X1, bound=str) # E: int is not a subtype of str\n\n\n# > The constraints of ``T2`` must be a superset of the constraints of ``T1``.\n\nY1 = TypeVar(\"Y1\", bound=int)\nInvalid2 = TypeVar(\"Invalid2\", float, str, default=Y1) # E: upper bound int is incompatible with constraints float or str\n\nY2 = TypeVar(\"Y2\", int, str)\nAlsoOk2 = TypeVar(\"AlsoOk2\", int, str, bool, default=Y2) # OK\nAlsoInvalid2 = TypeVar(\"AlsoInvalid2\", bool, complex, default=Y2) # E: {bool, complex} is not a superset of {int, str}\n\n\n# > Type parameters are valid as parameters to generics inside of a\n# > ``default`` when the first parameter is in scope as determined by the\n# > `previous section `_.\n\n\nZ1 = TypeVar(\"Z1\")\nListDefaultT = TypeVar(\"ListDefaultT\", default=list[Z1]) # OK\n\n\nclass Bar(Generic[Z1, ListDefaultT]): # OK\n x: Z1\n y: ListDefaultT\n def __init__(self, x: Z1, y: ListDefaultT): ...\n\n\ndef f(b1: Bar, b2: Bar[int]):\n assert_type(b1.x, Any)\n assert_type(b1.y, list[Any])\n assert_type(b2.x, int)\n assert_type(b2.y, list[int])\n\n\nassert_type(Bar[int](0, []), Bar[int, list[int]])\nassert_type(Bar[int, list[str]](0, []), Bar[int, list[str]])\nassert_type(Bar[int, str](0, \"\"), Bar[int, str])\n","source":"typing_tests","origin":"conformance/tests/generics_defaults_referential.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_17.py","code":"\"\"\"\nTests for specialization rules associated with type parameters with\ndefault values.\n\"\"\"\n\n# > A generic type alias can be further subscripted following normal subscription\n# > rules. If a type parameter has a default that hasn't been overridden, it should\n# > be treated like it was substituted into the type alias.\n\nfrom typing import Generic, TypeAlias, assert_type\nfrom typing_extensions import TypeVar\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nDefaultIntT = TypeVar(\"DefaultIntT\", default=int)\nDefaultStrT = TypeVar(\"DefaultStrT\", default=str)\n\n\nclass SomethingWithNoDefaults(Generic[T1, T2]): ...\n\n\nMyAlias: TypeAlias = SomethingWithNoDefaults[int, DefaultStrT] # OK\n\n\ndef func1(p1: MyAlias, p2: MyAlias[bool]):\n assert_type(p1, SomethingWithNoDefaults[int, str])\n assert_type(p2, SomethingWithNoDefaults[int, bool])\n\n\nMyAlias[bool, int] # E: too many arguments passed to MyAlias\n\n\n# > Generic classes with type parameters that have defaults behave similarly\n# > generic type aliases. That is, subclasses can be further subscripted following\n# > normal subscription rules, non-overridden defaults should be substituted.\n\n\nclass SubclassMe(Generic[T1, DefaultStrT]):\n x: DefaultStrT\n\n\nclass Bar(SubclassMe[int, DefaultStrT]): ...\n\n\nx1: type[Bar[str]] = Bar # ok\n# Type checkers may take type context into account when deciding how to\n# specialize a bare runtime reference to a generic class.\nx2: type[Bar[int]] = Bar # E?\nassert_type(Bar(), Bar[str])\nassert_type(Bar[bool](), Bar[bool])\n\n\nclass Foo(SubclassMe[float]): ...\n\n\nassert_type(Foo().x, str)\n\nFoo[str] # E: Foo cannot be further subscripted\n\n\nclass Baz(Generic[DefaultIntT, DefaultStrT]): ...\n\n\nclass Spam(Baz): ...\n\n\n# Spam is \nv1: Baz[int, str] = Spam()\n","source":"typing_tests","origin":"conformance/tests/generics_defaults_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_15.py","code":"\"\"\"\nTests the \"type\" statement introduced in Python 3.12.\n\"\"\"\n\nfrom typing import Callable, TypeVar\n\n\ntype GoodAlias1 = int\ntype GoodAlias2[S1, *S2, **S3] = Callable[S3, S1] | tuple[*S2]\ntype GoodAlias3 = GoodAlias2[int, tuple[int, str], ...]\n\n\nclass ClassA:\n type GoodAlias4 = int | None\n\n\nGoodAlias1.bit_count # E: cannot access attribute\n\nGoodAlias1() # E: cannot call alias\n\nprint(GoodAlias1.__value__) # OK\nprint(GoodAlias1.__type_params__) # OK\nprint(GoodAlias1.other_attrib) # E: unknown attribute\n\n\nclass DerivedInt(GoodAlias1): # E: cannot use alias as base class\n pass\n\n\ndef func2(x: object):\n if isinstance(x, GoodAlias1): # E: cannot use alias in isinstance\n pass\n\nvar1 = 1\n\n# The following should not be allowed as type aliases.\ntype BadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116]))) # E\ntype BadTypeAlias2 = [int, str] # E\ntype BadTypeAlias3 = ((int, str),) # E\ntype BadTypeAlias4 = [int for i in range(1)] # E\ntype BadTypeAlias5 = {\"a\": \"b\"} # E\ntype BadTypeAlias6 = (lambda: int)() # E\ntype BadTypeAlias7 = [int][0] # E\ntype BadTypeAlias8 = int if 1 < 3 else str # E\ntype BadTypeAlias9 = var1 # E\ntype BadTypeAlias10 = True # E\ntype BadTypeAlias11 = 1 # E\ntype BadTypeAlias12 = list or set # E\ntype BadTypeAlias13 = f\"{'int'}\" # E\n\nV = TypeVar(\"V\")\n\ntype TA1[K] = dict[K, V] # E: combines old and new TypeVars\n\n\nT1 = TypeVar(\"T1\")\n\ntype TA2 = list[T1] # E: uses old TypeVar\n\n\ntype RecursiveTypeAlias1[T] = T | list[RecursiveTypeAlias1[T]]\n\nr1_1: RecursiveTypeAlias1[int] = 1\nr1_2: RecursiveTypeAlias1[int] = [1, [1, 2, 3]]\n\ntype RecursiveTypeAlias2[S: int, T: str, **P] = Callable[P, T] | list[S] | list[RecursiveTypeAlias2[S, T, P]]\n\nr2_1: RecursiveTypeAlias2[str, str, ...] # E: not compatible with S bound\nr2_2: RecursiveTypeAlias2[int, str, ...]\nr2_3: RecursiveTypeAlias2[int, int, ...] # E: not compatible with T bound\nr2_4: RecursiveTypeAlias2[int, str, [int, str]]\n\ntype RecursiveTypeAlias3 = RecursiveTypeAlias3 # E: circular definition\n\ntype RecursiveTypeAlias4[T] = T | RecursiveTypeAlias4[str] # E: circular definition\n\ntype RecursiveTypeAlias5[T] = T | list[RecursiveTypeAlias5[T]]\n\ntype RecursiveTypeAlias6 = RecursiveTypeAlias7 # E[RTA6+]: circular definition\ntype RecursiveTypeAlias7 = RecursiveTypeAlias6 # E[RTA6+]: circular definition\n","source":"typing_tests","origin":"conformance/tests/aliases_type_statement.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_16.py","code":"\"\"\"\nTests the TypeAliasType call introduced in Python 3.12.\n\"\"\"\n\nfrom typing import Callable, Generic, ParamSpec, TypeAliasType, TypeVar, TypeVarTuple\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nTStr = TypeVar(\"TStr\", bound=str)\nP = ParamSpec(\"P\")\nTs = TypeVarTuple(\"Ts\")\n\nmy_tuple = (S, T)\nvar1 = 3\n\nGoodAlias1 = TypeAliasType(\"GoodAlias1\", int)\nGoodAlias2 = TypeAliasType(\"GoodAlias2\", list[T], type_params=(T,))\nGoodAlias3 = TypeAliasType(\"GoodAlias3\", list[T] | list[S], type_params=(S, T))\nGoodAlias4 = TypeAliasType(\"GoodAlias4\", T | \"list[GoodAlias4[T]]\", type_params=(T,))\nGoodAlias5 = TypeAliasType(\n \"GoodAlias5\",\n Callable[P, TStr] | list[S] | list[\"GoodAlias5[S, TStr, P]\"] | tuple[*Ts],\n type_params=(S, TStr, P, Ts),\n)\n\nclass ClassA(Generic[T]):\n GoodAlias6 = TypeAliasType(\"GoodAlias6\", list[T])\n\n\nprint(GoodAlias1.__value__) # OK\nprint(GoodAlias1.__type_params__) # OK\nprint(GoodAlias1.other_attrib) # E: unknown attribute\n\n\nx1: GoodAlias4[int] = 1 # OK\nx2: GoodAlias4[int] = [1] # OK\nx3: GoodAlias5[str, str, ..., int, str] # OK\nx4: GoodAlias5[int, str, ..., int, str] # OK\nx5: GoodAlias5[int, str, [int, str], *tuple[int, str, int]] # OK\nx6: GoodAlias5[int, int, ...] # E: incorrect type arguments\n\n\nBadAlias1 = TypeAliasType(\"BadAlias1\", list[S], type_params=(T,)) # E: S not in scope\nBadAlias2 = TypeAliasType(\"BadAlias2\", list[S]) # E: S not in scope\nBadAlias3 = TypeAliasType(\"BadAlias3\", int, type_params=my_tuple) # E: not literal tuple\nBadAlias4 = TypeAliasType(\"BadAlias4\", \"BadAlias4\") # E: circular dependency\nBadAlias5 = TypeAliasType(\"BadAlias5\", T | \"BadAlias5[str]\", type_params=(T,)) # E: circular dependency\nBadAlias6 = TypeAliasType(\"BadAlias6\", \"BadAlias7\") # E: circular dependency\nBadAlias7 = TypeAliasType(\"BadAlias7\", BadAlias6) # E?: circular dependency\n\n# The following are invalid type expressions for a type alias.\nBadAlias8 = TypeAliasType(\"BadAlias8\", eval(\"\".join(map(chr, [105, 110, 116])))) # E\nBadAlias9 = TypeAliasType(\"BadAlias9\", [int, str]) # E\nBadAlias10 = TypeAliasType(\"BadAlias10\", ((int, str),)) # E\nBadAlias11 = TypeAliasType(\"BadAlias11\", [int for i in range(1)]) # E\nBadAlias12 = TypeAliasType(\"BadAlias12\", {\"a\": \"b\"}) # E\nBadAlias13 = TypeAliasType(\"BadAlias13\", (lambda: int)()) # E\nBadAlias14 = TypeAliasType(\"BadAlias14\", [int][0]) # E\nBadAlias15 = TypeAliasType(\"BadAlias15\", int if 1 < 3 else str) # E\nBadAlias16 = TypeAliasType(\"BadAlias16\", var1) # E\nBadAlias17 = TypeAliasType(\"BadAlias17\", True) # E\nBadAlias18 = TypeAliasType(\"BadAlias18\", 1) # E\nBadAlias19 = TypeAliasType(\"BadAlias19\", list or set) # E\nBadAlias20 = TypeAliasType(\"BadAlias20\", f\"{'int'}\") # E\n\nBadAlias21 = TypeAliasType(\"BadAlias21\", list[BadAlias21]) # E\n","source":"typing_tests","origin":"conformance/tests/aliases_typealiastype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_17.py","code":"\"\"\"\nTests the compatibility rules between type parameter syntax (introduced in PEP 695)\nand traditional TypeVars.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#compatibility-with-traditional-typevars\n\nfrom typing import TypeVar\n\n\nK = TypeVar(\"K\")\n\n\nclass ClassA[V](dict[K, V]): # E: traditional TypeVar not allowed here\n ...\n\n\nclass ClassB[K, V](dict[K, V]): # OK\n ...\n\n\nclass ClassC[V]:\n def method1(self, a: V, b: K) -> V | K: # OK\n raise NotImplementedError\n\n def method2[M](self, a: M, b: K) -> M | K: # E\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_compatibility.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_18.py","code":"\"\"\"\nValidates the type parameter syntax introduced in PEP 695.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#type-parameter-declarations\n\n\n# This generic class is parameterized by a TypeVar T, a\n# TypeVarTuple Ts, and a ParamSpec P.\nfrom typing import Generic, Protocol\n\n\nclass ChildClass[T, *Ts, **P]:\n pass\n\n\nclass ClassA[T](Generic[T]): # E: Runtime error\n ...\n\n\nclass ClassB[S, T](Protocol): # OK\n ...\n\n\nclass ClassC[S, T](Protocol[S, T]): # E\n ...\n\n\nclass ClassD[T: str]:\n def method1(self, x: T):\n x.capitalize() # OK\n x.is_integer() # E\n\n\nclass ClassE[T: dict[str, int]]: # OK\n pass\n\n\nclass ClassF[S: ForwardReference[int], T: \"ForwardReference[str]\"]: # OK\n ...\n\n\nclass ClassG[V]:\n class ClassD[T: dict[str, V]]: # E: generic type not allowed\n ...\n\n\nclass ClassH[T: [str, int]]: # E: illegal expression form\n ...\n\n\nclass ClassI[AnyStr: (str, bytes)]: # OK\n ...\n\n\nclass ClassJ[T: (ForwardReference[int], \"ForwardReference[str]\", bytes)]: # OK\n ...\n\n\nclass ClassK[T: ()]: # E: two or more types required\n ...\n\n\nclass ClassL[T: (str,)]: # E: two or more types required\n ...\n\n\nt1 = (bytes, str)\n\n\nclass ClassM[T: t1]: # E: literal tuple expression required\n ...\n\n\nclass ClassN[T: (3, bytes)]: # E: invalid expression form\n ...\n\n\nclass ClassO[T: (list[S], str)]: # E: generic type\n ...\n\n\nclass ForwardReference[T]: ...\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_declarations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_19.py","code":"\"\"\"\nTests the handling of \"infer_variance\" parameter for TypeVar.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#auto-variance-for-typevar\n\nfrom typing import Final, Generic, Iterator, overload, Sequence, TypeVar\nfrom dataclasses import dataclass\n\n\nT = TypeVar(\"T\", infer_variance=True)\nK = TypeVar(\"K\", infer_variance=True)\nV = TypeVar(\"V\", infer_variance=True)\n\nS1 = TypeVar(\"S1\", covariant=True, infer_variance=True) # E: cannot use covariant with infer_variance\n\nS2 = TypeVar(\"S2\", contravariant=True, infer_variance=True) # E: cannot use contravariant with infer_variance\n\n\nclass ShouldBeCovariant1(Generic[T]):\n def __getitem__(self, index: int) -> T:\n raise NotImplementedError\n\n def __iter__(self) -> Iterator[T]:\n raise NotImplementedError\n\n\nvco1_1: ShouldBeCovariant1[float] = ShouldBeCovariant1[int]() # OK\nvco1_2: ShouldBeCovariant1[int] = ShouldBeCovariant1[float]() # E\n\n\nclass ShouldBeCovariant2(Sequence[T]):\n @overload\n def __getitem__(self, index: int) -> T:\n ...\n @overload\n def __getitem__(self, index: slice) -> Sequence[T]:\n ...\n def __getitem__(self, index: int | slice) -> T | Sequence[T]:\n raise NotImplementedError\n\n def __len__(self) -> int:\n raise NotImplementedError\n\n\nvco2_1: ShouldBeCovariant2[float] = ShouldBeCovariant2[int]() # OK\nvco2_2: ShouldBeCovariant2[int] = ShouldBeCovariant2[float]() # E\n\n\nclass ShouldBeCovariant3(Generic[T]):\n def method1(self) -> \"ShouldBeCovariant2[T]\":\n raise NotImplementedError\n\n\nvco3_1: ShouldBeCovariant3[float] = ShouldBeCovariant3[int]() # OK\nvco3_2: ShouldBeCovariant3[int] = ShouldBeCovariant3[float]() # E\n\n\n@dataclass(frozen=True)\nclass ShouldBeCovariant4(Generic[T]):\n x: T\n\n\n# This test is problematic as of Python 3.13 because of the\n# newly synthesized \"__replace__\" method, which causes the type\n# variable to be inferred as invariant rather than covariant.\n# See https://github.com/python/mypy/issues/17623#issuecomment-2266312738\n# for details. Until we sort this out, we'll leave this test commented\n# out.\n\n# vo4_1: ShouldBeCovariant4[float] = ShouldBeCovariant4[int](1) # OK\n# vo4_4: ShouldBeCovariant4[int] = ShouldBeCovariant4[float](1.0) # E\n\n\nclass ShouldBeCovariant5(Generic[T]):\n def __init__(self, x: T) -> None:\n self._x = x\n\n @property\n def x(self) -> T:\n return self._x\n\n\nvo5_1: ShouldBeCovariant5[float] = ShouldBeCovariant5[int](1) # OK\nvo5_2: ShouldBeCovariant5[int] = ShouldBeCovariant5[float](1.0) # E\n\n\nclass ShouldBeCovariant6(Generic[T]):\n x: Final[T]\n\n def __init__(self, value: T):\n self.x = value\n\n\nvo6_1: ShouldBeCovariant6[float] = ShouldBeCovariant6[int](1) # OK\nvo6_2: ShouldBeCovariant6[int] = ShouldBeCovariant6[float](1.0) # E\n\n\nclass ShouldBeInvariant1(Generic[T]):\n def __init__(self, value: T) -> None:\n self._value = value\n\n @property\n def value(self) -> T:\n return self._value\n\n @value.setter\n def value(self, value: T):\n self._value = value\n\n\nvinv1_1: ShouldBeInvariant1[float] = ShouldBeInvariant1[int](1) # E\nvinv1_2: ShouldBeInvariant1[int] = ShouldBeInvariant1[float](1.1) # E\n\n\nclass ShouldBeInvariant2(Generic[T]):\n def __init__(self, value: T) -> None:\n self._value = value\n\n def get_value(self) -> T:\n return self._value\n\n def set_value(self, value: T):\n self._value = value\n\n\nvinv2_1: ShouldBeInvariant2[float] = ShouldBeInvariant2[int](1) # E\nvinv2_2: ShouldBeInvariant2[int] = ShouldBeInvariant2[float](1.1) # E\n\n\nclass ShouldBeInvariant3(dict[K, V]):\n pass\n\n\nvinv3_1: ShouldBeInvariant3[float, str] = ShouldBeInvariant3[int, str]() # E\nvinv3_2: ShouldBeInvariant3[int, str] = ShouldBeInvariant3[float, str]() # E\nvinv3_3: ShouldBeInvariant3[str, float] = ShouldBeInvariant3[str, int]() # E\nvinv3_4: ShouldBeInvariant3[str, int] = ShouldBeInvariant3[str, float]() # E\n\n\n@dataclass\nclass ShouldBeInvariant4[T]:\n x: T\n\n\nvinv4_1: ShouldBeInvariant4[float] = ShouldBeInvariant4[int](1) # E\n\n\nclass ShouldBeInvariant5[T]:\n def __init__(self, x: T) -> None:\n self.x = x\n\n\nvinv5_1: ShouldBeInvariant5[float] = ShouldBeInvariant5[int](1) # E\n\n\nclass ShouldBeContravariant1(Generic[T]):\n def __init__(self, value: T) -> None:\n pass\n\n def set_value(self, value: T):\n pass\n\n\nvcontra1_1: ShouldBeContravariant1[float] = ShouldBeContravariant1[int](1) # E\nvcontra1_2: ShouldBeContravariant1[int] = ShouldBeContravariant1[float](1.2) # OK\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_infer_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_20.py","code":"\"\"\"\nTests the scoping rules for type parameter syntax introduced in PEP 695.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#type-parameter-scopes\n\nfrom typing import Callable, Mapping, Sequence, TypeVar, assert_type\n\n# > A compiler error or runtime exception is generated if the definition\n# > of an earlier type parameter references a later type parameter even\n# > if the name is defined in an outer scope.\n\n\nclass ClassA[S, T: Sequence[S]]: # E\n ...\n\n\nclass ClassB[S: Sequence[T], T]: # E\n ...\n\n\nclass Foo[T]:\n ...\n\n\nprint(T) # E: Runtime error: 'T' is not defined\n\n\ndef decorator1[\n T, **P, R\n](x: type[Foo[T]]) -> Callable[[Callable[P, R]], Callable[P, R]]:\n raise NotImplementedError\n\n\n@decorator1(Foo[T]) # E: Runtime error: 'T' is not defined\nclass ClassD[T]:\n ...\n\n\ntype Alias1[K, V] = Mapping[K, V] | Sequence[K]\n\n\nS: int = int(0)\n\n\ndef outer1[S](x: str):\n S: str = x\n T: int = 1\n\n def outer2[T]():\n def inner1():\n nonlocal S # OK\n assert_type(S, str)\n # nonlocal T # Syntax error\n\n def inner2():\n global S # OK\n assert_type(S, int)\n\n\nclass Outer1:\n class Private:\n pass\n\n class Inner[T](Private, Sequence[T]): # OK\n pass\n\n def method1[T](self, a: Inner[T]) -> Inner[T]: # OK\n return a\n\n\ndef decorator2[**P, R](x: int) -> Callable[[Callable[P, R]], Callable[P, R]]:\n raise NotImplementedError\n\n\nT = int(0)\n\n\n@decorator2(T) # OK\nclass ClassE[T](Sequence[T]):\n T = int(1)\n\n def method1[T](self): # E\n ...\n\n def method2[T](self, x=T): # E\n ...\n\n def method3[T](self, x: T): # E\n ...\n\n\nT = int(0)\n\n\ndef f(a: int, b: str, c: complex):\n class Outer2[T]:\n T = a\n\n assert_type(T, int)\n\n class Inner1:\n T = b\n\n assert_type(T, str)\n\n def inner_method(self):\n assert_type(T, TypeVar)\n\n def outer_method(self):\n T = c\n\n assert_type(T, complex)\n\n def inner_func():\n assert_type(T, complex)\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_13.py","code":"\"\"\"\nTests the \"alternative\" (non-class) syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#alternative-syntax\n\nfrom typing import TypedDict\n\n\nMovie = TypedDict(\"Movie\", {\"name\": str, \"year\": int, \"illegal key name\": bool})\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982, \"illegal key name\": True}\n\nMovieOptional = TypedDict(\"MovieOptional\", {\"name\": str, \"year\": int}, total=False)\n\nmovie_opt1: MovieOptional = {}\nmovie_opt2: MovieOptional = {\"year\": 1982}\n\n# > A type checker is only expected to accept a dictionary display expression as\n# > the second argument to TypedDict. In particular, a variable that refers to a\n# > dictionary object does not need to be supported, to simplify implementation.\nmy_dict = {\"name\": str}\nBadTypedDict1 = TypedDict(\"BadTypedDict1\", my_dict) # E\n\n\n# This should generate an error because it uses a non-str key.\nBadTypedDict2 = TypedDict(\"BadTypedDict2\", {1: str}) # E\n\n\n# This should generate an error because it uses a non-matching name.\nBadTypedDict3 = TypedDict(\"WrongName\", {\"name\": str}) # E\n\n\n# This should generate an error because of the additional parameter.\nBadTypedDict4 = TypedDict(\"BadTypedDict4\", {\"name\": str}, total=False, other=False) # E\n\n\n# > The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13.\n# > It may also be unsupported by static type checkers.\n\nMovie2 = TypedDict(\"Movie2\", name=str, year=int) # E?\n\nmovie2: Movie2\nmovie2 = {\"name\": \"Blade Runner\", \"year\": 1982} # E?: May generate errors if keyword-argument syntax is unsupported\nmovie2 = {\"name\": \"Blade Runner\", \"year\": \"\"} # E?: Incorrect type for year\n","source":"typing_tests","origin":"conformance/tests/typeddicts_alt_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_14.py","code":"\"\"\"\nTests the class syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import Generic, TypeVar, TypedDict\nimport sys\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n # > String literal forward references are valid in the value types.\n director: \"Person\"\n\n\nclass Person(TypedDict):\n name: str\n age: int\n\n\n# > Methods are not allowed, since the runtime type of a TypedDict object\n# > will always be just dict (it is never a subclass of dict).\nclass BadTypedDict1(TypedDict):\n name: str\n\n # Methods are not allowed, so this should generate an error.\n def method1(self): # E\n pass\n\n # Methods are not allowed, so this should generate an error.\n @classmethod # E[method2]\n def method2(cls): # E[method2]\n pass\n\n # Methods are not allowed, so this should generate an error.\n @staticmethod # E[method3]\n def method3(): # E[method3]\n pass\n\n\nclass CustomMeta(type):\n pass\n\n\n# > Specifying a custom metaclass is not allowed.\nclass BadTypedDict2(TypedDict, metaclass=CustomMeta): # E\n name: str\n\n\n# This should generate an error because \"other\" is not an allowed keyword argument.\nclass BadTypedDict3(TypedDict, other=True): # E\n name: str\n\n# > `if` conditions that the type checker is able to\n# > statically evaluate are also permitted (e.g. `if sys.version_info > (3, 14)`),\n# > in order to specify items that exist only under the given conditions.\nclass ConditionalField(TypedDict):\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nConditionalField(x=1, y=2)\nConditionalField(x=1, y=2, z=3) # E\n\n\n# > TypedDicts may be made generic by adding Generic[T] among the bases.\nT = TypeVar(\"T\")\n\n\nclass GenericTypedDict(TypedDict, Generic[T]):\n name: str\n value: T\n\n\n# > An empty TypedDict can be created by only including pass in the\n# > body (if there is a docstring, pass can be omitted):\nclass EmptyDict1(TypedDict):\n pass\n\n\nclass EmptyDict2(TypedDict):\n \"\"\"Docstring\"\"\"\n\n\nclass MovieTotal(TypedDict, total=True):\n name: str\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n","source":"typing_tests","origin":"conformance/tests/typeddicts_class_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_15.py","code":"\"\"\"\nTests inheritance rules for TypedDict classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclass BookBasedMovie(Movie):\n based_on: str\n\nclass BookBasedMovieAlso(TypedDict):\n name: str\n year: int\n based_on: str\n\nb1: BookBasedMovie = {\"name\": \"Little Women\", \"year\": 2019, \"based_on\": \"Little Women\"}\n\nb2: BookBasedMovieAlso = b1\n\n\nclass X(TypedDict):\n x: int\n\nclass Y(TypedDict):\n y: str\n\nclass XYZ(X, Y):\n z: bool\n\nx1 = XYZ(x=1, y=\"\", z=True)\n\n# > A TypedDict cannot inherit from both a TypedDict type and a\n# > non-TypedDict base class other than Generic.\n\nclass NonTypedDict:\n pass\n\nclass BadTypedDict(TypedDict, NonTypedDict): # E\n pass\n\n\n# > Changing a field type of a parent TypedDict class in a subclass is\n# > not allowed.\n\nclass X1(TypedDict):\n x: str\n\nclass Y1(X1): # E[Y1]\n x: int # E[Y1]: cannot overwrite TypedDict field \"x\"\n\n\n# > Multiple inheritance does not allow conflict types for the same name field:\nclass X2(TypedDict):\n x: int\n\nclass Y2(TypedDict):\n x: str\n\nclass XYZ2(X2, Y2): # E: cannot overwrite TypedDict field \"x\" while merging\n xyz: bool\n","source":"typing_tests","origin":"conformance/tests/typeddicts_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_16.py","code":"\"\"\"\nTests operations provided by a TypedDict object.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#supported-and-unsupported-operations\n\n\nfrom typing import TypedDict, assert_type\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie\n\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982}\nmovie[\"name\"] = \"Other\"\nmovie[\"year\"] = 1981\n\nmovie[\"name\"] = 1982 # E: wrong type\nmovie[\"year\"] = \"\" # E: wrong type\nmovie[\"other\"] = \"\" # E: unknown key added\n\nprint(movie[\"other\"]) # E: unknown key referenced\n\nmovie = {\"name\": \"Blade Runner\"} # E: year is missing\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982.1} # E: year is wrong type\n\n# > The use of a key that is not known to exist should be reported as an error.\nmovie = {\"name\": \"\", \"year\": 1900, \"other\": 2} # E: extra key\n\n\ndef func1(variable_key: str):\n # > A key that is not a literal should generally be rejected.\n movie: Movie = {variable_key: \"\", \"year\": 1900} # E: variable key\n\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"name\")\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"other\") # E?\n\n\nmovie.clear() # E: clear not allowed\n\ndel movie[\"name\"] # E: del not allowed for required key\n\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n year: int\n\n\nmovie_optional: MovieOptional = {}\n\nassert_type(movie_optional.get(\"name\"), str | None)\n\nmovie_optional.clear() # E: clear not allowed\n\ndel movie_optional[\"name\"]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_operations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_17.py","code":"\"\"\"\nTests the type consistency rules for TypedDict objects.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#type-consistency\n\nfrom typing import Any, Literal, Mapping, TypedDict\n\n\nclass A1(TypedDict):\n x: int | None\n\n\nclass B1(TypedDict):\n x: int\n\n\nb1: B1 = {\"x\": 0}\n\n# > Value types behave invariantly.\na1: A1 = b1 # E: 'B1' not compatible with 'A1'\n\n# > any TypedDict type is consistent with Mapping[str, object]\nv1: Mapping[str, object] = b1\n\n# > A TypedDict type with a required key is not consistent with a TypedDict\n# > type where the same key is a non-required key.\n\nclass A2(TypedDict, total=False):\n x: int\n\n\nclass B2(TypedDict):\n x: int\n\n\nb2: B2 = {\"x\": 0}\na2: A2 = b2 # E: 'B2' not compatible with 'A2'\n\n\n# > A TypedDict type A is consistent with TypedDict B if A is structurally\n# > compatible with B. This is true if and only if both of these conditions\n# > are satisfied:\n# > 1. For each key in B, A has the corresponding key and the corresponding\n# > value type in A is consistent with the value type in B. For each key in B,\n# > the value type in B is also consistent with the corresponding value type\n# > in A.\n# > 2. For each required key in B, the corresponding key is required in A. For\n# > each non-required key in B, the corresponding key is not required in A.\n\n\nclass A3(TypedDict):\n x: int\n\n\nclass B3(TypedDict):\n x: int\n y: int\n\n\nb3: B3 = {\"x\": 0, \"y\": 0}\na3: A3 = b3\n\na3 = {\"x\": 0}\nb3 = a3 # E\n\n\n# This should generate an error because it's a literal assignment.\na3_1: A3 = {\"x\": 0, \"y\": 0} # E\n\n# This should not generate an error.\na3_2 = b3\n\n# > A TypedDict isn’t consistent with any Dict[...] type.\n\nd1: dict[str, int] = b3 # E\nd2: dict[str, object] = b3 # E\nd3: dict[Any, Any] = b3 # E\n\n# > A TypedDict with all int values is not consistent with Mapping[str, int].\n\nm1: Mapping[str, int] = b3 # E\nm2: Mapping[str, object] = b3 # OK\nm3: Mapping[str, Any] = b3 # OK\n\n\n# Test \"get\" method.\nUserType1 = TypedDict(\"UserType1\", {\"name\": str, \"age\": int}, total=False)\nuser1: UserType1 = {\"name\": \"Bob\", \"age\": 40}\n\nname1: str = user1.get(\"name\", \"n/a\")\nage1: int = user1.get(\"age\", 42)\n\nUserType2 = TypedDict(\"UserType2\", {\"name\": str, \"age\": int})\nuser2: UserType2 = {\"name\": \"Bob\", \"age\": 40}\n\nname2: str | None = user2.get(\"name\")\n\n# The spec does not say whether type checkers should adjust the return type of `.get()`\n# to exclude `None` if it is known that the key exists. Either option is acceptable.\nname3: str = user2.get(\"name\") # E?\n\nage2: int = user2.get(\"age\", 42)\n\nage3: int | str = user2.get(\"age\", \"42\")\n\nage4: int = user2.get(\"age\", \"42\") # E?\n\n# Test nested TypedDicts.\nclass Inner1(TypedDict):\n inner_key: str\n\n\nclass Inner2(TypedDict):\n inner_key: Inner1\n\n\nclass Outer1(TypedDict):\n outer_key: Inner2\n\n\no1: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": \"hi\"}}}\n\n# This should generate an error because the inner-most value\n# should be a string.\no2: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": 1}}} # E\n\n\nclass Inner3(TypedDict):\n x: int\n\n\nclass Inner4(TypedDict):\n x: int\n\n\nclass Outer2(TypedDict):\n y: str\n z: Literal[\"\"] | Inner3\n\n\nclass Outer3(TypedDict):\n y: str\n z: Literal[\"\"] | Inner4\n\n\ndef func1(td: Outer3):\n ...\n\n\no3: Outer2 = {\"y\": \"\", \"z\": {\"x\": 0}}\no4: Outer3 = o3\n","source":"typing_tests","origin":"conformance/tests/typeddicts_type_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_18.py","code":"\"\"\"\nTests for basic usage of TypedDict.\n\"\"\"\n\nfrom typing import TypeVar, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982}\n\n\ndef record_movie(movie: Movie) -> None:\n ...\n\n\nrecord_movie({\"name\": \"Blade Runner\", \"year\": 1982})\n\n\nmovie[\"director\"] = \"Ridley Scott\" # E: invalid key 'director'\nmovie[\"year\"] = \"1982\" # E: invalid value type (\"int\" expected)\n\n# The code below should be rejected, since 'title' is not a valid key,\n# and the 'name' key is missing:\nmovie2: Movie = {\"title\": \"Blade Runner\", \"year\": 1982} # E\n\nm = Movie(name='Blade Runner', year=1982)\n\n\n# > TypedDict type objects cannot be used in isinstance() tests such as\n# > isinstance(d, Movie).\nif isinstance(movie, Movie): # E\n pass\n\n\n# TypedDict should not be allowed as a bound for a TypeVar.\nT = TypeVar(\"T\", bound=TypedDict) # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"typed-kwargs","pep":"692","introduced_in":"3.12","form":"modern","file":"typed-kwargs/modern_01.py","code":"\"\"\"\nTests the use of an unpacked TypedDict for annotating **kwargs.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#unpack-for-keyword-arguments\n\n# This sample tests the handling of Unpack[TypedDict] when used with\n# a **kwargs parameter in a function signature.\n\nfrom typing import Protocol, TypeVar, TypedDict, NotRequired, Required, Unpack, assert_type\n\n\nclass TD1(TypedDict):\n v1: Required[int]\n v2: NotRequired[str]\n\n\nclass TD2(TD1):\n v3: Required[str]\n\n\ndef func1(**kwargs: Unpack[TD2]) -> None:\n v1 = kwargs[\"v1\"]\n assert_type(v1, int)\n\n # > Type checkers may allow reading an item using ``d['x']`` even if\n # > the key ``'x'`` is not required\n kwargs[\"v2\"] # E?: v2 may not be present\n\n if \"v2\" in kwargs:\n v2 = kwargs[\"v2\"]\n assert_type(v2, str)\n\n v3 = kwargs[\"v3\"]\n assert_type(v3, str)\n\n\ndef func2(v3: str, **kwargs: Unpack[TD1]) -> None:\n # > When Unpack is used, type checkers treat kwargs inside the function\n # > body as a TypedDict.\n assert_type(kwargs, TD1)\n\n\ndef func3() -> None:\n # Mypy reports multiple errors here.\n func1() # E: missing required keyword args\n func1(v1=1, v2=\"\", v3=\"5\") # OK\n\n td2 = TD2(v1=2, v3=\"4\")\n func1(**td2) # OK\n func1(v1=1, v2=\"\", v3=\"5\", v4=5) # E?: v4 is not in TD2, but could be in a subtype\n func1(1, \"\", \"5\") # E: args not passed by position\n\n # > Passing a dictionary of type dict[str, object] as a **kwargs argument\n # > to a function that has **kwargs annotated with Unpack must generate a\n # > type checker error.\n my_dict: dict[str, str] = {}\n func1(**my_dict) # E: untyped dict\n\n d1 = {\"v1\": 2, \"v3\": \"4\", \"v4\": 4}\n func1(**d1) # E?: OK or Type error (spec allows either)\n func2(**td2) # OK\n func1(v1=2, **td2) # E: v1 is already specified\n func2(1, **td2) # E: v1 is already specified\n func2(v1=1, **td2) # E: v1 is already specified\n\n\nclass TDProtocol1(Protocol):\n def __call__(self, *, v1: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol2(Protocol):\n def __call__(self, *, v1: int, v3: str, v2: str = \"\") -> None:\n ...\n\n\nclass TDProtocol3(Protocol):\n def __call__(self, *, v1: int, v2: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol4(Protocol):\n def __call__(self, *, v1: int) -> None:\n ...\n\n\nclass TDProtocol5(Protocol):\n def __call__(self, v1: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol6(Protocol):\n def __call__(self, **kwargs: Unpack[TD2]) -> None:\n ...\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#assignment\n\nv1: TDProtocol1 = func1 # OK\nv2: TDProtocol2 = func1 # OK\nv3: TDProtocol3 = func1 # E: v2 is wrong type\nv4: TDProtocol4 = func1 # E: v3 is missing\nv5: TDProtocol5 = func1 # E: params are positional\nv6: TDProtocol6 = func1 # OK\n\n\ndef func4(v1: int, /, **kwargs: Unpack[TD2]) -> None:\n ...\n\n\ndef func5(v1: int, **kwargs: Unpack[TD2]) -> None: # E: parameter v1 overlaps with the TypedDict.\n ...\n\n\nT = TypeVar(\"T\", bound=TD2)\n\n# > TypedDict is the only permitted heterogeneous type for typing **kwargs.\n# > Therefore, in the context of typing **kwargs, using Unpack with types other\n# > than TypedDict should not be allowed and type checkers should generate\n# > errors in such cases.\n\ndef func6(**kwargs: Unpack[T]) -> None: # E: unpacked value must be a TypedDict, not a TypeVar bound to TypedDict.\n ...\n\n# > The situation where the destination callable contains **kwargs: Unpack[TypedDict] and\n# > the source callable doesn’t contain **kwargs should be disallowed. This is because,\n# > we cannot be sure that additional keyword arguments are not being passed in when an instance of a subclass\n# > had been assigned to a variable with a base class type and then unpacked in the destination callable invocation\n\ndef func7(*, v1: int, v3: str, v2: str = \"\") -> None:\n ...\n\n\nv7: TDProtocol6 = func7 # E: source does not have kwargs\n","source":"typing_tests","origin":"conformance/tests/callables_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"typed-kwargs","pep":"692","introduced_in":"3.12","form":"modern","file":"typed-kwargs/modern_02.py","code":"\"\"\"\nTests the use of unpacked TypedDicts with read-only items when used to annotate\na **kwargs parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Protocol, TypedDict, Unpack\nfrom typing_extensions import ReadOnly\n\n# > :pep:`692` introduced ``Unpack`` to annotate ``**kwargs`` with a\n# > ``TypedDict``. Marking one or more of the items of a ``TypedDict`` used\n# > in this way as read-only will have no effect on the type signature of\n# > the method. However, it *will* prevent the item from being modified in\n# > the body of the function.\n\n\nclass Args(TypedDict):\n key1: int\n key2: str\n\n\nclass ReadOnlyArgs(TypedDict):\n key1: ReadOnly[int]\n key2: ReadOnly[str]\n\n\nclass Function(Protocol):\n def __call__(self, **kwargs: Unpack[Args]) -> None: ...\n\n\ndef impl(**kwargs: Unpack[ReadOnlyArgs]) -> None:\n kwargs[\"key1\"] = 3 # E\n\n\nfn: Function = impl # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_13.py","code":"\"\"\"\nTests for the use of TypeVarTuple with \"*args\" parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#args-as-a-type-variable-tuple\n\n# > If *args is annotated as a type variable tuple, the types of the individual\n# > arguments become the types in the type variable tuple.\n\nfrom typing import TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef args_to_tuple(*args: *Ts) -> tuple[*Ts]:\n raise NotImplementedError\n\n\nclass Env:\n ...\n\n\ndef exec_le(path: str, *args: *tuple[*Ts, Env], env: Env | None = None) -> tuple[*Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(x: int, y: str):\n assert_type(args_to_tuple(x, y), tuple[int, str])\n\n assert_type(exec_le(\"\", Env()), tuple[()]) # OK\n assert_type(exec_le(y, x, y, Env()), tuple[int, str]) # OK\n exec_le(\"\", 0, \"\") # E\n exec_le(\"\", 0, \"\", env=Env()) # E\n\n\n# > Using an unpacked unbounded tuple is equivalent to the\n# > PEP 484#arbitrary-argument-lists-and-default-argument-values behavior of\n# > *args: int, which accepts zero or more values of type int.\n\n\ndef func1(*args: *tuple[int, ...]) -> None:\n ...\n\n\nfunc1() # OK\nfunc1(1, 2, 3, 4, 5) # OK\nfunc1(1, \"2\", 3) # E\n\n\ndef func2(*args: *tuple[int, *tuple[str, ...], str]) -> None:\n ...\n\n\nfunc2(1, \"\") # OK\nfunc2(1, \"\", \"\", \"\", \"\") # OK\nfunc2(1, 1, \"\") # E\nfunc2(1) # E\nfunc2(\"\") # E\n\n\ndef func3(*args: *tuple[int, str]) -> None:\n ...\n\n\nfunc3(1, \"hello\") # OK\nfunc3(1) # E\n\n\ndef func4(*args: tuple[*Ts]):\n ...\n\n\nfunc4((0,), (1,)) # OK\nfunc4((0,), (1, 2)) # E (length mismatch)\nfunc4((0,), (\"1\",)) # OK\n\n\n# This is a syntax error, so leave it commented out.\n# def func5(**kwargs: *Ts): # E\n# ...\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_14.py","code":"\"\"\"\nTests basic usage of TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#typevartuple\n\nfrom typing import Generic, NewType, TypeVarTuple, assert_type\n\nTs = TypeVarTuple(\"Ts\")\nTs1 = TypeVarTuple(\"Ts1\")\n\n\nclass Array1(Generic[*Ts]):\n ...\n\n\ndef func1(*args: *Ts) -> tuple[*Ts]:\n raise NotImplementedError\n\n\nShape = TypeVarTuple(\"Shape\")\n\n\nclass Array(Generic[*Shape]):\n def __init__(self, shape: tuple[*Shape]):\n self._shape: tuple[*Shape] = shape\n\n def get_shape(self) -> tuple[*Shape]:\n return self._shape\n\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nTime = NewType(\"Time\", int)\nBatch = NewType(\"Batch\", int)\n\nv1: Array[Height, Width] = Array((Height(1), Width(2))) # OK\nv2: Array[Batch, Height, Width] = Array((Batch(1), Height(1), Width(1))) # OK\nv3: Array[Time, Batch, Height, Width] = Array(\n (Time(1), Batch(1), Height(1), Width(1))\n) # OK\n\nv4: Array[Height, Width] = Array(Height(1)) # E\nv5: Array[Batch, Height, Width] = Array((Batch(1), Width(1))) # E\nv6: Array[Time, Batch, Height, Width] = Array( # E[v6]\n (Time(1), Batch(1), Width(1), Height(1)) # E[v6]\n)\n\n\n# > Type Variable Tuples Must Always be Unpacked\n\n\nclass ClassA(Generic[Shape]): # E: not unpacked\n def __init__(self, shape: tuple[Shape]): # E: not unpacked\n self._shape: tuple[*Shape] = shape\n\n def get_shape(self) -> tuple[Shape]: # E: not unpacked\n raise NotImplementedError\n\n def method1(*args: Shape) -> None: # E: not unpacked\n ...\n\n\n# > TypeVarTuple does not support type constraints.\n\nTs2 = TypeVarTuple(\"Ts2\", int, float) # E\nTs3 = TypeVarTuple(\"Ts3\", bound=int) # E: bound is unavailable in Python 3.12\n\n\n# > If the same TypeVarTuple instance is used in multiple places in a signature\n# > or class, a valid type inference might be to bind the TypeVarTuple to a\n# > tuple of a union of types.\n\n\ndef func2(arg1: tuple[*Ts], arg2: tuple[*Ts]) -> tuple[*Ts]:\n raise NotImplementedError\n\n\n# > We do not allow this; type unions may not appear within the tuple.\n# > If a type variable tuple appears in multiple places in a signature,\n# > the types must match exactly (the list of type parameters must be the\n# > same length, and the type parameters themselves must be identical)\n\ndef check_func2(x: int):\n assert_type(func2((x,), (1,)), tuple[int]) # OK\nfunc2((0,), (0.0,)) # OK\nfunc2((0.0,), (0,)) # OK\nfunc2((0,), (1,)) # OK\n\nfunc2((0,), (\"0\",)) # OK\nfunc2((0, 0), (0,)) # E\n\n\ndef multiply(x: Array[*Shape], y: Array[*Shape]) -> Array[*Shape]:\n raise NotImplementedError\n\n\ndef func3(x: Array[Height], y: Array[Width], z: Array[Height, Width]):\n multiply(x, x) # OK\n multiply(x, y) # E\n multiply(x, z) # E\n\n\n# > Only a single type variable tuple may appear in a type parameter list.\n\n\nclass Array3(Generic[*Ts, *Ts1]): # E\n ...\n\n\nclass Array4[*Ts1, *Ts2]: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_15.py","code":"\"\"\"\nTests the use of TypeVarTuple within a Callable.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variable-tuples-with-callable\n\n# > Type variable tuples can also be used in the arguments section of a Callable.\n\n\nfrom typing import Callable, TypeVar, TypeVarTuple, assert_type\n\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Process:\n def __init__(self, target: Callable[[*Ts], None], args: tuple[*Ts]) -> None:\n ...\n\n\ndef func1(arg1: int, arg2: str) -> None:\n ...\n\n\nProcess(target=func1, args=(0, \"\")) # OK\nProcess(target=func1, args=(\"\", 0)) # E\n\n\ndef func2(f: Callable[[int, *Ts, T], tuple[T, *Ts]]) -> tuple[*Ts, T]:\n raise NotImplementedError\n\n\ndef callback1(a: int, b: str, c: int, d: complex) -> tuple[complex, str, int]:\n raise NotImplementedError\n\n\ndef callback2(a: int, d: str) -> tuple[str]:\n raise NotImplementedError\n\n\nassert_type(func2(callback1), tuple[str, int, complex])\nassert_type(func2(callback2), tuple[str])\n\n\ndef func3(*args: *tuple[int, *Ts, T]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(a: int, b: str, c: float, d: complex):\n assert_type(func3(a, b, c, d), tuple[complex, str, float])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_callable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_16.py","code":"\"\"\"\nTests type concatenation using TypeVarTuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-concatenation\n\n# > Type variable tuples don’t have to be alone; normal types can be prefixed and/or suffixed.\n\nfrom typing import Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nShape = TypeVarTuple(\"Shape\")\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef add_batch_axis(x: Array[*Shape]) -> Array[Batch, *Shape]:\n raise NotImplementedError\n\n\ndef del_batch_axis(x: Array[Batch, *Shape]) -> Array[*Shape]:\n raise NotImplementedError\n\n\ndef add_batch_channels(x: Array[*Shape]) -> Array[Batch, *Shape, Channels]:\n raise NotImplementedError\n\n\ndef func1(a: Array[Height, Width]):\n b = add_batch_axis(a) # OK\n assert_type(b, Array[Batch, Height, Width])\n c = del_batch_axis(b) # OK\n assert_type(c, Array[Height, Width])\n d = add_batch_channels(a) # OK\n assert_type(d, Array[Batch, Height, Width, Channels])\n\n\ndef prefix_tuple(x: T, y: tuple[*Ts]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef call_prefix_tuple(x: int, y: bool, z: str):\n result = prefix_tuple(x=x, y=(y, z))\n assert_type(result, tuple[int, bool, str])\n\n\ndef move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n return (*tup[1:], tup[0])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_concat.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_17.py","code":"\"\"\"\nTests the use of TypeVarTuple in function overloads.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#overloads-for-accessing-individual-types\n\nfrom typing import Any, Generic, TypeVar, TypeVarTuple, assert_type, overload\n\n\nShape = TypeVarTuple(\"Shape\")\nAxis1 = TypeVar(\"Axis1\")\nAxis2 = TypeVar(\"Axis2\")\nAxis3 = TypeVar(\"Axis3\")\n\n\nclass Array(Generic[*Shape]):\n @overload\n def transpose(self: \"Array[Axis1, Axis2]\") -> \"Array[Axis2, Axis1]\":\n ...\n\n @overload\n def transpose(self: \"Array[Axis1, Axis2, Axis3]\") -> \"Array[Axis3, Axis2, Axis1]\":\n ...\n\n def transpose(self) -> Any:\n raise NotImplementedError\n\n\ndef func1(a: Array[Axis1, Axis2], b: Array[Axis1, Axis2, Axis3]):\n assert_type(a.transpose(), Array[Axis2, Axis1])\n assert_type(b.transpose(), Array[Axis3, Axis2, Axis1])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_overloads.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_18.py","code":"\"\"\"\nTests the handling of a TypeVarTuple specialization.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#behaviour-when-type-parameters-are-not-specified\n\nfrom typing import Any, Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nTime = NewType(\"Time\", int)\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef takes_any_array1(arr: Array):\n ...\n\n\ndef takes_any_array2(arr: Array[*tuple[Any, ...]]):\n ...\n\n\ndef func1(x: Array[Height, Width]):\n takes_any_array1(x) # OK\n takes_any_array2(x) # OK\n\n\ndef func2(y: Array[Time, Height, Width]):\n takes_any_array1(y) # OK\n takes_any_array2(y) # OK\n\n\n# > Generic aliases can be created using a type variable tuple in a similar\n# > way to regular type variables.\n\nIntTuple = tuple[int, *Ts]\nNamedArray = tuple[str, Array[*Ts]]\n\n\ndef func3(a: IntTuple[float, bool], b: NamedArray[Height]):\n assert_type(a, tuple[int, float, bool])\n assert_type(b, tuple[str, Array[Height]])\n\n\ndef func4(a: IntTuple[()], b: NamedArray[()]):\n assert_type(a, tuple[int])\n assert_type(b, tuple[str, Array[()]])\n\n\nShape = TypeVarTuple(\"Shape\")\nDType = TypeVar(\"DType\")\n\n\nclass Array2(Generic[DType, *Shape]):\n ...\n\n\nFloatArray = Array2[float, *Shape]\nArray1D = Array2[DType, Any]\n\n\ndef func5_0(a: Array1D, b: Array1D[int]):\n assert_type(a, Array2[Any, Any])\n assert_type(b, Array2[int, Any])\n\n\ndef takes_float_array_of_any_shape(x: FloatArray):\n ...\n\n\ndef func5_1(x: FloatArray[Height, Width]):\n takes_float_array_of_any_shape(x) # OK\n\n\ndef takes_float_array_with_specific_shape(y: FloatArray[Height, Width]):\n ...\n\n\ndef func5_2(x: FloatArray):\n takes_float_array_with_specific_shape(x) # OK\n\n\nT = TypeVar(\"T\")\nVariadicTuple = tuple[T, *Ts]\n\n\ndef func6(a: VariadicTuple[str, int], b: VariadicTuple[float], c: VariadicTuple):\n assert_type(a, tuple[str, int])\n assert_type(b, tuple[float])\n assert_type(c, tuple[Any, *tuple[Any, ...]])\n\n\nTs1 = TypeVarTuple(\"Ts1\")\nTs2 = TypeVarTuple(\"Ts2\")\n\nIntTupleVar = tuple[int, *Ts1] # OK\nIntFloatTupleVar = IntTupleVar[float, *Ts2] # OK\nIntFloatsTupleVar = IntTupleVar[*tuple[float, ...]] # OK\n\n\nIntTupleGeneric = tuple[int, T]\n\nIntTupleGeneric[str] # OK\nIntTupleGeneric[*Ts] # E\nIntTupleGeneric[*tuple[float, ...]] # E\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nTA1 = tuple[*Ts, T1, T2] # OK\nTA2 = tuple[T1, T2, *Ts] # OK\nTA3 = tuple[T1, *Ts, T2, T3] # OK\nTA4 = tuple[T1, T2, *tuple[int, ...]] # OK\nTA5 = tuple[T1, *Ts, T2, *Ts] # E\nTA6 = tuple[T1, *Ts, T2, *tuple[int, ...]] # E\n\n\nTA7 = tuple[*Ts, T1, T2]\n\nv1: TA7[int] # E: requires at least two type arguments\n\n\ndef func7(a: TA7[*Ts, T1, T2]) -> tuple[tuple[*Ts], T1, T2]:\n raise NotImplementedError\n\n\ndef func8(a: TA7[str, bool], b: TA7[str, bool, float], c: TA7[str, bool, float, int]):\n assert_type(func7(a), tuple[tuple[()], str, bool])\n assert_type(func7(b), tuple[tuple[str], bool, float])\n assert_type(func7(c), tuple[tuple[str, bool], float, int])\n\n\nTA8 = tuple[T1, *Ts, T2, T3]\n\n\ndef func9(a: TA8[T1, *Ts, T2, T3]) -> tuple[tuple[*Ts], T1, T2, T3]:\n raise NotImplementedError\n\n\ndef func10(a: TA8[str, bool, float], b: TA8[str, bool, float, int]):\n assert_type(func9(a), tuple[tuple[()], str, bool, float])\n assert_type(func9(b), tuple[tuple[bool], str, float, int])\n\n\nTA9 = tuple[*Ts, T1]\nTA10 = TA9[*tuple[int, ...]] # OK\n\n\ndef func11(a: TA10, b: TA9[*tuple[int, ...], str], c: TA9[*tuple[int, ...], str]):\n assert_type(a, tuple[*tuple[int, ...], int])\n assert_type(b, tuple[*tuple[int, ...], str])\n assert_type(c, tuple[*tuple[int, ...], str])\n\n\nTA11 = tuple[T, *Ts1]\nTA12 = TA11[*Ts2] # E\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_19.py","code":"\"\"\"\nTests unpack operations for TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#unpacking-tuple-types\n\nfrom typing import Any, Generic, NewType, TypeVarTuple\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nTs = TypeVarTuple(\"Ts\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef process_batch_channels(x: Array[Batch, *tuple[Any, ...], Channels]) -> None:\n ...\n\n\ndef func3(\n x: Array[Batch, Height, Width, Channels], y: Array[Batch, Channels], z: Array[Batch]\n):\n process_batch_channels(x) # OK\n process_batch_channels(y) # OK\n process_batch_channels(z) # E\n\n\nShape = TypeVarTuple(\"Shape\")\n\n\ndef expect_variadic_array(x: Array[Batch, *Shape]) -> None:\n ...\n\n\ndef expect_precise_array(x: Array[Batch, Height, Width, Channels]) -> None:\n ...\n\n\ndef func4(y: Array[*tuple[Any, ...]]):\n expect_variadic_array(y) # OK\n expect_precise_array(y) # OK\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_unpack.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_20.py","code":"\"\"\"\nTests variance of TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance-inference\n\n\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple\n\nclass InvariantTypeVarTuple[*InOutTs]:\n a: tuple[*InOutTs]\n\nin_out_obj: InvariantTypeVarTuple[object] = InvariantTypeVarTuple[int]() # E\nin_out_int: InvariantTypeVarTuple[int] = InvariantTypeVarTuple[object]() # E\nin_out_int = InvariantTypeVarTuple[int]()\nin_out_variadic_int: InvariantTypeVarTuple[*tuple[int, ...]] = InvariantTypeVarTuple[*tuple[object, ...]]() # E\nin_out_variadic_object: InvariantTypeVarTuple[*tuple[object, ...]] = InvariantTypeVarTuple[*tuple[int, ...]]() # E\nin_out_empty: InvariantTypeVarTuple[()] = InvariantTypeVarTuple[()]() # OK\nin_out_fixed_from_variadic: InvariantTypeVarTuple[int] = InvariantTypeVarTuple[*tuple[int, ...]]() # E\nin_out_variadic_from_fixed: InvariantTypeVarTuple[*tuple[int, ...]] = InvariantTypeVarTuple[int]() # E\n\n\nclass ContravariantTypeVarTuple[*InTs]:\n def f(self, t: tuple[*InTs]):\n raise NotImplementedError\n\nin_obj: ContravariantTypeVarTuple[object, object] = ContravariantTypeVarTuple[object, int]() # E\nin_int: ContravariantTypeVarTuple[int] = ContravariantTypeVarTuple[object]() # OK\nin_variadic_int: ContravariantTypeVarTuple[*tuple[int, ...]] = ContravariantTypeVarTuple[*tuple[object, ...]]() # OK\nin_variadic_object: ContravariantTypeVarTuple[*tuple[object, ...]] = ContravariantTypeVarTuple[*tuple[int, ...]]() # E\nin_empty: ContravariantTypeVarTuple[()] = ContravariantTypeVarTuple[()]() # OK\nin_fixed_from_variadic: ContravariantTypeVarTuple[int] = ContravariantTypeVarTuple[*tuple[int, ...]]() # OK\nin_variadic_from_fixed: ContravariantTypeVarTuple[*tuple[int, ...]] = ContravariantTypeVarTuple[int]() # E\n\n\nclass CovariantTypeVarTuple[*OutTs]:\n def f(self) -> tuple[*OutTs]:\n raise NotImplementedError\n\n\nout_int: CovariantTypeVarTuple[int] = CovariantTypeVarTuple[object]() # E\nout_obj: CovariantTypeVarTuple[object] = CovariantTypeVarTuple[int]() # OK\nout_multiple1: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[bool, bool]() # OK\nout_multiple2: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[bool, object]() # E\nout_multiple3: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[object, bool]() # E\nout_multiple4: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[object, object]() # E\nout_variadic_int: CovariantTypeVarTuple[*tuple[int, ...]] = CovariantTypeVarTuple[*tuple[object, ...]]() # E\nout_variadic_object: CovariantTypeVarTuple[*tuple[object, ...]] = CovariantTypeVarTuple[*tuple[int, ...]]() # OK\nout_empty: CovariantTypeVarTuple[()] = CovariantTypeVarTuple[()]() # OK\nout_fixed_from_variadic: CovariantTypeVarTuple[int] = CovariantTypeVarTuple[*tuple[int, ...]]() # E\nout_variadic_from_fixed: CovariantTypeVarTuple[*tuple[int, ...]] = CovariantTypeVarTuple[int]() # OK\n\nTs = TypeVarTuple(\"Ts\") # OK\nInferTs = TypeVarTuple(\"InferTs\", infer_variance=True) # OK\nInvTs1 = TypeVarTuple(\"InvTs1\", covariant=True, contravariant=True) # E\nInvTs2 = TypeVarTuple(\"InvTs2\", covariant=True, infer_variance=True) # E\nInvTs3 = TypeVarTuple(\"InvTs3\", contravariant=True, infer_variance=True) # E\n\nclass InvariantTypeVarTupleOld(Generic[*Ts]):\n def in_f(self, *args: *Ts) -> None: # OK\n raise NotImplementedError\n\n def out_f(self) -> tuple[*Ts]: # OK\n raise NotImplementedError\n\n\nobj_old: InvariantTypeVarTupleOld[object] = InvariantTypeVarTupleOld[int]() # E\nint_old: InvariantTypeVarTupleOld[int] = InvariantTypeVarTupleOld[object]() # E\nint_old = InvariantTypeVarTupleOld[int]()\n\n\nInTs = TypeVarTuple(\"InTs\", contravariant=True)\n\nclass ContravariantTypeVarTupleOld(Generic[*InTs]):\n def in_f(self, *args: *InTs) -> None: # OK\n raise NotImplementedError\n\n def out_f(self) -> tuple[*InTs]: # E\n raise NotImplementedError\n\n\nin_obj_old: ContravariantTypeVarTupleOld[object] = ContravariantTypeVarTupleOld[int]() # E\nin_int_old: ContravariantTypeVarTupleOld[int] = ContravariantTypeVarTupleOld[object]() # OK\n\n\nOutTs = TypeVarTuple(\"OutTs\", covariant=True)\n\nclass CovariantTypeVarTupleOld(Generic[*OutTs]):\n def in_f(self, *args: *OutTs) -> None: # E\n raise NotImplementedError\n\n def out_f(self) -> tuple[*OutTs]: # OK\n raise NotImplementedError\n\n\nout_int_old: CovariantTypeVarTupleOld[int] = CovariantTypeVarTupleOld[object]() # E\nout_obj_old: CovariantTypeVarTupleOld[object] = CovariantTypeVarTupleOld[int]() # OK\n\n\n# `infer_variance=True` on a traditional `TypeVarTuple`\nclass InferredContravariantTypeVarTupleOld(Generic[*InferTs]):\n def in_f(self, *args: *InferTs) -> None: # OK\n raise NotImplementedError\n\n\ninfer_in_obj_old: InferredContravariantTypeVarTupleOld[object] = InferredContravariantTypeVarTupleOld[int]() # E\ninfer_in_int_old: InferredContravariantTypeVarTupleOld[int] = InferredContravariantTypeVarTupleOld[object]() # OK\n\n\nclass InferredCovariantTypeVarTupleOld(Generic[*InferTs]):\n def out_f(self) -> tuple[*InferTs]: # OK\n raise NotImplementedError\n\n\ninfer_out_int_old: InferredCovariantTypeVarTupleOld[int] = InferredCovariantTypeVarTupleOld[object]() # E\ninfer_out_obj_old: InferredCovariantTypeVarTupleOld[object] = InferredCovariantTypeVarTupleOld[int]() # OK\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_21.py","code":"\"\"\"\nTests the handling of unpacked tuples embedded within other tuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#unpacked-tuple-form\n\n# > An unpacked form of ``tuple`` (using an unpack operator ``*``)\n# > can be used within a tuple type argument list\n\n# > Unpacking a concrete tuple type is analogous to unpacking a tuple of values at runtime.\n\n\nfrom typing import TypeVarTuple, Unpack, assert_type\n\n\ndef func1(x: tuple[int, *tuple[bool, bool], str]):\n assert_type(x, tuple[int, bool, bool, str])\n assert_type(x, tuple[*tuple[int, bool], bool, str])\n assert_type(x, tuple[int, bool, *tuple[bool, str]])\n\n\n# > Unpacking an unbounded tuple preserves the unbounded tuple as it is.\n\n\ndef func2(x: tuple[int, *tuple[bool, ...], str]):\n assert_type(x, tuple[int, *tuple[bool, ...], str])\n\n\n# > For example, tuple[int, *tuple[str]] is equivalent to tuple[int, str].\n\nu1: tuple[*tuple[int], *tuple[int]] = (int(1), int(1)) # OK\nassert_type(u1, tuple[int, int])\nu2: tuple[*tuple[int, ...], *tuple[int]] # OK\n\n\n# > Only one unbounded tuple can be used within another tuple:\n\nt1: tuple[*tuple[str], *tuple[str]] # OK\nt2: tuple[*tuple[str, *tuple[str, ...]]] # OK\nt3: tuple[*tuple[str, ...], *tuple[int, ...]] # E\nt4: tuple[*tuple[str, *tuple[str, ...]], *tuple[int, ...]] # E\n\n\n# > An unpacked TypeVarTuple counts as an unbounded tuple in the context of this rule\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef func3(t: tuple[*Ts]):\n t5: tuple[*tuple[str], *Ts] # OK\n t6: tuple[*tuple[str, ...], *Ts] # E\n\n\n# > The ``*`` syntax requires Python 3.11 or newer. For older versions of Python,\n# > the ``typing.Unpack`` special form can be used:\n\nt11: tuple[Unpack[tuple[str]], Unpack[tuple[str]]] # OK\nt12: tuple[Unpack[tuple[str, Unpack[tuple[str, ...]]]]] # OK\nt13: tuple[Unpack[tuple[str, ...]], Unpack[tuple[int, ...]]] # E\nt14: tuple[ # E[t14]\n Unpack[tuple[str, Unpack[tuple[str, ...]]]], Unpack[tuple[int, ...]] # E[t14]\n]\n","source":"typing_tests","origin":"conformance/tests/tuples_unpacked.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n an = g.__anext__()\n try:\n while True:\n try:\n an.__next__()\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n break\n else:\n res.append('EMPTY StopIteration')\n break\n except StopAsyncIteration:\n raise\n except Exception as ex:\n res.append(str(type(ex)))\n break\n except StopAsyncIteration:\n res.append('STOP')\n break\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_exception_11(self):\n def sync_gen():\n yield 10\n yield 20\n\n def sync_gen_wrapper():\n yield 1\n sg = sync_gen()\n sg.send(None)\n try:\n sg.throw(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n async def async_gen():\n yield 10\n yield 20\n\n async def async_gen_wrapper():\n yield 1\n asg = async_gen()\n await asg.asend(None)\n try:\n await asg.athrow(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())\n\n def test_async_gen_exception_12(self):\n async def gen():\n with self.assertWarnsRegex(RuntimeWarning,\n f\"coroutine method 'asend' of '{gen.__qualname__}' \"\n f\"was never awaited\"):\n await anext(me)\n yield 123\n\n me = gen()\n ai = me.__aiter__()\n an = ai.__anext__()\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n an.__next__()\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"):\n an.send(None)\n\n def test_async_gen_asend_throw_concurrent_with_send(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n return\n yield\n\n\n agen = agenfn()\n gen = agen.asend(None)\n gen.send(None)\n gen2 = agen.asend(None)\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_athrow_throw_concurrent_with_send(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n return\n yield\n\n\n agen = agenfn()\n gen = agen.asend(None)\n gen.send(None)\n gen2 = agen.athrow(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r'athrow\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_asend_throw_concurrent_with_throw(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n try:\n yield\n except MyExc:\n pass\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n\n\n agen = agenfn()\n with self.assertRaises(StopIteration):\n agen.asend(None).send(None)\n\n gen = agen.athrow(MyExc)\n gen.throw(MyExc)\n gen2 = agen.asend(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_athrow_throw_concurrent_with_throw(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n try:\n yield\n except MyExc:\n pass\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n\n agen = agenfn()\n with self.assertRaises(StopIteration):\n agen.asend(None).send(None)\n\n gen = agen.athrow(MyExc)\n gen.throw(MyExc)\n gen2 = agen.athrow(None)\n\n with self.assertRaisesRegex(RuntimeError,\n r'athrow\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_3_arg_deprecation_warning(self):\n async def gen():\n yield 123\n\n with self.assertWarns(DeprecationWarning):\n x = gen().athrow(GeneratorExit, GeneratorExit(), None)\n with self.assertRaises(GeneratorExit):\n x.send(None)\n del x\n gc_collect()\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n aclose = g.aclose()\n self.assertTrue(inspect.isawaitable(aclose))\n aclose.close()\n\n def test_async_gen_asend_close_runtime_error(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n async def agenfn():\n try:\n await _async_yield(None)\n except GeneratorExit:\n await _async_yield(None)\n return\n yield\n\n agen = agenfn()\n gen = agen.asend(None)\n gen.send(None)\n with self.assertRaisesRegex(RuntimeError, \"coroutine ignored GeneratorExit\"):\n gen.close()\n\n def test_async_gen_athrow_close_runtime_error(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n try:\n yield\n except MyExc:\n try:\n await _async_yield(None)\n except GeneratorExit:\n await _async_yield(None)\n\n agen = agenfn()\n with self.assertRaises(StopIteration):\n agen.asend(None).send(None)\n gen = agen.athrow(MyExc)\n gen.send(None)\n with self.assertRaisesRegex(RuntimeError, \"coroutine ignored GeneratorExit\"):\n gen.close()\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n asyncio.set_event_loop_policy(None)\n\n def check_async_iterator_anext(self, ait_class):\n with self.subTest(anext=\"pure-Python\"):\n self._check_async_iterator_anext(ait_class, py_anext)\n with self.subTest(anext=\"builtin\"):\n self._check_async_iterator_anext(ait_class, anext)\n\n def _check_async_iterator_anext(self, ait_class, anext):\n g = ait_class()\n async def consume():\n results = []\n results.append(await anext(g))\n results.append(await anext(g))\n results.append(await anext(g, 'buckle my shoe'))\n return results\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2, 'buckle my shoe'])\n with self.assertRaises(StopAsyncIteration):\n self.loop.run_until_complete(consume())\n\n async def test_2():\n g1 = ait_class()\n self.assertEqual(await anext(g1), 1)\n self.assertEqual(await anext(g1), 2)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n\n g2 = ait_class()\n self.assertEqual(await anext(g2, \"default\"), 1)\n self.assertEqual(await anext(g2, \"default\"), 2)\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n\n return \"completed\"\n\n result = self.loop.run_until_complete(test_2())\n self.assertEqual(result, \"completed\")\n\n def test_send():\n p = ait_class()\n obj = anext(p, \"completed\")\n with self.assertRaises(StopIteration):\n with contextlib.closing(obj.__await__()) as g:\n g.send(None)\n\n test_send()\n\n async def test_throw():\n p = ait_class()\n obj = anext(p, \"completed\")\n self.assertRaises(SyntaxError, obj.throw, SyntaxError)\n return \"completed\"\n\n result = self.loop.run_until_complete(test_throw())\n self.assertEqual(result, \"completed\")\n\n def test_async_generator_anext(self):\n async def agen():\n yield 1\n yield 2\n self.check_async_iterator_anext(agen)\n\n def test_python_async_iterator_anext(self):\n class MyAsyncIter:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n async def __anext__(self):\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIter)\n\n def test_python_async_iterator_types_coroutine_anext(self):\n import types\n class MyAsyncIterWithTypesCoro:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n @types.coroutine\n def __anext__(self):\n if False:\n yield \"this is a generator-based coroutine\"\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIterWithTypesCoro)\n\n def test_async_gen_aiter(self):\n async def gen():\n yield 1\n yield 2\n g = gen()\n async def consume():\n return [i async for i in aiter(g)]\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_aiter_class(self):\n results = []\n class Gen:\n async def __aiter__(self):\n yield 1\n yield 2\n g = Gen()\n async def consume():\n ait = aiter(g)\n while True:\n try:\n results.append(await anext(ait))\n except StopAsyncIteration:\n break\n self.loop.run_until_complete(consume())\n self.assertEqual(results, [1, 2])\n\n def test_aiter_idempotent(self):\n async def gen():\n yield 1\n applied_once = aiter(gen())\n applied_twice = aiter(applied_once)\n self.assertIs(applied_once, applied_twice)\n\n def test_anext_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await anext()\n async def call_with_too_many_args():\n await anext(gen(), 1, 3)\n async def call_with_wrong_type_args():\n await anext(1, gen())\n async def call_with_kwarg():\n await anext(aiterator=gen())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_kwarg())\n\n def test_anext_bad_await(self):\n async def bad_awaitable():\n class BadAwaitable:\n def __await__(self):\n return 42\n class MyAsyncIter:\n def __aiter__(self):\n return self\n def __anext__(self):\n return BadAwaitable()\n regex = r\"__await__.*iterator\"\n awaitable = anext(MyAsyncIter(), \"default\")\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n awaitable = anext(MyAsyncIter())\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(bad_awaitable())\n self.assertEqual(result, \"completed\")\n\n async def check_anext_returning_iterator(self, aiter_class):\n awaitable = anext(aiter_class(), \"default\")\n with self.assertRaises(TypeError):\n await awaitable\n awaitable = anext(aiter_class())\n with self.assertRaises(TypeError):\n await awaitable\n return \"completed\"\n\n def test_anext_return_iterator(self):\n class WithIterAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return iter(\"abc\")\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithIterAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_return_generator(self):\n class WithGenAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n yield\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithGenAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_await_raises(self):\n class RaisingAwaitable:\n def __await__(self):\n raise ZeroDivisionError()\n yield\n class WithRaisingAwaitableAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return RaisingAwaitable()\n async def do_test():\n awaitable = anext(WithRaisingAwaitableAnext())\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n awaitable = anext(WithRaisingAwaitableAnext(), \"default\")\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(do_test())\n self.assertEqual(result, \"completed\")\n\n def test_anext_iter(self):\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyError(Exception):\n pass\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n def test1(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError()), 2)\n try:\n g.send(None)\n except StopIteration as e:\n err = e\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(err.value, \"default\")\n\n def test2(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError()), 2)\n with self.assertRaises(MyError):\n g.throw(MyError())\n\n def test3(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n g.close()\n with self.assertRaisesRegex(RuntimeError, 'cannot reuse'):\n self.assertEqual(g.send(None), 1)\n\n def test4(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n self.assertEqual(g.throw(MyError()), 20)\n with self.assertRaisesRegex(MyError, 'val'):\n g.throw(MyError('val'))\n\n def test5(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n return\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n with self.assertRaisesRegex(StopIteration, 'default'):\n g.throw(MyError())\n\n def test6(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n await _async_yield(1)\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n with self.assertRaises(MyError):\n g.throw(MyError())\n\n def run_test(test):\n with self.subTest('pure-Python anext()'):\n test(py_anext)\n with self.subTest('builtin anext()'):\n test(anext)\n\n run_test(test1)\n run_test(test2)\n run_test(test3)\n run_test(test4)\n run_test(test5)\n run_test(test6)\n\n def test_aiter_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await aiter()\n async def call_with_too_many_args():\n await aiter(gen(), 1)\n async def call_with_wrong_type_arg():\n await aiter(1)\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_arg())\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n await asyncio.sleep(0.01)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n gc_collect() # For PyPy or other GCs.\n\n # Starts running the aclose task\n await asyncio.sleep(0)\n # For asyncio.sleep(0) in finally block\n await asyncio.sleep(0)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_aclose_12(self):\n DONE = 0\n\n async def target():\n await asyncio.sleep(0.01)\n 1 / 0\n\n async def foo():\n nonlocal DONE\n task = asyncio.create_task(target())\n try:\n yield 1\n finally:\n try:\n await task\n except ZeroDivisionError:\n DONE = 1\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout)\n yield 1\n finally:\n await asyncio.sleep(0)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1))\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t1)\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t2)\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(finalized, 2)\n\n def test_async_gen_asyncio_shutdown_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n self.assertEqual(messages, [])\n\n def test_async_gen_asyncio_shutdown_exception_01(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n message, = messages\n self.assertEqual(message['asyncgen'], it)\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('an error occurred during closing of asynchronous generator',\n message['message'])\n\n def test_async_gen_asyncio_shutdown_exception_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n gc_collect()\n\n asyncio.run(main())\n\n message, = messages\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('unhandled exception during asyncio.run() shutdown',\n message['message'])\n del message, messages\n gc_collect()\n\n def test_async_gen_expression_01(self):\n async def arange(n):\n for i in range(n):\n await asyncio.sleep(0.01)\n yield i\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 async for i in arange(n))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(10)])\n\n def test_async_gen_expression_02(self):\n async def wrap(n):\n await asyncio.sleep(0.01)\n return n\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 for i in range(n) if await wrap(i))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(1, 10)])\n\n def test_asyncgen_nonstarted_hooks_are_cancellable(self):\n # See https://bugs.python.org/issue38013\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n\n asyncio.run(main())\n\n self.assertEqual([], messages)\n gc_collect()\n\n def test_async_gen_await_same_anext_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.__anext__()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"\n ):\n await nxt\n\n await it.aclose() # prevent unfinished iterator warning\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_await_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.aclose()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n await nxt\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_throw_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n nxt = it.aclose()\n with self.assertRaises(StopIteration):\n nxt.throw(GeneratorExit)\n\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n nxt.throw(GeneratorExit)\n\n def test_async_gen_throw_custom_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n\n class MyException(Exception):\n pass\n\n nxt = it.aclose()\n with self.assertRaises(MyException):\n nxt.throw(MyException)\n\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n nxt.throw(MyException)\n\n def test_async_gen_throw_custom_same_athrow_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n\n class MyException(Exception):\n pass\n\n nxt = it.athrow(MyException)\n with self.assertRaises(MyException):\n nxt.throw(MyException)\n\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n nxt.throw(MyException)\n\n def test_async_gen_aclose_twice_with_different_coros(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n await it.aclose()\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_after_exhaustion(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n async for _ in it:\n pass\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_compatible_with_get_stack(self):\n async def async_generator():\n yield object()\n\n async def run():\n ag = async_generator()\n asyncio.create_task(ag.aclose())\n tasks = asyncio.all_tasks()\n for task in tasks:\n # No AttributeError raised\n task.get_stack()\n\n self.loop.run_until_complete(run())\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"breakpoint","pep":"553","introduced_in":"3.7","form":"modern","file":"breakpoint/modern_01.py","code":"import ast\nimport asyncio\nimport builtins\nimport collections\nimport contextlib\nimport decimal\nimport fractions\nimport gc\nimport io\nimport locale\nimport math\nimport os\nimport pickle\nimport platform\nimport random\nimport re\nimport sys\nimport traceback\nimport types\nimport typing\nimport unittest\nimport warnings\nfrom contextlib import ExitStack\nfrom functools import partial\nfrom inspect import CO_COROUTINE\nfrom itertools import product\nfrom textwrap import dedent\nfrom types import AsyncGeneratorType, FunctionType, CellType\nfrom operator import neg\nfrom test import support\nfrom test.support import (cpython_only, swap_attr, maybe_get_event_loop_policy)\nfrom test.support.import_helper import import_module\nfrom test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink)\nfrom test.support.script_helper import assert_python_ok\nfrom test.support.warnings_helper import check_warnings\nfrom test.support import requires_IEEE_754\nfrom unittest.mock import MagicMock, patch\n\n\nclass TestBreakpoint(unittest.TestCase):\n def setUp(self):\n # These tests require a clean slate environment. For example, if the\n # test suite is run with $PYTHONBREAKPOINT set to something else, it\n # will mess up these tests. Similarly for sys.breakpointhook.\n # Cleaning the slate here means you can't use breakpoint() to debug\n # these tests, but I think that's okay. Just use pdb.set_trace() if\n # you must.\n self.resources = ExitStack()\n self.addCleanup(self.resources.close)\n self.env = self.resources.enter_context(EnvironmentVarGuard())\n del self.env['PYTHONBREAKPOINT']\n self.resources.enter_context(\n swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))\n\n def test_breakpoint(self):\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once()\n\n def test_breakpoint_with_breakpointhook_set(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_breakpointhook_reset(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n # Reset the hook and it will not be called again.\n sys.breakpointhook = sys.__breakpointhook__\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_args_and_keywords(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint(1, 2, 3, four=4, five=5)\n my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)\n\n def test_breakpoint_with_passthru_error(self):\n def my_breakpointhook():\n pass\n sys.breakpointhook = my_breakpointhook\n self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_builtin(self):\n self.env['PYTHONBREAKPOINT'] = 'int'\n with patch('builtins.int') as mock:\n breakpoint('7')\n mock.assert_called_once_with('7')\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_other(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_noop_0(self):\n self.env['PYTHONBREAKPOINT'] = '0'\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_not_called()\n\n def test_envar_good_path_empty_string(self):\n # PYTHONBREAKPOINT='' is the same as it not being set.\n self.env['PYTHONBREAKPOINT'] = ''\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_unimportable(self):\n for envar in (\n '.', '..', '.foo', 'foo.', '.int', 'int.',\n '.foo.bar', '..foo.bar', '/./',\n 'nosuchbuiltin',\n 'nosuchmodule.nosuchcallable',\n ):\n with self.subTest(envar=envar):\n self.env['PYTHONBREAKPOINT'] = envar\n mock = self.resources.enter_context(patch('pdb.set_trace'))\n w = self.resources.enter_context(check_warnings(quiet=True))\n breakpoint()\n self.assertEqual(\n str(w.message),\n f'Ignoring unimportable $PYTHONBREAKPOINT: \"{envar}\"')\n self.assertEqual(w.category, RuntimeWarning)\n mock.assert_not_called()\n\n def test_envar_ignored_when_hook_is_set(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n sys.breakpointhook = int\n breakpoint()\n mock.assert_not_called()\n\n def test_runtime_error_when_hook_is_lost(self):\n del sys.breakpointhook\n with self.assertRaises(RuntimeError):\n breakpoint()\n","source":"cpython_tests","origin":"Lib/test/test_builtin.py::TestBreakpoint","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(ZeroDivisionError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n notes = cm.exception.__notes__\n self.assertRegex(str(notes), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(notes), r'\\battr\\b')\n self.assertRegex(str(notes), r'\\bDescriptor\\b')\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(TypeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n notes = cm.exception.__notes__\n self.assertRegex(str(notes), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(notes), r'\\battr\\b')\n self.assertRegex(str(notes), r'\\bDescriptor\\b')\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass2(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass3(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass3.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass2(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass2.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_03.py","code":"import concurrent.futures\nimport contextvars\nimport functools\nimport gc\nimport random\nimport time\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import threading_helper\n\n\nclass ContextTest(unittest.TestCase):\n def test_context_var_new_1(self):\n with self.assertRaisesRegex(TypeError, 'takes exactly 1'):\n contextvars.ContextVar()\n\n with self.assertRaisesRegex(TypeError, 'must be a str'):\n contextvars.ContextVar(1)\n\n c = contextvars.ContextVar('aaa')\n self.assertEqual(c.name, 'aaa')\n\n with self.assertRaises(AttributeError):\n c.name = 'bbb'\n\n self.assertNotEqual(hash(c), hash('aaa'))\n\n @isolated_context\n def test_context_var_repr_1(self):\n c = contextvars.ContextVar('a')\n self.assertIn('a', repr(c))\n\n c = contextvars.ContextVar('a', default=123)\n self.assertIn('123', repr(c))\n\n lst = []\n c = contextvars.ContextVar('a', default=lst)\n lst.append(c)\n self.assertIn('...', repr(c))\n self.assertIn('...', repr(lst))\n\n t = c.set(1)\n self.assertIn(repr(c), repr(t))\n self.assertNotIn(' used ', repr(t))\n c.reset(t)\n self.assertIn(' used ', repr(t))\n\n def test_context_subclassing_1(self):\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContextVar(contextvars.ContextVar):\n # Potentially we might want ContextVars to be subclassable.\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContext(contextvars.Context):\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyToken(contextvars.Token):\n pass\n\n def test_context_new_1(self):\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1, a=1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(a=1)\n contextvars.Context(**{})\n\n def test_context_typerrors_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx[1]\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n 1 in ctx\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx.get(1)\n\n def test_context_get_context_1(self):\n ctx = contextvars.copy_context()\n self.assertIsInstance(ctx, contextvars.Context)\n\n def test_context_run_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required'):\n ctx.run()\n\n def test_context_run_2(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n kwargs['spam'] = 'foo'\n args += ('bar',)\n return args, kwargs\n\n for f in (func, functools.partial(func)):\n # partial doesn't support FASTCALL\n\n self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))\n self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, a=2),\n (('bar',), {'a': 2, 'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, 11, a=2),\n ((11, 'bar'), {'a': 2, 'spam': 'foo'}))\n\n a = {}\n self.assertEqual(\n ctx.run(f, 11, **a),\n ((11, 'bar'), {'spam': 'foo'}))\n self.assertEqual(a, {})\n\n def test_context_run_3(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2, a=123)\n\n @isolated_context\n def test_context_run_4(self):\n ctx1 = contextvars.Context()\n ctx2 = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func2():\n self.assertIsNone(var.get(None))\n\n def func1():\n self.assertIsNone(var.get(None))\n var.set('spam')\n ctx2.run(func2)\n self.assertEqual(var.get(None), 'spam')\n\n cur = contextvars.copy_context()\n self.assertEqual(len(cur), 1)\n self.assertEqual(cur[var], 'spam')\n return cur\n\n returned_ctx = ctx1.run(func1)\n self.assertEqual(ctx1, returned_ctx)\n self.assertEqual(returned_ctx[var], 'spam')\n self.assertIn(var, returned_ctx)\n\n def test_context_run_5(self):\n ctx = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func():\n self.assertIsNone(var.get(None))\n var.set('spam')\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n\n self.assertIsNone(var.get(None))\n\n def test_context_run_6(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('a', default=0)\n\n def fun():\n self.assertEqual(c.get(), 0)\n self.assertIsNone(ctx.get(c))\n\n c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(ctx.get(c), 42)\n\n ctx.run(fun)\n\n def test_context_run_7(self):\n ctx = contextvars.Context()\n\n def fun():\n with self.assertRaisesRegex(RuntimeError, 'is already entered'):\n ctx.run(fun)\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_1(self):\n c = contextvars.ContextVar('c')\n with self.assertRaises(LookupError):\n c.get()\n\n self.assertIsNone(c.get(None))\n\n t0 = c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n self.assertIs(t0.old_value, t0.MISSING)\n self.assertIs(t0.old_value, contextvars.Token.MISSING)\n self.assertIs(t0.var, c)\n\n t = c.set('spam')\n self.assertEqual(c.get(), 'spam')\n self.assertEqual(c.get(None), 'spam')\n self.assertEqual(t.old_value, 42)\n c.reset(t)\n\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n\n c.set('spam2')\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t)\n self.assertEqual(c.get(), 'spam2')\n\n ctx1 = contextvars.copy_context()\n self.assertIn(c, ctx1)\n\n c.reset(t0)\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t0)\n self.assertIsNone(c.get(None))\n\n self.assertIn(c, ctx1)\n self.assertEqual(ctx1[c], 'spam2')\n self.assertEqual(ctx1.get(c, 'aa'), 'spam2')\n self.assertEqual(len(ctx1), 1)\n self.assertEqual(list(ctx1.items()), [(c, 'spam2')])\n self.assertEqual(list(ctx1.values()), ['spam2'])\n self.assertEqual(list(ctx1.keys()), [c])\n self.assertEqual(list(ctx1), [c])\n\n ctx2 = contextvars.copy_context()\n self.assertNotIn(c, ctx2)\n with self.assertRaises(KeyError):\n ctx2[c]\n self.assertEqual(ctx2.get(c, 'aa'), 'aa')\n self.assertEqual(len(ctx2), 0)\n self.assertEqual(list(ctx2), [])\n\n @isolated_context\n def test_context_getset_2(self):\n v1 = contextvars.ContextVar('v1')\n v2 = contextvars.ContextVar('v2')\n\n t1 = v1.set(42)\n with self.assertRaisesRegex(ValueError, 'by a different'):\n v2.reset(t1)\n\n @isolated_context\n def test_context_getset_3(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n def fun():\n self.assertEqual(c.get(), 42)\n with self.assertRaises(KeyError):\n ctx[c]\n self.assertIsNone(ctx.get(c))\n self.assertEqual(ctx.get(c, 'spam'), 'spam')\n self.assertNotIn(c, ctx)\n self.assertEqual(list(ctx.keys()), [])\n\n t = c.set(1)\n self.assertEqual(list(ctx.keys()), [c])\n self.assertEqual(ctx[c], 1)\n\n c.reset(t)\n self.assertEqual(list(ctx.keys()), [])\n with self.assertRaises(KeyError):\n ctx[c]\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_4(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n tok = ctx.run(c.set, 1)\n\n with self.assertRaisesRegex(ValueError, 'different Context'):\n c.reset(tok)\n\n @isolated_context\n def test_context_getset_5(self):\n c = contextvars.ContextVar('c', default=42)\n c.set([])\n\n def fun():\n c.set([])\n c.get().append(42)\n self.assertEqual(c.get(), [42])\n\n contextvars.copy_context().run(fun)\n self.assertEqual(c.get(), [])\n\n def test_context_copy_1(self):\n ctx1 = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def ctx1_fun():\n c.set(10)\n\n ctx2 = ctx1.copy()\n self.assertEqual(ctx2[c], 10)\n\n c.set(20)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 10)\n\n ctx2.run(ctx2_fun)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 30)\n\n def ctx2_fun():\n self.assertEqual(c.get(), 10)\n c.set(30)\n self.assertEqual(c.get(), 30)\n\n ctx1.run(ctx1_fun)\n\n @isolated_context\n @threading_helper.requires_working_threading()\n def test_context_threads_1(self):\n cvar = contextvars.ContextVar('cvar')\n\n def sub(num):\n for i in range(10):\n cvar.set(num + i)\n time.sleep(random.uniform(0.001, 0.05))\n self.assertEqual(cvar.get(), num + i)\n return num\n\n tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)\n try:\n results = list(tp.map(sub, range(10)))\n finally:\n tp.shutdown()\n self.assertEqual(results, list(range(10)))\n","source":"cpython_tests","origin":"Lib/test/test_context.py::ContextTest","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_17.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestFieldNoAnnotation(unittest.TestCase):\n def test_field_without_annotation(self):\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n @dataclass\n class C:\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base(self):\n @dataclass\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n\n def test_field_without_annotation_but_annotation_in_base_not_dataclass(self):\n # Same test, but with the base class not a dataclass.\n class B:\n f: int\n\n with self.assertRaisesRegex(TypeError,\n \"'f' is a field but has no type annotation\"):\n # This is still an error: make sure we don't pick up the\n # type annotation in the base class.\n @dataclass\n class C(B):\n f = field()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestFieldNoAnnotation","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_18.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestDocString(unittest.TestCase):\n def assertDocStrEqual(self, a, b):\n # Because 3.6 and 3.7 differ in how inspect.signature work\n # (see bpo #32108), for the time being just compare them with\n # whitespace stripped.\n self.assertEqual(a.replace(' ', ''), b.replace(' ', ''))\n\n @support.requires_docstrings\n def test_existing_docstring_not_overridden(self):\n @dataclass\n class C:\n \"\"\"Lorem ipsum\"\"\"\n x: int\n\n self.assertEqual(C.__doc__, \"Lorem ipsum\")\n\n def test_docstring_no_fields(self):\n @dataclass\n class C:\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C()\")\n\n def test_docstring_one_field(self):\n @dataclass\n class C:\n x: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int)\")\n\n def test_docstring_two_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int)\")\n\n def test_docstring_three_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n z: str\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int, z:str)\")\n\n def test_docstring_one_field_with_default(self):\n @dataclass\n class C:\n x: int = 3\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int=3)\")\n\n def test_docstring_one_field_with_default_none(self):\n @dataclass\n class C:\n x: Union[int, type(None)] = None\n\n self.assertDocStrEqual(C.__doc__, \"C(x:Optional[int]=None)\")\n\n def test_docstring_list_field(self):\n @dataclass\n class C:\n x: List[int]\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int])\")\n\n def test_docstring_list_field_with_default_factory(self):\n @dataclass\n class C:\n x: List[int] = field(default_factory=list)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int]=)\")\n\n def test_docstring_deque_field(self):\n @dataclass\n class C:\n x: deque\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque)\")\n\n def test_docstring_deque_field_with_default_factory(self):\n @dataclass\n class C:\n x: deque = field(default_factory=deque)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque=)\")\n\n def test_docstring_with_no_signature(self):\n # See https://github.com/python/cpython/issues/103449\n class Meta(type):\n __call__ = dict\n class Base(metaclass=Meta):\n pass\n\n @dataclass\n class C(Base):\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestDocString","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_19.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestInit(unittest.TestCase):\n def test_base_has_init(self):\n class B:\n def __init__(self):\n self.z = 100\n\n # Make sure that declaring this class doesn't raise an error.\n # The issue is that we can't override __init__ in our class,\n # but it should be okay to add __init__ to us if our base has\n # an __init__.\n @dataclass\n class C(B):\n x: int = 0\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertNotIn('z', vars(c))\n\n # Make sure that if we don't add an init, the base __init__\n # gets called.\n @dataclass(init=False)\n class C(B):\n x: int = 10\n c = C()\n self.assertEqual(c.x, 10)\n self.assertEqual(c.z, 100)\n\n def test_no_init(self):\n @dataclass(init=False)\n class C:\n i: int = 0\n self.assertEqual(C().i, 0)\n\n @dataclass(init=False)\n class C:\n i: int = 2\n def __init__(self):\n self.i = 3\n self.assertEqual(C().i, 3)\n\n def test_overwriting_init(self):\n # If the class has __init__, use it no matter the value of\n # init=.\n\n @dataclass\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(3).x, 6)\n\n @dataclass(init=True)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(4).x, 8)\n\n @dataclass(init=False)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(5).x, 10)\n\n def test_inherit_from_protocol(self):\n # Dataclasses inheriting from protocol should preserve their own `__init__`.\n # See bpo-45081.\n\n class P(Protocol):\n a: int\n\n @dataclass\n class C(P):\n a: int\n\n self.assertEqual(C(5).a, 5)\n\n @dataclass\n class D(P):\n def __init__(self, a):\n self.a = a * 2\n\n self.assertEqual(D(5).a, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestInit","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_20.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestRepr(unittest.TestCase):\n def test_repr(self):\n @dataclass\n class B:\n x: int\n\n @dataclass\n class C(B):\n y: int = 10\n\n o = C(4)\n self.assertEqual(repr(o), 'TestRepr.test_repr..C(x=4, y=10)')\n\n @dataclass\n class D(C):\n x: int = 20\n self.assertEqual(repr(D()), 'TestRepr.test_repr..D(x=20, y=10)')\n\n @dataclass\n class C:\n @dataclass\n class D:\n i: int\n @dataclass\n class E:\n pass\n self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr..C.D(i=0)')\n self.assertEqual(repr(C.E()), 'TestRepr.test_repr..C.E()')\n\n def test_no_repr(self):\n # Test a class with no __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n self.assertIn(f'{__name__}.TestRepr.test_no_repr..C object at',\n repr(C(3)))\n\n # Test a class with a __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'C-class'\n self.assertEqual(repr(C(3)), 'C-class')\n\n def test_overwriting_repr(self):\n # If the class has __repr__, use it no matter the value of\n # repr=.\n\n @dataclass\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=True)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestRepr","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_21.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestEq(unittest.TestCase):\n def test_recursive_eq(self):\n # Test a class with recursive child\n @dataclass\n class C:\n recursive: object = ...\n c = C()\n c.recursive = c\n self.assertEqual(c, c)\n\n def test_no_eq(self):\n # Test a class with no __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n self.assertNotEqual(C(0), C(0))\n c = C(3)\n self.assertEqual(c, c)\n\n # Test a class with an __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 10\n self.assertEqual(C(3), 10)\n\n def test_overwriting_eq(self):\n # If the class has __eq__, use it no matter the value of\n # eq=.\n\n @dataclass\n class C:\n x: int\n def __eq__(self, other):\n return other == 3\n self.assertEqual(C(1), 3)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=True)\n class C:\n x: int\n def __eq__(self, other):\n return other == 4\n self.assertEqual(C(1), 4)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 5\n self.assertEqual(C(1), 5)\n self.assertNotEqual(C(1), 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestEq","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_22.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestOrdering(unittest.TestCase):\n def test_functools_total_ordering(self):\n # Test that functools.total_ordering works with this class.\n @total_ordering\n @dataclass\n class C:\n x: int\n def __lt__(self, other):\n # Perform the test \"backward\", just to make\n # sure this is being called.\n return self.x >= other\n\n self.assertLess(C(0), -1)\n self.assertLessEqual(C(0), -1)\n self.assertGreater(C(0), 1)\n self.assertGreaterEqual(C(0), 1)\n\n def test_no_order(self):\n # Test that no ordering functions are added by default.\n @dataclass(order=False)\n class C:\n x: int\n # Make sure no order methods are added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__lt__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n # Test that __lt__ is still called\n @dataclass(order=False)\n class C:\n x: int\n def __lt__(self, other):\n return False\n # Make sure other methods aren't added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n def test_overwriting_order(self):\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __lt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __lt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __le__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __le__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __gt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __gt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __ge__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __ge__(self):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestOrdering","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_23.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestHash(unittest.TestCase):\n def test_unsafe_hash(self):\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n y: str\n self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))\n\n def test_hash_rules(self):\n def non_bool(value):\n # Map to something else that's True, but not a bool.\n if value is None:\n return None\n if value:\n return (3,)\n return 0\n\n def test(case, unsafe_hash, eq, frozen, with_hash, result):\n with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,\n frozen=frozen):\n if result != 'exception':\n if with_hash:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n else:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n pass\n\n # See if the result matches what's expected.\n if result == 'fn':\n # __hash__ contains the function we generated.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNotNone(C.__dict__['__hash__'])\n\n elif result == '':\n # __hash__ is not present in our class.\n if not with_hash:\n self.assertNotIn('__hash__', C.__dict__)\n\n elif result == 'none':\n # __hash__ is set to None.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNone(C.__dict__['__hash__'])\n\n elif result == 'exception':\n # Creating the class should cause an exception.\n # This only happens with with_hash==True.\n assert(with_hash)\n with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n\n else:\n assert False, f'unknown result {result!r}'\n\n # There are 8 cases of:\n # unsafe_hash=True/False\n # eq=True/False\n # frozen=True/False\n # And for each of these, a different result if\n # __hash__ is defined or not.\n for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([\n (False, False, False, '', ''),\n (False, False, True, '', ''),\n (False, True, False, 'none', ''),\n (False, True, True, 'fn', ''),\n (True, False, False, 'fn', 'exception'),\n (True, False, True, 'fn', 'exception'),\n (True, True, False, 'fn', 'exception'),\n (True, True, True, 'fn', 'exception'),\n ], 1):\n test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)\n test(case, unsafe_hash, eq, frozen, True, res_defined_hash)\n\n # Test non-bool truth values, too. This is just to\n # make sure the data-driven table in the decorator\n # handles non-bool values.\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)\n\n\n def test_eq_only(self):\n # If a class defines __eq__, __hash__ is automatically added\n # and set to None. This is normal Python behavior, not\n # related to dataclasses. Make sure we don't interfere with\n # that (see bpo=32546).\n\n @dataclass\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1))\n self.assertNotEqual(C(1), C(4))\n\n # And make sure things work in this case if we specify\n # unsafe_hash=True.\n @dataclass(unsafe_hash=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1.0))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n # And check that the classes __eq__ is being used, despite\n # specifying eq=True.\n @dataclass(unsafe_hash=True, eq=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == 3 and self.i == other.i\n self.assertEqual(C(3), C(3))\n self.assertNotEqual(C(1), C(1))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n def test_0_field_hash(self):\n @dataclass(frozen=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n @dataclass(unsafe_hash=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n def test_1_field_hash(self):\n @dataclass(frozen=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n def test_hash_no_args(self):\n # Test dataclasses with no hash= argument. This exists to\n # make sure that if the @dataclass parameter name is changed\n # or the non-default hashing behavior changes, the default\n # hashability keeps working the same way.\n\n class Base:\n def __hash__(self):\n return 301\n\n # If frozen or eq is None, then use the default value (do not\n # specify any value in the decorator).\n for frozen, eq, base, expected in [\n (None, None, object, 'unhashable'),\n (None, None, Base, 'unhashable'),\n (None, False, object, 'object'),\n (None, False, Base, 'base'),\n (None, True, object, 'unhashable'),\n (None, True, Base, 'unhashable'),\n (False, None, object, 'unhashable'),\n (False, None, Base, 'unhashable'),\n (False, False, object, 'object'),\n (False, False, Base, 'base'),\n (False, True, object, 'unhashable'),\n (False, True, Base, 'unhashable'),\n (True, None, object, 'tuple'),\n (True, None, Base, 'tuple'),\n (True, False, object, 'object'),\n (True, False, Base, 'base'),\n (True, True, object, 'tuple'),\n (True, True, Base, 'tuple'),\n ]:\n\n with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):\n # First, create the class.\n if frozen is None and eq is None:\n @dataclass\n class C(base):\n i: int\n elif frozen is None:\n @dataclass(eq=eq)\n class C(base):\n i: int\n elif eq is None:\n @dataclass(frozen=frozen)\n class C(base):\n i: int\n else:\n @dataclass(frozen=frozen, eq=eq)\n class C(base):\n i: int\n\n # Now, make sure it hashes as expected.\n if expected == 'unhashable':\n c = C(10)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(c)\n\n elif expected == 'base':\n self.assertEqual(hash(C(10)), 301)\n\n elif expected == 'object':\n # I'm not sure what test to use here. object's\n # hash isn't based on id(), so calling hash()\n # won't tell us much. So, just check the\n # function used is object's.\n self.assertIs(C.__hash__, object.__hash__)\n\n elif expected == 'tuple':\n self.assertEqual(hash(C(42)), hash((42,)))\n\n else:\n assert False, f'unknown value for expected={expected!r}'\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestHash","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_24.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestFrozen(unittest.TestCase):\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n c = C(10)\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertEqual(c.i, 10)\n\n def test_frozen_empty(self):\n @dataclass(frozen=True)\n class C:\n pass\n\n c = C()\n self.assertFalse(hasattr(c, 'i'))\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertFalse(hasattr(c, 'i'))\n with self.assertRaises(FrozenInstanceError):\n del c.i\n\n def test_inherit(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n @dataclass(frozen=True)\n class D(C):\n j: int\n\n d = D(0, 10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n with self.assertRaises(FrozenInstanceError):\n d.j = 6\n self.assertEqual(d.i, 0)\n self.assertEqual(d.j, 10)\n\n def test_inherit_nonfrozen_from_empty_frozen(self):\n @dataclass(frozen=True)\n class C:\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(C):\n j: int\n\n def test_inherit_frozen_mutliple_inheritance(self):\n @dataclass\n class NotFrozen:\n pass\n\n @dataclass(frozen=True)\n class Frozen:\n pass\n\n class NotDataclass:\n pass\n\n for bases in (\n (NotFrozen, Frozen),\n (Frozen, NotFrozen),\n (Frozen, NotDataclass),\n (NotDataclass, Frozen),\n ):\n with self.subTest(bases=bases):\n with self.assertRaisesRegex(\n TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one',\n ):\n @dataclass\n class NotFrozenChild(*bases):\n pass\n\n for bases in (\n (NotFrozen, Frozen),\n (Frozen, NotFrozen),\n (NotFrozen, NotDataclass),\n (NotDataclass, NotFrozen),\n ):\n with self.subTest(bases=bases):\n with self.assertRaisesRegex(\n TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one',\n ):\n @dataclass(frozen=True)\n class FrozenChild(*bases):\n pass\n\n def test_inherit_frozen_mutliple_inheritance_regular_mixins(self):\n @dataclass(frozen=True)\n class Frozen:\n pass\n\n class NotDataclass:\n pass\n\n class C1(Frozen, NotDataclass):\n pass\n self.assertEqual(C1.__mro__, (C1, Frozen, NotDataclass, object))\n\n class C2(NotDataclass, Frozen):\n pass\n self.assertEqual(C2.__mro__, (C2, NotDataclass, Frozen, object))\n\n @dataclass(frozen=True)\n class C3(Frozen, NotDataclass):\n pass\n self.assertEqual(C3.__mro__, (C3, Frozen, NotDataclass, object))\n\n @dataclass(frozen=True)\n class C4(NotDataclass, Frozen):\n pass\n self.assertEqual(C4.__mro__, (C4, NotDataclass, Frozen, object))\n\n def test_multiple_frozen_dataclasses_inheritance(self):\n @dataclass(frozen=True)\n class FrozenA:\n pass\n\n @dataclass(frozen=True)\n class FrozenB:\n pass\n\n class C1(FrozenA, FrozenB):\n pass\n self.assertEqual(C1.__mro__, (C1, FrozenA, FrozenB, object))\n\n class C2(FrozenB, FrozenA):\n pass\n self.assertEqual(C2.__mro__, (C2, FrozenB, FrozenA, object))\n\n @dataclass(frozen=True)\n class C3(FrozenA, FrozenB):\n pass\n self.assertEqual(C3.__mro__, (C3, FrozenA, FrozenB, object))\n\n @dataclass(frozen=True)\n class C4(FrozenB, FrozenA):\n pass\n self.assertEqual(C4.__mro__, (C4, FrozenB, FrozenA, object))\n\n def test_inherit_nonfrozen_from_empty(self):\n @dataclass\n class C:\n pass\n\n @dataclass\n class D(C):\n j: int\n\n d = D(3)\n self.assertEqual(d.j, 3)\n self.assertIsInstance(d, C)\n\n # Test both ways: with an intermediate normal (non-dataclass)\n # class and without an intermediate class.\n def test_inherit_nonfrozen_from_frozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass(frozen=True)\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(I):\n pass\n\n def test_inherit_frozen_from_nonfrozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one'):\n @dataclass(frozen=True)\n class D(I):\n pass\n\n def test_inherit_from_normal_class(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n class C:\n pass\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n @dataclass(frozen=True)\n class D(I):\n i: int\n\n d = D(10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n\n def test_non_frozen_normal_derived(self):\n # See bpo-32953.\n\n @dataclass(frozen=True)\n class D:\n x: int\n y: int = 10\n\n class S(D):\n pass\n\n s = S(3)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n s.cached = True\n\n # But can't change the frozen attributes.\n with self.assertRaises(FrozenInstanceError):\n s.x = 5\n with self.assertRaises(FrozenInstanceError):\n s.y = 5\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.cached, True)\n\n with self.assertRaises(FrozenInstanceError):\n del s.x\n self.assertEqual(s.x, 3)\n with self.assertRaises(FrozenInstanceError):\n del s.y\n self.assertEqual(s.y, 10)\n del s.cached\n self.assertFalse(hasattr(s, 'cached'))\n with self.assertRaises(AttributeError) as cm:\n del s.cached\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n\n def test_non_frozen_normal_derived_from_empty_frozen(self):\n @dataclass(frozen=True)\n class D:\n pass\n\n class S(D):\n pass\n\n s = S()\n self.assertFalse(hasattr(s, 'x'))\n s.x = 5\n self.assertEqual(s.x, 5)\n\n del s.x\n self.assertFalse(hasattr(s, 'x'))\n with self.assertRaises(AttributeError) as cm:\n del s.x\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n\n def test_overwriting_frozen(self):\n # frozen uses __setattr__ and __delattr__.\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __setattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __setattr__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __delattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __delattr__(self):\n pass\n\n @dataclass(frozen=False)\n class C:\n x: int\n def __setattr__(self, name, value):\n self.__dict__['x'] = value * 2\n self.assertEqual(C(10).x, 20)\n\n def test_frozen_hash(self):\n @dataclass(frozen=True)\n class C:\n x: Any\n\n # If x is immutable, we can compute the hash. No exception is\n # raised.\n hash(C(3))\n\n # If x is mutable, computing the hash is an error.\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(C({}))\n\n def test_frozen_deepcopy_without_slots(self):\n # see: https://github.com/python/cpython/issues/89683\n @dataclass(frozen=True, slots=False)\n class C:\n s: str\n\n c = C('hello')\n self.assertEqual(deepcopy(c), c)\n\n def test_frozen_deepcopy_with_slots(self):\n # see: https://github.com/python/cpython/issues/89683\n with self.subTest('generated __slots__'):\n @dataclass(frozen=True, slots=True)\n class C:\n s: str\n\n c = C('hello')\n self.assertEqual(deepcopy(c), c)\n\n with self.subTest('user-defined __slots__ and no __{get,set}state__'):\n @dataclass(frozen=True, slots=False)\n class C:\n __slots__ = ('s',)\n s: str\n\n # with user-defined slots, __getstate__ and __setstate__ are not\n # automatically added, hence the error\n err = r\"^cannot\\ assign\\ to\\ field\\ 's'$\"\n self.assertRaisesRegex(FrozenInstanceError, err, deepcopy, C(''))\n\n with self.subTest('user-defined __slots__ and __{get,set}state__'):\n @dataclass(frozen=True, slots=False)\n class C:\n __slots__ = ('s',)\n __getstate__ = dataclasses._dataclass_getstate\n __setstate__ = dataclasses._dataclass_setstate\n\n s: str\n\n c = C('hello')\n self.assertEqual(deepcopy(c), c)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestFrozen","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_25.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestSlots(unittest.TestCase):\n def test_simple(self):\n @dataclass\n class C:\n __slots__ = ('x',)\n x: Any\n\n # There was a bug where a variable in a slot was assumed to\n # also have a default value (of type\n # types.MemberDescriptorType).\n with self.assertRaisesRegex(TypeError,\n r\"__init__\\(\\) missing 1 required positional argument: 'x'\"):\n C()\n\n # We can create an instance, and assign to x.\n c = C(10)\n self.assertEqual(c.x, 10)\n c.x = 5\n self.assertEqual(c.x, 5)\n\n # We can't assign to anything else.\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'y'\"):\n c.y = 5\n\n def test_derived_added_field(self):\n # See bpo-33100.\n @dataclass\n class Base:\n __slots__ = ('x',)\n x: Any\n\n @dataclass\n class Derived(Base):\n x: int\n y: int\n\n d = Derived(1, 2)\n self.assertEqual((d.x, d.y), (1, 2))\n\n # We can add a new field to the derived instance.\n d.z = 10\n\n def test_generated_slots(self):\n @dataclass(slots=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n self.assertEqual((c.x, c.y), (1, 2))\n\n c.x = 3\n c.y = 4\n self.assertEqual((c.x, c.y), (3, 4))\n\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'z'\"):\n c.z = 5\n\n def test_add_slots_when_slots_exists(self):\n with self.assertRaisesRegex(TypeError, '^C already specifies __slots__$'):\n @dataclass(slots=True)\n class C:\n __slots__ = ('x',)\n x: int\n\n def test_generated_slots_value(self):\n\n class Root:\n __slots__ = {'x'}\n\n class Root2(Root):\n __slots__ = {'k': '...', 'j': ''}\n\n class Root3(Root2):\n __slots__ = ['h']\n\n class Root4(Root3):\n __slots__ = 'aa'\n\n @dataclass(slots=True)\n class Base(Root4):\n y: int\n j: str\n h: str\n\n self.assertEqual(Base.__slots__, ('y', ))\n\n @dataclass(slots=True)\n class Derived(Base):\n aa: float\n x: str\n z: int\n k: str\n h: str\n\n self.assertEqual(Derived.__slots__, ('z', ))\n\n @dataclass\n class AnotherDerived(Base):\n z: int\n\n self.assertNotIn('__slots__', AnotherDerived.__dict__)\n\n def test_cant_inherit_from_iterator_slots(self):\n\n class Root:\n __slots__ = iter(['a'])\n\n class Root2(Root):\n __slots__ = ('b', )\n\n with self.assertRaisesRegex(\n TypeError,\n \"^Slots of 'Root' cannot be determined\"\n ):\n @dataclass(slots=True)\n class C(Root2):\n x: int\n\n def test_returns_new_class(self):\n class A:\n x: int\n\n B = dataclass(A, slots=True)\n self.assertIsNot(A, B)\n\n self.assertFalse(hasattr(A, \"__slots__\"))\n self.assertTrue(hasattr(B, \"__slots__\"))\n\n # Can't be local to test_frozen_pickle.\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsClass:\n foo: str\n bar: int\n\n @dataclass(frozen=True)\n class FrozenWithoutSlotsClass:\n foo: str\n bar: int\n\n def test_frozen_pickle(self):\n # bpo-43999\n\n self.assertEqual(self.FrozenSlotsClass.__slots__, (\"foo\", \"bar\"))\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n obj = self.FrozenWithoutSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsGetStateClass:\n foo: str\n bar: int\n\n getstate_called: bool = field(default=False, compare=False)\n\n def __getstate__(self):\n object.__setattr__(self, 'getstate_called', True)\n return [self.foo, self.bar]\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsSetStateClass:\n foo: str\n bar: int\n\n setstate_called: bool = field(default=False, compare=False)\n\n def __setstate__(self, state):\n object.__setattr__(self, 'setstate_called', True)\n object.__setattr__(self, 'foo', state[0])\n object.__setattr__(self, 'bar', state[1])\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsAllStateClass:\n foo: str\n bar: int\n\n getstate_called: bool = field(default=False, compare=False)\n setstate_called: bool = field(default=False, compare=False)\n\n def __getstate__(self):\n object.__setattr__(self, 'getstate_called', True)\n return [self.foo, self.bar]\n\n def __setstate__(self, state):\n object.__setattr__(self, 'setstate_called', True)\n object.__setattr__(self, 'foo', state[0])\n object.__setattr__(self, 'bar', state[1])\n\n def test_frozen_slots_pickle_custom_state(self):\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsGetStateClass('a', 1)\n dumped = pickle.dumps(obj, protocol=proto)\n\n self.assertTrue(obj.getstate_called)\n self.assertEqual(obj, pickle.loads(dumped))\n\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsSetStateClass('a', 1)\n obj2 = pickle.loads(pickle.dumps(obj, protocol=proto))\n\n self.assertTrue(obj2.setstate_called)\n self.assertEqual(obj, obj2)\n\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsAllStateClass('a', 1)\n dumped = pickle.dumps(obj, protocol=proto)\n\n self.assertTrue(obj.getstate_called)\n\n obj2 = pickle.loads(dumped)\n self.assertTrue(obj2.setstate_called)\n self.assertEqual(obj, obj2)\n\n def test_slots_with_default_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default='b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_with_default_factory_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default_factory=lambda:'b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_no_weakref(self):\n @dataclass(slots=True)\n class A:\n # No weakref.\n pass\n\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A()\n with self.assertRaisesRegex(TypeError,\n \"cannot create weak reference\"):\n weakref.ref(a)\n with self.assertRaises(AttributeError):\n a.__weakref__\n\n def test_slots_weakref(self):\n @dataclass(slots=True, weakref_slot=True)\n class A:\n a: int\n\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n\n self.assertIs(a.__weakref__, a_ref)\n\n def test_slots_weakref_base_str(self):\n class Base:\n __slots__ = '__weakref__'\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_slots_weakref_base_tuple(self):\n # Same as test_slots_weakref_base, but use a tuple instead of a string\n # in the base class.\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still\n # weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_weakref_slot_without_slot(self):\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n @dataclass(weakref_slot=True)\n class A:\n a: int\n\n def test_weakref_slot_make_dataclass(self):\n A = make_dataclass('A', [('a', int),], slots=True, weakref_slot=True)\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n # And make sure if raises if slots=True is not given.\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n B = make_dataclass('B', [('a', int),], weakref_slot=True)\n\n def test_weakref_slot_subclass_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n # A *can* also specify weakref_slot=True if it wants to (gh-93521)\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. But an instance of A\n # is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_weakref_slot_subclass_no_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n @dataclass(slots=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. Even though A doesn't\n # specify weakref_slot, it should still be weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_weakref_slot_normal_base_weakref_slot(self):\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n field: int\n\n # __weakref__ is in the base class, not A. But an instance of\n # A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n\n def test_dataclass_derived_weakref_slot(self):\n class A:\n pass\n\n @dataclass(slots=True, weakref_slot=True)\n class B(A):\n pass\n\n self.assertEqual(B.__slots__, ())\n B()\n\n def test_dataclass_derived_generic(self):\n T = typing.TypeVar('T')\n\n @dataclass(slots=True, weakref_slot=True)\n class A(typing.Generic[T]):\n pass\n self.assertEqual(A.__slots__, ('__weakref__',))\n self.assertTrue(A.__weakref__)\n A()\n\n @dataclass(slots=True, weakref_slot=True)\n class B[T2]:\n pass\n self.assertEqual(B.__slots__, ('__weakref__',))\n self.assertTrue(B.__weakref__)\n B()\n\n def test_dataclass_derived_generic_from_base(self):\n T = typing.TypeVar('T')\n\n class RawBase: ...\n\n @dataclass(slots=True, weakref_slot=True)\n class C1(typing.Generic[T], RawBase):\n pass\n self.assertEqual(C1.__slots__, ())\n self.assertTrue(C1.__weakref__)\n C1()\n @dataclass(slots=True, weakref_slot=True)\n class C2(RawBase, typing.Generic[T]):\n pass\n self.assertEqual(C2.__slots__, ())\n self.assertTrue(C2.__weakref__)\n C2()\n\n @dataclass(slots=True, weakref_slot=True)\n class D[T2](RawBase):\n pass\n self.assertEqual(D.__slots__, ())\n self.assertTrue(D.__weakref__)\n D()\n\n def test_dataclass_derived_generic_from_slotted_base(self):\n T = typing.TypeVar('T')\n\n class WithSlots:\n __slots__ = ('a', 'b')\n\n @dataclass(slots=True, weakref_slot=True)\n class E1(WithSlots, Generic[T]):\n pass\n self.assertEqual(E1.__slots__, ('__weakref__',))\n self.assertTrue(E1.__weakref__)\n E1()\n @dataclass(slots=True, weakref_slot=True)\n class E2(Generic[T], WithSlots):\n pass\n self.assertEqual(E2.__slots__, ('__weakref__',))\n self.assertTrue(E2.__weakref__)\n E2()\n\n @dataclass(slots=True, weakref_slot=True)\n class F[T2](WithSlots):\n pass\n self.assertEqual(F.__slots__, ('__weakref__',))\n self.assertTrue(F.__weakref__)\n F()\n\n def test_dataclass_derived_generic_from_slotted_base(self):\n T = typing.TypeVar('T')\n\n class WithWeakrefSlot:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True, weakref_slot=True)\n class G1(WithWeakrefSlot, Generic[T]):\n pass\n self.assertEqual(G1.__slots__, ())\n self.assertTrue(G1.__weakref__)\n G1()\n @dataclass(slots=True, weakref_slot=True)\n class G2(Generic[T], WithWeakrefSlot):\n pass\n self.assertEqual(G2.__slots__, ())\n self.assertTrue(G2.__weakref__)\n G2()\n\n @dataclass(slots=True, weakref_slot=True)\n class H[T2](WithWeakrefSlot):\n pass\n self.assertEqual(H.__slots__, ())\n self.assertTrue(H.__weakref__)\n H()\n\n def test_dataclass_slot_dict(self):\n class WithDictSlot:\n __slots__ = ('__dict__',)\n\n @dataclass(slots=True)\n class A(WithDictSlot): ...\n\n self.assertEqual(A.__slots__, ())\n self.assertEqual(A().__dict__, {})\n A()\n\n @support.cpython_only\n def test_slots_with_wrong_init_subclass(self):\n # TODO: This test is for a kinda-buggy behavior.\n # Ideally, it should be fixed and `__init_subclass__`\n # should be fully supported in the future versions.\n # See https://github.com/python/cpython/issues/91126\n class WrongSuper:\n def __init_subclass__(cls, arg):\n pass\n\n with self.assertRaisesRegex(\n TypeError,\n \"missing 1 required positional argument: 'arg'\",\n ):\n @dataclass(slots=True)\n class WithWrongSuper(WrongSuper, arg=1):\n pass\n\n class CorrectSuper:\n args = []\n def __init_subclass__(cls, arg=\"default\"):\n cls.args.append(arg)\n\n @dataclass(slots=True)\n class WithCorrectSuper(CorrectSuper):\n pass\n\n # __init_subclass__ is called twice: once for `WithCorrectSuper`\n # and once for `WithCorrectSuper__slots__` new class\n # that we create internally.\n self.assertEqual(CorrectSuper.args, [\"default\", \"default\"])\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestSlots","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_26.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestDescriptors(unittest.TestCase):\n def test_set_name(self):\n # See bpo-33141.\n\n # Create a descriptor.\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n def __get__(self, instance, owner):\n if instance is not None:\n return 1\n return self\n\n # This is the case of just normal descriptor behavior, no\n # dataclass code is involved in initializing the descriptor.\n @dataclass\n class C:\n c: int=D()\n self.assertEqual(C.c.name, 'cx')\n\n # Now test with a default value and init=False, which is the\n # only time this is really meaningful. If not using\n # init=False, then the descriptor will be overwritten, anyway.\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n self.assertEqual(C().c, 1)\n\n def test_non_descriptor(self):\n # PEP 487 says __set_name__ should work on non-descriptors.\n # Create a descriptor.\n\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n\n def test_lookup_on_instance(self):\n # See bpo-33175.\n class D:\n pass\n\n d = D()\n # Create an attribute on the instance, not type.\n d.__set_name__ = Mock()\n\n # Make sure d.__set_name__ is not called.\n @dataclass\n class C:\n i: int=field(default=d, init=False)\n\n self.assertEqual(d.__set_name__.call_count, 0)\n\n def test_lookup_on_class(self):\n # See bpo-33175.\n class D:\n pass\n D.__set_name__ = Mock()\n\n # Make sure D.__set_name__ is called.\n @dataclass\n class C:\n i: int=field(default=D(), init=False)\n\n self.assertEqual(D.__set_name__.call_count, 1)\n\n def test_init_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_getting_field_calls_get(self):\n class D:\n pass\n\n D.__set__ = Mock()\n D.__get__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__get__ is called.\n D.__get__.reset_mock()\n value = c.i\n self.assertEqual(D.__get__.call_count, 1)\n\n def test_setting_field_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c.i = 10\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_setting_uninitialized_descriptor_field(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D\n\n # D.__set__ is not called because there's no D instance to call it on\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 0)\n\n # D.__set__ still isn't called after setting i to an instance of D\n # because descriptors don't behave like that when stored as instance vars\n c.i = D()\n c.i = 5\n self.assertEqual(D.__set__.call_count, 0)\n\n def test_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n return 100\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n c = C()\n self.assertEqual(c.i, 100)\n\n c = C(5)\n self.assertEqual(c.i, 5)\n\n def test_no_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n raise AttributeError()\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):\n c = C()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestDescriptors","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_27.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestMakeDataclass(unittest.TestCase):\n def test_simple(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace={'add_one': lambda self: self.x + 1})\n c = C(10)\n self.assertEqual((c.x, c.y), (10, 5))\n self.assertEqual(c.add_one(), 11)\n\n\n def test_no_mutate_namespace(self):\n # Make sure a provided namespace isn't mutated.\n ns = {}\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace=ns)\n self.assertEqual(ns, {})\n\n def test_base(self):\n class Base1:\n pass\n class Base2:\n pass\n C = make_dataclass('C',\n [('x', int)],\n bases=(Base1, Base2))\n c = C(2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n def test_base_dataclass(self):\n @dataclass\n class Base1:\n x: int\n class Base2:\n pass\n C = make_dataclass('C',\n [('y', int)],\n bases=(Base1, Base2))\n with self.assertRaisesRegex(TypeError, 'required positional'):\n c = C(2)\n c = C(1, 2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n self.assertEqual((c.x, c.y), (1, 2))\n\n def test_init_var(self):\n def post_init(self, y):\n self.x *= y\n\n C = make_dataclass('C',\n [('x', int),\n ('y', InitVar[int]),\n ],\n namespace={'__post_init__': post_init},\n )\n c = C(2, 3)\n self.assertEqual(vars(c), {'x': 6})\n self.assertEqual(len(fields(c)), 1)\n\n def test_class_var(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ])\n c = C(1)\n self.assertEqual(vars(c), {'x': 1})\n self.assertEqual(len(fields(c)), 1)\n self.assertEqual(C.y, 10)\n self.assertEqual(C.z, 20)\n\n def test_other_params(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ],\n init=False)\n # Make sure we have a repr, but no init.\n self.assertNotIn('__init__', vars(C))\n self.assertIn('__repr__', vars(C))\n\n # Make sure random other params don't work.\n with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):\n C = make_dataclass('C',\n [],\n xxinit=False)\n\n def test_no_types(self):\n C = make_dataclass('Point', ['x', 'y', 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': 'typing.Any',\n 'z': 'typing.Any'})\n\n C = make_dataclass('Point', ['x', ('y', int), 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': 'typing.Any',\n 'y': int,\n 'z': 'typing.Any'})\n\n def test_module_attr(self):\n self.assertEqual(ByMakeDataClass.__module__, __name__)\n self.assertEqual(ByMakeDataClass(1).__module__, __name__)\n self.assertEqual(WrongModuleMakeDataclass.__module__, \"custom\")\n Nested = make_dataclass('Nested', [])\n self.assertEqual(Nested.__module__, __name__)\n self.assertEqual(Nested().__module__, __name__)\n\n def test_pickle_support(self):\n for klass in [ByMakeDataClass, ManualModuleMakeDataClass]:\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n self.assertEqual(\n pickle.loads(pickle.dumps(klass, proto)),\n klass,\n )\n self.assertEqual(\n pickle.loads(pickle.dumps(klass(1), proto)),\n klass(1),\n )\n\n def test_cannot_be_pickled(self):\n for klass in [WrongNameMakeDataclass, WrongModuleMakeDataclass]:\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n with self.assertRaises(pickle.PickleError):\n pickle.dumps(klass, proto)\n with self.assertRaises(pickle.PickleError):\n pickle.dumps(klass(1), proto)\n\n def test_invalid_type_specification(self):\n for bad_field in [(),\n (1, 2, 3, 4),\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'Invalid field: '):\n make_dataclass('C', ['a', bad_field])\n\n # And test for things with no len().\n for bad_field in [float,\n lambda x:x,\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'has no len\\(\\)'):\n make_dataclass('C', ['a', bad_field])\n\n def test_duplicate_field_names(self):\n for field in ['a', 'ab']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'Field name duplicated'):\n make_dataclass('C', [field, 'a', field])\n\n def test_keyword_field_names(self):\n for field in ['for', 'async', 'await', 'as']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field, 'a'])\n\n def test_non_identifier_field_names(self):\n for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field, 'a'])\n\n def test_underscore_field_names(self):\n # Unlike namedtuple, it's okay if dataclass field names have\n # an underscore.\n make_dataclass('C', ['_', '_a', 'a_a', 'a_'])\n\n def test_funny_class_names_names(self):\n # No reason to prevent weird class names, since\n # types.new_class allows them.\n for classname in ['()', 'x,y', '*', '2@3', '']:\n with self.subTest(classname=classname):\n C = make_dataclass(classname, ['a', 'b'])\n self.assertEqual(C.__name__, classname)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestMakeDataclass","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_28.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestReplace(unittest.TestCase):\n def test(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n z: int = field(init=False, default=10)\n t: int = field(init=False, default=100)\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))\n self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))\n\n\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, x=3, z=20, t=50)\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, z=20)\n replace(c, x=3, z=20, t=50)\n\n # Make sure the result is still frozen.\n with self.assertRaisesRegex(FrozenInstanceError, \"cannot assign to field 'x'\"):\n c1.x = 3\n\n # Make sure we can't replace an attribute that doesn't exist,\n # if we're also replacing one that does exist. Test this\n # here, because setting attributes on frozen instances is\n # handled slightly differently from non-frozen ones.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'a'\"):\n c1 = replace(c, x=20, a=5)\n\n def test_invalid_field_name(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'z'\"):\n c1 = replace(c, z=3)\n\n def test_invalid_object(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(C, x=3)\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(0, x=3)\n\n def test_no_init(self):\n @dataclass\n class C:\n x: int\n y: int = field(init=False, default=10)\n\n c = C(1)\n c.y = 20\n\n # Make sure y gets the default value.\n c1 = replace(c, x=5)\n self.assertEqual((c1.x, c1.y), (5, 10))\n\n # Trying to replace y is an error.\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, x=2, y=30)\n\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, y=30)\n\n def test_classvar(self):\n @dataclass\n class C:\n x: int\n y: ClassVar[int] = 1000\n\n c = C(1)\n d = C(2)\n\n self.assertIs(c.y, d.y)\n self.assertEqual(c.y, 1000)\n\n # Trying to replace y is an error: can't replace ClassVars.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an \"\n \"unexpected keyword argument 'y'\"):\n replace(c, y=30)\n\n replace(c, x=5)\n\n def test_initvar_is_specified(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int]\n\n def __post_init__(self, y):\n self.x *= y\n\n c = C(1, 10)\n self.assertEqual(c.x, 10)\n with self.assertRaisesRegex(TypeError, r\"InitVar 'y' must be \"\n r\"specified with replace\\(\\)\"):\n replace(c, x=3)\n c = replace(c, x=3, y=5)\n self.assertEqual(c.x, 15)\n\n def test_initvar_with_default_value(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int] = None\n z: InitVar[int] = 42\n\n def __post_init__(self, y, z):\n if y is not None:\n self.x += y\n if z is not None:\n self.x += z\n\n c = C(x=1, y=10, z=1)\n self.assertEqual(replace(c), C(x=12))\n self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42))\n self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1))\n\n def test_recursive_repr(self):\n @dataclass\n class C:\n f: \"C\"\n\n c = C(None)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr..C(f=...)\")\n\n def test_recursive_repr_two_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: \"C\"\n\n c = C(None, None)\n c.f = c\n c.g = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_two_attrs\"\n \"..C(f=..., g=...)\")\n\n def test_recursive_repr_indirection(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n c.f = d\n d.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection\"\n \"..C(f=TestReplace.test_recursive_repr_indirection\"\n \"..D(f=...))\")\n\n def test_recursive_repr_indirection_two(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"E\"\n\n @dataclass\n class E:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n e = E(None)\n c.f = d\n d.f = e\n e.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection_two\"\n \"..C(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..D(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..E(f=...)))\")\n\n def test_recursive_repr_misc_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: int\n\n c = C(None, 1)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_misc_attrs\"\n \"..C(f=..., g=1)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestReplace","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_29.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestAbstract(unittest.TestCase):\n def test_abc_implementation(self):\n class Ordered(abc.ABC):\n @abc.abstractmethod\n def __lt__(self, other):\n pass\n\n @abc.abstractmethod\n def __le__(self, other):\n pass\n\n @dataclass(order=True)\n class Date(Ordered):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertFalse(inspect.isabstract(Date))\n self.assertGreater(Date(2020,12,25), Date(2020,8,31))\n\n def test_maintain_abc(self):\n class A(abc.ABC):\n @abc.abstractmethod\n def foo(self):\n pass\n\n @dataclass\n class Date(A):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertTrue(inspect.isabstract(Date))\n msg = \"class Date without an implementation for abstract method 'foo'\"\n self.assertRaisesRegex(TypeError, msg, Date)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestAbstract","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_30.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestMatchArgs(unittest.TestCase):\n def test_match_args(self):\n @dataclass\n class C:\n a: int\n self.assertEqual(C(42).__match_args__, ('a',))\n\n def test_explicit_match_args(self):\n ma = ()\n @dataclass\n class C:\n a: int\n __match_args__ = ma\n self.assertIs(C(42).__match_args__, ma)\n\n def test_bpo_43764(self):\n @dataclass(repr=False, eq=False, init=False)\n class X:\n a: int\n b: int\n c: int\n self.assertEqual(X.__match_args__, (\"a\", \"b\", \"c\"))\n\n def test_match_args_argument(self):\n @dataclass(match_args=False)\n class X:\n a: int\n self.assertNotIn('__match_args__', X.__dict__)\n\n @dataclass(match_args=False)\n class Y:\n a: int\n __match_args__ = ('b',)\n self.assertEqual(Y.__match_args__, ('b',))\n\n @dataclass(match_args=False)\n class Z(Y):\n z: int\n self.assertEqual(Z.__match_args__, ('b',))\n\n # Ensure parent dataclass __match_args__ is seen, if child class\n # specifies match_args=False.\n @dataclass\n class A:\n a: int\n z: int\n @dataclass(match_args=False)\n class B(A):\n b: int\n self.assertEqual(B.__match_args__, ('a', 'z'))\n\n def test_make_dataclasses(self):\n C = make_dataclass('C', [('x', int), ('y', int)])\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=True)\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=False)\n self.assertNotIn('__match__args__', C.__dict__)\n\n C = make_dataclass('C', [('x', int), ('y', int)], namespace={'__match_args__': ('z',)})\n self.assertEqual(C.__match_args__, ('z',))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestMatchArgs","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_31.py","code":"from dataclasses import *\nimport abc\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering\nimport typing\nimport dataclasses\nfrom test import support\n\n\nclass TestKeywordArgs(unittest.TestCase):\n def test_no_classvar_kwarg(self):\n msg = 'field a is a ClassVar but specifies kw_only'\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=True)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass(kw_only=True)\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n def test_field_marked_as_kwonly(self):\n #######################\n # Using dataclass(kw_only=True)\n @dataclass(kw_only=True)\n class A:\n a: int\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Using dataclass(kw_only=False)\n @dataclass(kw_only=False)\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Not specifying dataclass(kw_only)\n @dataclass\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n def test_match_args(self):\n # kw fields don't show up in __match_args__.\n @dataclass(kw_only=True)\n class C:\n a: int\n self.assertEqual(C(a=42).__match_args__, ())\n\n @dataclass\n class C:\n a: int\n b: int = field(kw_only=True)\n self.assertEqual(C(42, b=10).__match_args__, ('a',))\n\n def test_KW_ONLY(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n\n @dataclass(kw_only=True)\n class B:\n a: int\n _: KW_ONLY\n b: int\n c: int\n B(a=3, b=4, c=5)\n msg = \"takes 1 positional argument but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n B(3, 4, 5)\n\n # Explicitly make a field that follows KW_ONLY be non-keyword-only.\n @dataclass\n class C:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=False)\n c = C(1, 2, b=3)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(c=2, b=3, a=1)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n\n def test_KW_ONLY_as_string(self):\n @dataclass\n class A:\n a: int\n _: 'dataclasses.KW_ONLY'\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n def test_KW_ONLY_twice(self):\n msg = \"'Y' is KW_ONLY, but KW_ONLY has already been specified\"\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n Y: KW_ONLY\n b: int\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n Y: KW_ONLY\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n c: int\n Y: KW_ONLY\n\n # But this usage is okay, since it's not using KW_ONLY.\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=True)\n\n # And if inheriting, it's okay.\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n _: KW_ONLY\n d: int\n\n # Make sure the error is raised in a derived class.\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n X: KW_ONLY\n d: int\n Y: KW_ONLY\n\n\n def test_post_init(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n raise CustomError(f'{b=} {d=}')\n with self.assertRaisesRegex(CustomError, 'b=3 d=4'):\n A(1, c=2, b=3, d=4)\n\n @dataclass\n class B:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n self.a = b\n self.c = d\n b = B(1, c=2, b=3, d=4)\n self.assertEqual(asdict(b), {'a': 3, 'c': 4})\n\n def test_defaults(self):\n # For kwargs, make sure we can have defaults after non-defaults.\n @dataclass\n class A:\n a: int = 0\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n a = A(d=4, b=3)\n self.assertEqual(a.a, 0)\n self.assertEqual(a.b, 3)\n self.assertEqual(a.c, 1)\n self.assertEqual(a.d, 4)\n\n # Make sure we still check for non-kwarg non-defaults not following\n # defaults.\n err_regex = \"non-default argument 'z' follows default argument 'a'\"\n with self.assertRaisesRegex(TypeError, err_regex):\n @dataclass\n class A:\n a: int = 0\n z: int\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n def test_make_dataclass(self):\n A = make_dataclass(\"A\", ['a'], kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n B = make_dataclass(\"B\",\n ['a', ('b', int, field(kw_only=False))],\n kw_only=True)\n self.assertTrue(fields(B)[0].kw_only)\n self.assertFalse(fields(B)[1].kw_only)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestKeywordArgs","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"dict-union","pep":"584","introduced_in":"3.9","form":"modern","file":"dict-union/modern_01.py","code":"import collections\nimport collections.abc\nimport gc\nimport pickle\nimport random\nimport string\nimport sys\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import import_helper, get_c_recursion_limit\nfrom test import mapping_tests\n\n\ndef test_merge_operator(self):\n\n a = {0: 0, 1: 1, 2: 1}\n b = {1: 1, 2: 2, 3: 3}\n\n c = a.copy()\n c |= b\n\n self.assertEqual(a | b, {0: 0, 1: 1, 2: 2, 3: 3})\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n c = b.copy()\n c |= a\n\n self.assertEqual(b | a, {1: 1, 2: 1, 3: 3, 0: 0})\n self.assertEqual(c, {1: 1, 2: 1, 3: 3, 0: 0})\n\n c = a.copy()\n c |= [(1, 1), (2, 2), (3, 3)]\n\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n self.assertIs(a.__or__(None), NotImplemented)\n self.assertIs(a.__or__(()), NotImplemented)\n self.assertIs(a.__or__(\"BAD\"), NotImplemented)\n self.assertIs(a.__or__(\"\"), NotImplemented)\n\n self.assertRaises(TypeError, a.__ior__, None)\n self.assertEqual(a.__ior__(()), {0: 0, 1: 1, 2: 1})\n self.assertRaises(ValueError, a.__ior__, \"BAD\")\n self.assertEqual(a.__ior__(\"\"), {0: 0, 1: 1, 2: 1})\n","source":"cpython_tests","origin":"Lib/test/test_dict.py::DictTest.test_merge_operator","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"exception-notes","pep":"678","introduced_in":"3.11","form":"modern","file":"exception-notes/modern_01.py","code":"import copy\nimport os\nimport sys\nimport unittest\nimport pickle\nimport weakref\nimport errno\nfrom textwrap import dedent\nfrom test.support import (captured_stderr, check_impl_detail,\n cpython_only, gc_collect,\n no_tracing, script_helper,\n SuppressCrashReport,\n force_not_colorized)\nfrom test.support.import_helper import import_module\nfrom test.support.os_helper import TESTFN, unlink\nfrom test.support.warnings_helper import check_warnings\nfrom test import support\n\n\ndef test_notes(self):\n for e in [BaseException(1), Exception(2), ValueError(3)]:\n with self.subTest(e=e):\n self.assertFalse(hasattr(e, '__notes__'))\n e.add_note(\"My Note\")\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n with self.assertRaises(TypeError):\n e.add_note(42)\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n e.add_note(\"Your Note\")\n self.assertEqual(e.__notes__, [\"My Note\", \"Your Note\"])\n\n del e.__notes__\n self.assertFalse(hasattr(e, '__notes__'))\n\n e.add_note(\"Our Note\")\n self.assertEqual(e.__notes__, [\"Our Note\"])\n\n e.__notes__ = 42\n self.assertEqual(e.__notes__, 42)\n\n with self.assertRaises(TypeError):\n e.add_note(\"will not work\")\n self.assertEqual(e.__notes__, 42)\n","source":"cpython_tests","origin":"Lib/test/test_exceptions.py::ExceptionTests.test_notes","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"numeric-underscores","pep":"515","introduced_in":"3.6","form":"modern","file":"numeric-underscores/modern_01.py","code":"import sys\nimport time\nimport unittest\nfrom unittest import mock\nfrom test import support\nfrom test.test_grammar import (VALID_UNDERSCORE_LITERALS,\n INVALID_UNDERSCORE_LITERALS)\n\n\nclass IntStrDigitLimitsTests(unittest.TestCase):\n\n int_class = int # Override this in subclasses to reuse the suite.\n\n def setUp(self):\n super().setUp()\n self._previous_limit = sys.get_int_max_str_digits()\n sys.set_int_max_str_digits(2048)\n\n def tearDown(self):\n sys.set_int_max_str_digits(self._previous_limit)\n super().tearDown()\n\n def test_disabled_limit(self):\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n self.assertLess(sys.get_int_max_str_digits(), 20_000)\n with support.adjust_int_max_str_digits(0):\n self.assertEqual(sys.get_int_max_str_digits(), 0)\n i = self.int_class('1' * 20_000)\n str(i)\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n\n def test_max_str_digits_edge_cases(self):\n \"\"\"Ignore the +/- sign and space padding.\"\"\"\n int_class = self.int_class\n maxdigits = sys.get_int_max_str_digits()\n\n int_class('1' * maxdigits)\n int_class(' ' + '1' * maxdigits)\n int_class('1' * maxdigits + ' ')\n int_class('+' + '1' * maxdigits)\n int_class('-' + '1' * maxdigits)\n self.assertEqual(len(str(10 ** (maxdigits - 1))), maxdigits)\n\n def check(self, i, base=None):\n with self.assertRaises(ValueError):\n if base is None:\n self.int_class(i)\n else:\n self.int_class(i, base)\n\n def test_max_str_digits(self):\n maxdigits = sys.get_int_max_str_digits()\n\n self.check('1' * (maxdigits + 1))\n self.check(' ' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1) + ' ')\n self.check('+' + '1' * (maxdigits + 1))\n self.check('-' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1))\n\n i = 10 ** maxdigits\n with self.assertRaises(ValueError):\n str(i)\n\n def test_denial_of_service_prevented_int_to_str(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 50_000, maxdigits # A test prerequisite.\n\n huge_int = int(f'0x{\"c\"*65_000}', base=16) # 78268 decimal digits.\n digits = 78_268\n with (\n support.adjust_int_max_str_digits(digits),\n support.CPUStopwatch() as sw_convert):\n huge_decimal = str(huge_int)\n self.assertEqual(len(huge_decimal), digits)\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if sw_convert.seconds < sw_convert.clock_info.resolution * 2:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{sw_convert.seconds} seconds.')\n\n # We test with the limit almost at the size needed to check performance.\n # The performant limit check is slightly fuzzy, give it a some room.\n with support.adjust_int_max_str_digits(int(.995 * digits)):\n with (\n self.assertRaises(ValueError) as err,\n support.CPUStopwatch() as sw_fail_huge):\n str(huge_int)\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(sw_fail_huge.seconds, sw_convert.seconds/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge_int = int(f'0x{\"c\"*500_000}', base=16) # 602060 digits.\n with (\n self.assertRaises(ValueError) as err,\n support.CPUStopwatch() as sw_fail_extra_huge):\n # If not limited, 8 seconds said Zen based cloud VM.\n str(extra_huge_int)\n self.assertIn('conversion', str(err.exception))\n self.assertLess(sw_fail_extra_huge.seconds, sw_convert.seconds/2)\n\n def test_denial_of_service_prevented_str_to_int(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 100_000, maxdigits # A test prerequisite.\n\n digits = 133700\n huge = '8'*digits\n with (\n support.adjust_int_max_str_digits(digits),\n support.CPUStopwatch() as sw_convert):\n int(huge)\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if sw_convert.seconds < sw_convert.clock_info.resolution * 2:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{sw_convert.seconds} seconds.')\n\n with support.adjust_int_max_str_digits(digits - 1):\n with (\n self.assertRaises(ValueError) as err,\n support.CPUStopwatch() as sw_fail_huge):\n int(huge)\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(sw_fail_huge.seconds, sw_convert.seconds/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge = '7'*1_200_000\n with (\n self.assertRaises(ValueError) as err,\n support.CPUStopwatch() as sw_fail_extra_huge):\n # If not limited, 8 seconds in the Zen based cloud VM.\n int(extra_huge)\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(sw_fail_extra_huge.seconds, sw_convert.seconds/2)\n\n def test_power_of_two_bases_unlimited(self):\n \"\"\"The limit does not apply to power of 2 bases.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n\n for base in (2, 4, 8, 16, 32):\n with self.subTest(base=base):\n self.int_class('1' * (maxdigits + 1), base)\n assert maxdigits < 100_000\n self.int_class('1' * 100_000, base)\n\n def test_underscores_ignored(self):\n maxdigits = sys.get_int_max_str_digits()\n\n triples = maxdigits // 3\n s = '111' * triples\n s_ = '1_11' * triples\n self.int_class(s) # succeeds\n self.int_class(s_) # succeeds\n self.check(f'{s}111')\n self.check(f'{s_}_111')\n\n def test_sign_not_counted(self):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '5' * max_digits\n i = int_class(s)\n pos_i = int_class(f'+{s}')\n assert i == pos_i\n neg_i = int_class(f'-{s}')\n assert -pos_i == neg_i\n str(pos_i)\n str(neg_i)\n\n def _other_base_helper(self, base):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '2' * max_digits\n i = int_class(s, base)\n if base > 10:\n with self.assertRaises(ValueError):\n str(i)\n elif base < 10:\n str(i)\n with self.assertRaises(ValueError) as err:\n int_class(f'{s}1', base)\n\n def test_int_from_other_bases(self):\n base = 3\n with self.subTest(base=base):\n self._other_base_helper(base)\n base = 36\n with self.subTest(base=base):\n self._other_base_helper(base)\n\n def test_int_max_str_digits_is_per_interpreter(self):\n # Changing the limit in one interpreter does not change others.\n code = \"\"\"if 1:\n # Subinterpreters maintain and enforce their own limit\n import sys\n sys.set_int_max_str_digits(2323)\n try:\n int('3'*3333)\n except ValueError:\n pass\n else:\n raise AssertionError('Expected a int max str digits ValueError.')\n \"\"\"\n with support.adjust_int_max_str_digits(4000):\n before_value = sys.get_int_max_str_digits()\n self.assertEqual(support.run_in_subinterp(code), 0,\n 'subinterp code failure, check stderr.')\n after_value = sys.get_int_max_str_digits()\n self.assertEqual(before_value, after_value)\n","source":"cpython_tests","origin":"Lib/test/test_int.py::IntStrDigitLimitsTests","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"numeric-underscores","pep":"515","introduced_in":"3.6","form":"modern","file":"numeric-underscores/modern_02.py","code":"import sys\nimport time\nimport unittest\nfrom unittest import mock\nfrom test import support\nfrom test.test_grammar import (VALID_UNDERSCORE_LITERALS,\n INVALID_UNDERSCORE_LITERALS)\n\n\nclass PyLongModuleTests(unittest.TestCase):\n # Tests of the functions in _pylong.py. Those get used when the\n # number of digits in the input values are large enough.\n\n def setUp(self):\n super().setUp()\n self._previous_limit = sys.get_int_max_str_digits()\n sys.set_int_max_str_digits(0)\n\n def tearDown(self):\n sys.set_int_max_str_digits(self._previous_limit)\n super().tearDown()\n\n def _test_pylong_int_to_decimal(self, n, suffix):\n s = str(n)\n self.assertEqual(s[-10:], suffix)\n s2 = str(-n)\n self.assertEqual(s2, '-' + s)\n s3 = '%d' % n\n self.assertEqual(s3, s)\n s4 = b'%d' % n\n self.assertEqual(s4, s.encode('ascii'))\n\n def test_pylong_int_to_decimal(self):\n self._test_pylong_int_to_decimal((1 << 100_000), '9883109376')\n self._test_pylong_int_to_decimal((1 << 100_000) - 1, '9883109375')\n self._test_pylong_int_to_decimal(10**30_000, '0000000000')\n self._test_pylong_int_to_decimal(10**30_000 - 1, '9999999999')\n self._test_pylong_int_to_decimal(3**60_000, '9313200001')\n\n @support.requires_resource('cpu')\n def test_pylong_int_to_decimal_2(self):\n self._test_pylong_int_to_decimal(2**1_000_000, '2747109376')\n self._test_pylong_int_to_decimal(10**300_000, '0000000000')\n self._test_pylong_int_to_decimal(3**600_000, '3132000001')\n\n def test_pylong_int_divmod(self):\n n = (1 << 100_000)\n a, b = divmod(n*3 + 1, n)\n assert a == 3 and b == 1\n\n def test_pylong_str_to_int(self):\n v1 = 1 << 100_000\n s = str(v1)\n v2 = int(s)\n assert v1 == v2\n v3 = int(' -' + s)\n assert -v1 == v3\n v4 = int(' +' + s + ' ')\n assert v1 == v4\n with self.assertRaises(ValueError) as err:\n int(s + 'z')\n with self.assertRaises(ValueError) as err:\n int(s + '_')\n with self.assertRaises(ValueError) as err:\n int('_' + s)\n\n @support.cpython_only # tests implementation details of CPython.\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @mock.patch.object(_pylong, \"int_to_decimal_string\")\n def test_pylong_misbehavior_error_path_to_str(\n self, mock_int_to_str):\n with support.adjust_int_max_str_digits(20_000):\n big_value = int('7'*19_999)\n mock_int_to_str.return_value = None # not a str\n with self.assertRaises(TypeError) as ctx:\n str(big_value)\n self.assertIn('_pylong.int_to_decimal_string did not',\n str(ctx.exception))\n mock_int_to_str.side_effect = RuntimeError(\"testABC\")\n with self.assertRaises(RuntimeError):\n str(big_value)\n\n @support.cpython_only # tests implementation details of CPython.\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @mock.patch.object(_pylong, \"int_from_string\")\n def test_pylong_misbehavior_error_path_from_str(\n self, mock_int_from_str):\n big_value = '7'*19_999\n with support.adjust_int_max_str_digits(20_000):\n mock_int_from_str.return_value = b'not an int'\n with self.assertRaises(TypeError) as ctx:\n int(big_value)\n self.assertIn('_pylong.int_from_string did not',\n str(ctx.exception))\n\n mock_int_from_str.side_effect = RuntimeError(\"test123\")\n with self.assertRaises(RuntimeError):\n int(big_value)\n\n def test_pylong_roundtrip(self):\n from random import randrange, getrandbits\n bits = 5000\n while bits <= 1_000_000:\n bits += randrange(-100, 101) # break bitlength patterns\n hibit = 1 << (bits - 1)\n n = hibit | getrandbits(bits - 1)\n assert n.bit_length() == bits\n sn = str(n)\n self.assertFalse(sn.startswith('0'))\n self.assertEqual(n, int(sn))\n bits <<= 1\n","source":"cpython_tests","origin":"Lib/test/test_int.py::PyLongModuleTests","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"tarfile-filter","pep":"706","introduced_in":"3.12","form":"modern","file":"tarfile-filter/modern_01.py","code":"import errno\nimport sys\nimport os\nimport io\nfrom hashlib import sha256\nfrom contextlib import contextmanager, ExitStack\nfrom random import Random\nimport pathlib\nimport shutil\nimport re\nimport warnings\nimport stat\nimport unittest\nimport unittest.mock\nimport tarfile\nfrom test import archiver_tests\nfrom test import support\nfrom test.support import os_helper\nfrom test.support import script_helper\nfrom test.support import warnings_helper\n\n\nclass TestExtractionFilters(unittest.TestCase):\n\n # A temporary directory for the extraction results.\n # All files that \"escape\" the destination path should still end\n # up in this directory.\n outerdir = pathlib.Path(TEMPDIR) / 'outerdir'\n\n # The destination for the extraction, within `outerdir`\n destdir = outerdir / 'dest'\n\n @contextmanager\n def check_context(self, tar, filter):\n \"\"\"Extracts `tar` to `self.destdir` and allows checking the result\n\n If an error occurs, it must be checked using `expect_exception`\n\n Otherwise, all resulting files must be checked using `expect_file`,\n except the destination directory itself and parent directories of\n other files.\n When checking directories, do so before their contents.\n \"\"\"\n with os_helper.temp_dir(self.outerdir):\n try:\n tar.extractall(self.destdir, filter=filter)\n except Exception as exc:\n self.raised_exception = exc\n self.expected_paths = set()\n else:\n self.raised_exception = None\n self.expected_paths = set(self.outerdir.glob('**/*'))\n self.expected_paths.discard(self.destdir)\n try:\n yield\n finally:\n tar.close()\n if self.raised_exception:\n raise self.raised_exception\n self.assertEqual(self.expected_paths, set())\n\n def expect_file(self, name, type=None, symlink_to=None, mode=None,\n size=None):\n \"\"\"Check a single file. See check_context.\"\"\"\n if self.raised_exception:\n raise self.raised_exception\n # use normpath() rather than resolve() so we don't follow symlinks\n path = pathlib.Path(os.path.normpath(self.destdir / name))\n self.assertIn(path, self.expected_paths)\n self.expected_paths.remove(path)\n if mode is not None and os_helper.can_chmod() and os.name != 'nt':\n got = stat.filemode(stat.S_IMODE(path.stat().st_mode))\n self.assertEqual(got, mode)\n if type is None and isinstance(name, str) and name.endswith('/'):\n type = tarfile.DIRTYPE\n if symlink_to is not None:\n got = (self.destdir / name).readlink()\n expected = pathlib.Path(symlink_to)\n # The symlink might be the same (textually) as what we expect,\n # but some systems change the link to an equivalent path, so\n # we fall back to samefile().\n if expected != got:\n self.assertTrue(got.samefile(expected))\n elif type == tarfile.REGTYPE or type is None:\n self.assertTrue(path.is_file())\n elif type == tarfile.DIRTYPE:\n self.assertTrue(path.is_dir())\n elif type == tarfile.FIFOTYPE:\n self.assertTrue(path.is_fifo())\n else:\n raise NotImplementedError(type)\n if size is not None:\n self.assertEqual(path.stat().st_size, size)\n for parent in path.parents:\n self.expected_paths.discard(parent)\n\n def expect_exception(self, exc_type, message_re='.'):\n with self.assertRaisesRegex(exc_type, message_re):\n if self.raised_exception is not None:\n raise self.raised_exception\n self.raised_exception = None\n\n def test_benign_file(self):\n with ArchiveMaker() as arc:\n arc.add('benign.txt')\n for filter in 'fully_trusted', 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_file('benign.txt')\n\n def test_absolute(self):\n # Test handling a member with an absolute path\n # Inspired by 'absolute1' in https://github.com/jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add(self.outerdir / 'escaped.evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('../escaped.evil')\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n if str(self.outerdir).startswith('/'):\n # We strip leading slashes, as e.g. GNU tar does\n # (without --absolute-filenames).\n outerdir_stripped = str(self.outerdir).lstrip('/')\n self.expect_file(f'{outerdir_stripped}/escaped.evil')\n else:\n # On this system, absolute paths don't have leading\n # slashes.\n # So, there's nothing to strip. We refuse to unpack\n # to an absolute path, nonetheless.\n self.expect_exception(\n tarfile.AbsolutePathError,\n \"\"\"['\"].*escaped.evil['\"] has an absolute path\"\"\")\n\n @symlink_test\n def test_parent_symlink(self):\n # Test interplaying symlinks\n # Inspired by 'dirsymlink2a' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n\n # `current` links to `.` which is both:\n # - the destination directory\n # - `current` itself\n arc.add('current', symlink_to='.')\n\n # effectively points to ./../\n arc.add('parent', symlink_to='current/..')\n\n arc.add('parent/evil')\n\n if os_helper.can_symlink():\n with self.check_context(arc.open(), 'fully_trusted'):\n if self.raised_exception is not None:\n # Windows will refuse to create a file that's a symlink to itself\n # (and tarfile doesn't swallow that exception)\n self.expect_exception(FileExistsError)\n # The other cases will fail with this error too.\n # Skip the rest of this test.\n return\n else:\n self.expect_file('current', symlink_to='.')\n self.expect_file('parent', symlink_to='current/..')\n self.expect_file('../evil')\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"\"\"'parent/evil' would be extracted to ['\"].*evil['\"], \"\"\"\n + \"which is outside the destination\")\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.LinkOutsideDestinationError,\n \"\"\"'parent' would link to ['\"].*outerdir['\"], \"\"\"\n + \"which is outside the destination\")\n\n else:\n # No symlink support. The symlinks are ignored.\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('parent/evil')\n with self.check_context(arc.open(), 'tar'):\n self.expect_file('parent/evil')\n with self.check_context(arc.open(), 'data'):\n self.expect_file('parent/evil')\n\n @symlink_test\n def test_parent_symlink2(self):\n # Test interplaying symlinks\n # Inspired by 'dirsymlink2b' in jwilk/traversal-archives\n\n # Posix and Windows have different pathname resolution:\n # either symlink or a '..' component resolve first.\n # Let's see which we are on.\n if os_helper.can_symlink():\n testpath = os.path.join(TEMPDIR, 'resolution_test')\n os.mkdir(testpath)\n\n # testpath/current links to `.` which is all of:\n # - `testpath`\n # - `testpath/current`\n # - `testpath/current/current`\n # - etc.\n os.symlink('.', os.path.join(testpath, 'current'))\n\n # we'll test where `testpath/current/../file` ends up\n with open(os.path.join(testpath, 'current', '..', 'file'), 'w'):\n pass\n\n if os.path.exists(os.path.join(testpath, 'file')):\n # Windows collapses 'current\\..' to '.' first, leaving\n # 'testpath\\file'\n dotdot_resolves_early = True\n elif os.path.exists(os.path.join(testpath, '..', 'file')):\n # Posix resolves 'current' to '.' first, leaving\n # 'testpath/../file'\n dotdot_resolves_early = False\n else:\n raise AssertionError('Could not determine link resolution')\n\n with ArchiveMaker() as arc:\n\n # `current` links to `.` which is both the destination directory\n # and `current` itself\n arc.add('current', symlink_to='.')\n\n # `current/parent` is also available as `./parent`,\n # and effectively points to `./../`\n arc.add('current/parent', symlink_to='..')\n\n arc.add('parent/evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n if os_helper.can_symlink():\n self.expect_file('current', symlink_to='.')\n self.expect_file('parent', symlink_to='..')\n self.expect_file('../evil')\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'tar'):\n if os_helper.can_symlink():\n # Fail when extracting a file outside destination\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'data'):\n if os_helper.can_symlink():\n if dotdot_resolves_early:\n # Fail when extracting a file outside destination\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n # Fail as soon as we have a symlink outside the destination\n self.expect_exception(\n tarfile.LinkOutsideDestinationError,\n \"'current/parent' would link to \"\n + \"\"\"['\"].*outerdir['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n @symlink_test\n def test_absolute_symlink(self):\n # Test symlink to an absolute path\n # Inspired by 'dirsymlink' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('parent', symlink_to=self.outerdir)\n arc.add('parent/evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n if os_helper.can_symlink():\n self.expect_file('parent', symlink_to=self.outerdir)\n self.expect_file('../evil')\n else:\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'tar'):\n if os_helper.can_symlink():\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.AbsoluteLinkError,\n \"'parent' is a link to an absolute path\")\n\n def test_absolute_hardlink(self):\n # Test hardlink to an absolute path\n # Inspired by 'dirsymlink' in https://github.com/jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('parent', hardlink_to=self.outerdir / 'foo')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_exception(KeyError, \".*foo. not found\")\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_exception(KeyError, \".*foo. not found\")\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.AbsoluteLinkError,\n \"'parent' is a link to an absolute path\")\n\n @symlink_test\n def test_sly_relative0(self):\n # Inspired by 'relative0' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n # points to `../../tmp/moo`\n arc.add('../moo', symlink_to='..//tmp/moo')\n\n try:\n with self.check_context(arc.open(), filter='fully_trusted'):\n if os_helper.can_symlink():\n if isinstance(self.raised_exception, FileExistsError):\n # XXX TarFile happens to fail creating a parent\n # directory.\n # This might be a bug, but fixing it would hurt\n # security.\n # Note that e.g. GNU `tar` rejects '..' components,\n # so you could argue this is an invalid archive and we\n # just raise an bad type of exception.\n self.expect_exception(FileExistsError)\n else:\n self.expect_file('../moo', symlink_to='..//tmp/moo')\n else:\n # The symlink can't be extracted and is ignored\n pass\n except FileExistsError:\n pass\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'../moo' would be extracted to \"\n + \"'.*moo', which is outside \"\n + \"the destination\")\n\n @symlink_test\n def test_sly_relative2(self):\n # Inspired by 'relative2' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('tmp/')\n arc.add('tmp/../../moo', symlink_to='tmp/../..//tmp/moo')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('tmp', type=tarfile.DIRTYPE)\n if os_helper.can_symlink():\n self.expect_file('../moo', symlink_to='tmp/../../tmp/moo')\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'tmp/../../moo' would be extracted to \"\n + \"\"\"['\"].*moo['\"], which is outside the \"\"\"\n + \"destination\")\n\n @symlink_test\n def test_deep_symlink(self):\n # Test that symlinks and hardlinks inside a directory\n # point to the correct file (`target` of size 3).\n # If links aren't supported we get a copy of the file.\n with ArchiveMaker() as arc:\n arc.add('targetdir/target', size=3)\n # a hardlink's linkname is relative to the archive\n arc.add('linkdir/hardlink', hardlink_to=os.path.join(\n 'targetdir', 'target'))\n # a symlink's linkname is relative to the link's directory\n arc.add('linkdir/symlink', symlink_to=os.path.join(\n '..', 'targetdir', 'target'))\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n self.expect_file('targetdir/target', size=3)\n self.expect_file('linkdir/hardlink', size=3)\n if os_helper.can_symlink():\n self.expect_file('linkdir/symlink', size=3,\n symlink_to='../targetdir/target')\n else:\n self.expect_file('linkdir/symlink', size=3)\n\n @symlink_test\n def test_chains(self):\n # Test chaining of symlinks/hardlinks.\n # Symlinks are created before the files they point to.\n with ArchiveMaker() as arc:\n arc.add('linkdir/symlink', symlink_to='hardlink')\n arc.add('symlink2', symlink_to=os.path.join(\n 'linkdir', 'hardlink2'))\n arc.add('targetdir/target', size=3)\n arc.add('linkdir/hardlink', hardlink_to='targetdir/target')\n arc.add('linkdir/hardlink2', hardlink_to='linkdir/symlink')\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n self.expect_file('targetdir/target', size=3)\n self.expect_file('linkdir/hardlink', size=3)\n self.expect_file('linkdir/hardlink2', size=3)\n if os_helper.can_symlink():\n self.expect_file('linkdir/symlink', size=3,\n symlink_to='hardlink')\n self.expect_file('symlink2', size=3,\n symlink_to='linkdir/hardlink2')\n else:\n self.expect_file('linkdir/symlink', size=3)\n self.expect_file('symlink2', size=3)\n\n def test_modes(self):\n # Test how file modes are extracted\n # (Note that the modes are ignored on platforms without working chmod)\n with ArchiveMaker() as arc:\n arc.add('all_bits', mode='?rwsrwsrwt')\n arc.add('perm_bits', mode='?rwxrwxrwx')\n arc.add('exec_group_other', mode='?rw-rwxrwx')\n arc.add('read_group_only', mode='?---r-----')\n arc.add('no_bits', mode='?---------')\n arc.add('dir/', mode='?---rwsrwt')\n arc.add('dir_all_bits/', mode='?rwsrwsrwt')\n\n # On some systems, setting the uid, gid, and/or sticky bit is a no-ops.\n # Check which bits we can set, so we can compare tarfile machinery to\n # a simple chmod.\n tmp_filename = os.path.join(TEMPDIR, \"tmp.file\")\n with open(tmp_filename, 'w'):\n pass\n try:\n new_mode = (os.stat(tmp_filename).st_mode\n | stat.S_ISVTX | stat.S_ISGID | stat.S_ISUID)\n try:\n os.chmod(tmp_filename, new_mode)\n except OSError as exc:\n if exc.errno == getattr(errno, \"EFTYPE\", 0):\n # gh-108948: On FreeBSD, regular users cannot set\n # the sticky bit.\n self.skipTest(\"chmod() failed with EFTYPE: \"\n \"regular users cannot set sticky bit\")\n else:\n raise\n\n got_mode = os.stat(tmp_filename).st_mode\n _t_file = 't' if (got_mode & stat.S_ISVTX) else 'x'\n _suid_file = 's' if (got_mode & stat.S_ISUID) else 'x'\n _sgid_file = 's' if (got_mode & stat.S_ISGID) else 'x'\n finally:\n os.unlink(tmp_filename)\n\n os.mkdir(tmp_filename)\n new_mode = (os.stat(tmp_filename).st_mode\n | stat.S_ISVTX | stat.S_ISGID | stat.S_ISUID)\n os.chmod(tmp_filename, new_mode)\n got_mode = os.stat(tmp_filename).st_mode\n _t_dir = 't' if (got_mode & stat.S_ISVTX) else 'x'\n _suid_dir = 's' if (got_mode & stat.S_ISUID) else 'x'\n _sgid_dir = 's' if (got_mode & stat.S_ISGID) else 'x'\n os.rmdir(tmp_filename)\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('all_bits',\n mode=f'?rw{_suid_file}rw{_sgid_file}rw{_t_file}')\n self.expect_file('perm_bits', mode='?rwxrwxrwx')\n self.expect_file('exec_group_other', mode='?rw-rwxrwx')\n self.expect_file('read_group_only', mode='?---r-----')\n self.expect_file('no_bits', mode='?---------')\n self.expect_file('dir/', mode=f'?---rw{_sgid_dir}rw{_t_dir}')\n self.expect_file('dir_all_bits/',\n mode=f'?rw{_suid_dir}rw{_sgid_dir}rw{_t_dir}')\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_file('all_bits', mode='?rwxr-xr-x')\n self.expect_file('perm_bits', mode='?rwxr-xr-x')\n self.expect_file('exec_group_other', mode='?rw-r-xr-x')\n self.expect_file('read_group_only', mode='?---r-----')\n self.expect_file('no_bits', mode='?---------')\n self.expect_file('dir/', mode='?---r-xr-x')\n self.expect_file('dir_all_bits/', mode='?rwxr-xr-x')\n\n with self.check_context(arc.open(), 'data'):\n normal_dir_mode = stat.filemode(stat.S_IMODE(\n self.outerdir.stat().st_mode))\n self.expect_file('all_bits', mode='?rwxr-xr-x')\n self.expect_file('perm_bits', mode='?rwxr-xr-x')\n self.expect_file('exec_group_other', mode='?rw-r--r--')\n self.expect_file('read_group_only', mode='?rw-r-----')\n self.expect_file('no_bits', mode='?rw-------')\n self.expect_file('dir/', mode=normal_dir_mode)\n self.expect_file('dir_all_bits/', mode=normal_dir_mode)\n\n def test_pipe(self):\n # Test handling of a special file\n with ArchiveMaker() as arc:\n arc.add('foo', type=tarfile.FIFOTYPE)\n\n for filter in 'fully_trusted', 'tar':\n with self.check_context(arc.open(), filter):\n if hasattr(os, 'mkfifo'):\n self.expect_file('foo', type=tarfile.FIFOTYPE)\n else:\n # The pipe can't be extracted and is skipped.\n pass\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.SpecialFileError,\n \"'foo' is a special file\")\n\n def test_special_files(self):\n # Creating device files is tricky. Instead of attempting that let's\n # only check the filter result.\n for special_type in tarfile.FIFOTYPE, tarfile.CHRTYPE, tarfile.BLKTYPE:\n tarinfo = tarfile.TarInfo('foo')\n tarinfo.type = special_type\n trusted = tarfile.fully_trusted_filter(tarinfo, '')\n self.assertIs(trusted, tarinfo)\n tar = tarfile.tar_filter(tarinfo, '')\n self.assertEqual(tar.type, special_type)\n with self.assertRaises(tarfile.SpecialFileError) as cm:\n tarfile.data_filter(tarinfo, '')\n self.assertIsInstance(cm.exception.tarinfo, tarfile.TarInfo)\n self.assertEqual(cm.exception.tarinfo.name, 'foo')\n\n def test_fully_trusted_filter(self):\n # The 'fully_trusted' filter returns the original TarInfo objects.\n with tarfile.TarFile.open(tarname) as tar:\n for tarinfo in tar.getmembers():\n filtered = tarfile.fully_trusted_filter(tarinfo, '')\n self.assertIs(filtered, tarinfo)\n\n def test_tar_filter(self):\n # The 'tar' filter returns TarInfo objects with the same name/type.\n # (It can also fail for particularly \"evil\" input, but we don't have\n # that in the test archive.)\n with tarfile.TarFile.open(tarname) as tar:\n for tarinfo in tar.getmembers():\n filtered = tarfile.tar_filter(tarinfo, '')\n self.assertIs(filtered.name, tarinfo.name)\n self.assertIs(filtered.type, tarinfo.type)\n\n def test_data_filter(self):\n # The 'data' filter either raises, or returns TarInfo with the same\n # name/type.\n with tarfile.TarFile.open(tarname) as tar:\n for tarinfo in tar.getmembers():\n try:\n filtered = tarfile.data_filter(tarinfo, '')\n except tarfile.FilterError:\n continue\n self.assertIs(filtered.name, tarinfo.name)\n self.assertIs(filtered.type, tarinfo.type)\n\n def test_default_filter_warns(self):\n \"\"\"Ensure the default filter warns\"\"\"\n with ArchiveMaker() as arc:\n arc.add('foo')\n with warnings_helper.check_warnings(\n ('Python 3.14', DeprecationWarning)):\n with self.check_context(arc.open(), None):\n self.expect_file('foo')\n\n def test_change_default_filter_on_instance(self):\n tar = tarfile.TarFile(tarname, 'r')\n def strict_filter(tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n tar.extraction_filter = strict_filter\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_on_class(self):\n def strict_filter(tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n tar = tarfile.TarFile(tarname, 'r')\n with support.swap_attr(tarfile.TarFile, 'extraction_filter',\n staticmethod(strict_filter)):\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_on_subclass(self):\n class TarSubclass(tarfile.TarFile):\n def extraction_filter(self, tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n\n tar = TarSubclass(tarname, 'r')\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_to_string(self):\n tar = tarfile.TarFile(tarname, 'r')\n tar.extraction_filter = 'data'\n with self.check_context(tar, None):\n self.expect_exception(TypeError)\n\n def test_custom_filter(self):\n def custom_filter(tarinfo, path):\n self.assertIs(path, self.destdir)\n if tarinfo.name == 'move_this':\n return tarinfo.replace(name='moved')\n if tarinfo.name == 'ignore_this':\n return None\n return tarinfo\n\n with ArchiveMaker() as arc:\n arc.add('move_this')\n arc.add('ignore_this')\n arc.add('keep')\n with self.check_context(arc.open(), custom_filter):\n self.expect_file('moved')\n self.expect_file('keep')\n\n def test_bad_filter_name(self):\n with ArchiveMaker() as arc:\n arc.add('foo')\n with self.check_context(arc.open(), 'bad filter name'):\n self.expect_exception(ValueError)\n\n def test_stateful_filter(self):\n # Stateful filters should be possible.\n # (This doesn't really test tarfile. Rather, it demonstrates\n # that third parties can implement a stateful filter.)\n class StatefulFilter:\n def __enter__(self):\n self.num_files_processed = 0\n return self\n\n def __call__(self, tarinfo, path):\n try:\n tarinfo = tarfile.data_filter(tarinfo, path)\n except tarfile.FilterError:\n return None\n self.num_files_processed += 1\n return tarinfo\n\n def __exit__(self, *exc_info):\n self.done = True\n\n with ArchiveMaker() as arc:\n arc.add('good')\n arc.add('bad', symlink_to='/')\n arc.add('good')\n with StatefulFilter() as custom_filter:\n with self.check_context(arc.open(), custom_filter):\n self.expect_file('good')\n self.assertEqual(custom_filter.num_files_processed, 2)\n self.assertEqual(custom_filter.done, True)\n\n def test_errorlevel(self):\n def extracterror_filter(tarinfo, path):\n raise tarfile.ExtractError('failed with ExtractError')\n def filtererror_filter(tarinfo, path):\n raise tarfile.FilterError('failed with FilterError')\n def oserror_filter(tarinfo, path):\n raise OSError('failed with OSError')\n def tarerror_filter(tarinfo, path):\n raise tarfile.TarError('failed with base TarError')\n def valueerror_filter(tarinfo, path):\n raise ValueError('failed with ValueError')\n\n with ArchiveMaker() as arc:\n arc.add('file')\n\n # If errorlevel is 0, errors affected by errorlevel are ignored\n\n with self.check_context(arc.open(errorlevel=0), extracterror_filter):\n self.expect_file('file')\n\n with self.check_context(arc.open(errorlevel=0), filtererror_filter):\n self.expect_file('file')\n\n with self.check_context(arc.open(errorlevel=0), oserror_filter):\n self.expect_file('file')\n\n with self.check_context(arc.open(errorlevel=0), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=0), valueerror_filter):\n self.expect_exception(ValueError)\n\n # If 1, all fatal errors are raised\n\n with self.check_context(arc.open(errorlevel=1), extracterror_filter):\n self.expect_file('file')\n\n with self.check_context(arc.open(errorlevel=1), filtererror_filter):\n self.expect_exception(tarfile.FilterError)\n\n with self.check_context(arc.open(errorlevel=1), oserror_filter):\n self.expect_exception(OSError)\n\n with self.check_context(arc.open(errorlevel=1), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=1), valueerror_filter):\n self.expect_exception(ValueError)\n\n # If 2, all non-fatal errors are raised as well.\n\n with self.check_context(arc.open(errorlevel=2), extracterror_filter):\n self.expect_exception(tarfile.ExtractError)\n\n with self.check_context(arc.open(errorlevel=2), filtererror_filter):\n self.expect_exception(tarfile.FilterError)\n\n with self.check_context(arc.open(errorlevel=2), oserror_filter):\n self.expect_exception(OSError)\n\n with self.check_context(arc.open(errorlevel=2), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=2), valueerror_filter):\n self.expect_exception(ValueError)\n\n # We only handle ExtractionError, FilterError & OSError specially.\n\n with self.check_context(arc.open(errorlevel='boo!'), filtererror_filter):\n self.expect_exception(TypeError) # errorlevel is not int\n","source":"cpython_tests","origin":"Lib/test/test_tarfile.py::TestExtractionFilters","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"tarfile-filter","pep":"706","introduced_in":"3.12","form":"modern","file":"tarfile-filter/modern_02.py","code":"import errno\nimport sys\nimport os\nimport io\nfrom hashlib import sha256\nfrom contextlib import contextmanager, ExitStack\nfrom random import Random\nimport pathlib\nimport shutil\nimport re\nimport warnings\nimport stat\nimport unittest\nimport unittest.mock\nimport tarfile\nfrom test import archiver_tests\nfrom test import support\nfrom test.support import os_helper\nfrom test.support import script_helper\nfrom test.support import warnings_helper\n\n\nclass NoneInfoExtractTests(ReadTest):\n # These mainly check that all kinds of members are extracted successfully\n # if some metadata is None.\n # Some of the methods do additional spot checks.\n\n # We also test that the default filters can deal with None.\n\n extraction_filter = None\n\n @classmethod\n def setUpClass(cls):\n tar = tarfile.open(tarname, mode='r', encoding=\"iso8859-1\")\n cls.control_dir = pathlib.Path(TEMPDIR) / \"extractall_ctrl\"\n tar.errorlevel = 0\n with ExitStack() as cm:\n if cls.extraction_filter is None:\n cm.enter_context(warnings.catch_warnings(\n action=\"ignore\", category=DeprecationWarning))\n tar.extractall(cls.control_dir, filter=cls.extraction_filter)\n tar.close()\n cls.control_paths = set(\n p.relative_to(cls.control_dir)\n for p in pathlib.Path(cls.control_dir).glob('**/*'))\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.control_dir)\n\n def check_files_present(self, directory):\n got_paths = set(\n p.relative_to(directory)\n for p in pathlib.Path(directory).glob('**/*'))\n self.assertEqual(self.control_paths, got_paths)\n\n @contextmanager\n def extract_with_none(self, *attr_names):\n DIR = pathlib.Path(TEMPDIR) / \"extractall_none\"\n self.tar.errorlevel = 0\n for member in self.tar.getmembers():\n for attr_name in attr_names:\n setattr(member, attr_name, None)\n with os_helper.temp_dir(DIR):\n self.tar.extractall(DIR, filter='fully_trusted')\n self.check_files_present(DIR)\n yield DIR\n\n def test_extractall_none_mtime(self):\n # mtimes of extracted files should be later than 'now' -- the mtime\n # of a previously created directory.\n now = pathlib.Path(TEMPDIR).stat().st_mtime\n with self.extract_with_none('mtime') as DIR:\n for path in pathlib.Path(DIR).glob('**/*'):\n with self.subTest(path=path):\n try:\n mtime = path.stat().st_mtime\n except OSError:\n # Some systems can't stat symlinks, ignore those\n if not path.is_symlink():\n raise\n else:\n self.assertGreaterEqual(path.stat().st_mtime, now)\n\n def test_extractall_none_mode(self):\n # modes of directories and regular files should match the mode\n # of a \"normally\" created directory or regular file\n dir_mode = pathlib.Path(TEMPDIR).stat().st_mode\n regular_file = pathlib.Path(TEMPDIR) / 'regular_file'\n regular_file.write_text('')\n regular_file_mode = regular_file.stat().st_mode\n with self.extract_with_none('mode') as DIR:\n for path in pathlib.Path(DIR).glob('**/*'):\n with self.subTest(path=path):\n if path.is_dir():\n self.assertEqual(path.stat().st_mode, dir_mode)\n elif path.is_file():\n self.assertEqual(path.stat().st_mode,\n regular_file_mode)\n\n def test_extractall_none_uid(self):\n with self.extract_with_none('uid'):\n pass\n\n def test_extractall_none_gid(self):\n with self.extract_with_none('gid'):\n pass\n\n def test_extractall_none_uname(self):\n with self.extract_with_none('uname'):\n pass\n\n def test_extractall_none_gname(self):\n with self.extract_with_none('gname'):\n pass\n\n def test_extractall_none_ownership(self):\n with self.extract_with_none('uid', 'gid', 'uname', 'gname'):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_tarfile.py::NoneInfoExtractTests","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_01.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS, requires_gil_enabled\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\n\n\nclass ZoneInfoCacheTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n def setUp(self):\n self.klass.clear_cache()\n super().setUp()\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @property\n def tzpath(self):\n return [self.zoneinfo_data.tzpath]\n\n def test_ephemeral_zones(self):\n self.assertIs(\n self.klass(\"America/Los_Angeles\"), self.klass(\"America/Los_Angeles\")\n )\n\n def test_strong_refs(self):\n tz0 = self.klass(\"Australia/Sydney\")\n tz1 = self.klass(\"Australia/Sydney\")\n\n self.assertIs(tz0, tz1)\n\n def test_no_cache(self):\n\n tz0 = self.klass(\"Europe/Lisbon\")\n tz1 = self.klass.no_cache(\"Europe/Lisbon\")\n\n self.assertIsNot(tz0, tz1)\n\n def test_cache_reset_tzpath(self):\n \"\"\"Test that the cache persists when tzpath has been changed.\n\n The PEP specifies that as long as a reference exists to one zone\n with a given key, the primary constructor must continue to return\n the same object.\n \"\"\"\n zi0 = self.klass(\"America/Los_Angeles\")\n with self.tzpath_context([]):\n zi1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIs(zi0, zi1)\n\n def test_clear_cache_explicit_none(self):\n la0 = self.klass(\"America/Los_Angeles\")\n self.klass.clear_cache(only_keys=None)\n la1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIsNot(la0, la1)\n\n def test_clear_cache_one_key(self):\n \"\"\"Tests that you can clear a single key from the cache.\"\"\"\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n\n self.klass.clear_cache(only_keys=[\"America/Los_Angeles\"])\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n\n self.assertIsNot(la0, la1)\n self.assertIs(dub0, dub1)\n\n def test_clear_cache_two_keys(self):\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n tok0 = self.klass(\"Asia/Tokyo\")\n\n self.klass.clear_cache(\n only_keys=[\"America/Los_Angeles\", \"Europe/Dublin\"]\n )\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n tok1 = self.klass(\"Asia/Tokyo\")\n\n self.assertIsNot(la0, la1)\n self.assertIsNot(dub0, dub1)\n self.assertIs(tok0, tok1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ZoneInfoCacheTest","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_02.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS, requires_gil_enabled\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\n\n\nclass TzPathTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n @staticmethod\n @contextlib.contextmanager\n def python_tzpath_context(value):\n path_var = \"PYTHONTZPATH\"\n unset_env_sentinel = object()\n old_env = unset_env_sentinel\n try:\n with OS_ENV_LOCK:\n old_env = os.environ.get(path_var, None)\n os.environ[path_var] = value\n yield\n finally:\n if old_env is unset_env_sentinel:\n # In this case, `old_env` was never retrieved from the\n # environment for whatever reason, so there's no need to\n # reset the environment TZPATH.\n pass\n elif old_env is None:\n del os.environ[path_var]\n else:\n os.environ[path_var] = old_env # pragma: nocover\n\n def test_env_variable(self):\n \"\"\"Tests that the environment variable works with reset_tzpath.\"\"\"\n new_paths = [\n (\"\", []),\n (f\"{DRIVE}/etc/zoneinfo\", [f\"{DRIVE}/etc/zoneinfo\"]),\n (f\"{DRIVE}/a/b/c{os.pathsep}{DRIVE}/d/e/f\", [f\"{DRIVE}/a/b/c\", f\"{DRIVE}/d/e/f\"]),\n ]\n\n for new_path_var, expected_result in new_paths:\n with self.python_tzpath_context(new_path_var):\n with self.subTest(tzpath=new_path_var):\n self.module.reset_tzpath()\n tzpath = self.module.TZPATH\n self.assertSequenceEqual(tzpath, expected_result)\n\n def test_env_variable_relative_paths(self):\n test_cases = [\n [(\"path/to/somewhere\",), ()],\n [\n (f\"{DRIVE}/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (f\"{DRIVE}/usr/share/zoneinfo\",),\n ],\n [(\"../relative/path\",), ()],\n [\n (f\"{DRIVE}/usr/share/zoneinfo\", \"../relative/path\",),\n (f\"{DRIVE}/usr/share/zoneinfo\",),\n ],\n [(\"path/to/somewhere\", \"../relative/path\",), ()],\n [\n (\n f\"{DRIVE}/usr/share/zoneinfo\",\n \"path/to/somewhere\",\n \"../relative/path\",\n ),\n (f\"{DRIVE}/usr/share/zoneinfo\",),\n ],\n ]\n\n for input_paths, expected_paths in test_cases:\n path_var = os.pathsep.join(input_paths)\n with self.python_tzpath_context(path_var):\n with self.subTest(\"warning\", path_var=path_var):\n # Note: Per PEP 615 the warning is implementation-defined\n # behavior, other implementations need not warn.\n with self.assertWarns(self.module.InvalidTZPathWarning) as w:\n self.module.reset_tzpath()\n self.assertEqual(w.warnings[0].filename, __file__)\n\n tzpath = self.module.TZPATH\n with self.subTest(\"filtered\", path_var=path_var):\n self.assertSequenceEqual(tzpath, expected_paths)\n\n def test_env_variable_relative_paths_warning_location(self):\n path_var = \"path/to/somewhere\"\n\n with self.python_tzpath_context(path_var):\n with CleanImport(\"zoneinfo\", \"zoneinfo._tzpath\"):\n with self.assertWarns(RuntimeWarning) as w:\n import zoneinfo\n InvalidTZPathWarning = zoneinfo.InvalidTZPathWarning\n self.assertIsInstance(w.warnings[0].message, InvalidTZPathWarning)\n # It should represent the current file:\n self.assertEqual(w.warnings[0].filename, __file__)\n\n def test_reset_tzpath_kwarg(self):\n self.module.reset_tzpath(to=[f\"{DRIVE}/a/b/c\"])\n\n self.assertSequenceEqual(self.module.TZPATH, (f\"{DRIVE}/a/b/c\",))\n\n def test_reset_tzpath_relative_paths(self):\n bad_values = [\n (\"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"path/to/somewhere\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\", \"../relative/path\",),\n ]\n for input_paths in bad_values:\n with self.subTest(input_paths=input_paths):\n with self.assertRaises(ValueError):\n self.module.reset_tzpath(to=input_paths)\n\n def test_tzpath_type_error(self):\n bad_values = [\n \"/etc/zoneinfo:/usr/share/zoneinfo\",\n b\"/etc/zoneinfo:/usr/share/zoneinfo\",\n 0,\n ]\n\n for bad_value in bad_values:\n with self.subTest(value=bad_value):\n with self.assertRaises(TypeError):\n self.module.reset_tzpath(bad_value)\n\n def test_tzpath_attribute(self):\n tzpath_0 = [f\"{DRIVE}/one\", f\"{DRIVE}/two\"]\n tzpath_1 = [f\"{DRIVE}/three\"]\n\n with self.tzpath_context(tzpath_0):\n query_0 = self.module.TZPATH\n\n with self.tzpath_context(tzpath_1):\n query_1 = self.module.TZPATH\n\n self.assertSequenceEqual(tzpath_0, query_0)\n self.assertSequenceEqual(tzpath_1, query_1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TzPathTest","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_03.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS, requires_gil_enabled\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\n\n\nclass TestModule(ZoneInfoTestBase):\n module = py_zoneinfo\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @cached_property\n def _UTC_bytes(self):\n zone_file = self.zoneinfo_data.path_from_key(\"UTC\")\n with open(zone_file, \"rb\") as f:\n return f.read()\n\n def touch_zone(self, key, tz_root):\n \"\"\"Creates a valid TZif file at key under the zoneinfo root tz_root.\n\n tz_root must exist, but all folders below that will be created.\n \"\"\"\n if not os.path.exists(tz_root):\n raise FileNotFoundError(f\"{tz_root} does not exist.\")\n\n root_dir, *tail = key.rsplit(\"/\", 1)\n if tail: # If there's no tail, then the first component isn't a dir\n os.makedirs(os.path.join(tz_root, root_dir), exist_ok=True)\n\n zonefile_path = os.path.join(tz_root, key)\n with open(zonefile_path, \"wb\") as f:\n f.write(self._UTC_bytes)\n\n def test_getattr_error(self):\n with self.assertRaises(AttributeError):\n self.module.NOATTRIBUTE\n\n def test_dir_contains_all(self):\n \"\"\"dir(self.module) should at least contain everything in __all__.\"\"\"\n module_all_set = set(self.module.__all__)\n module_dir_set = set(dir(self.module))\n\n difference = module_all_set - module_dir_set\n\n self.assertFalse(difference)\n\n def test_dir_unique(self):\n \"\"\"Test that there are no duplicates in dir(self.module)\"\"\"\n module_dir = dir(self.module)\n module_unique = set(module_dir)\n\n self.assertCountEqual(module_dir, module_unique)\n\n def test_available_timezones(self):\n with self.tzpath_context([self.zoneinfo_data.tzpath]):\n self.assertTrue(self.zoneinfo_data.keys) # Sanity check\n\n available_keys = self.module.available_timezones()\n zoneinfo_keys = set(self.zoneinfo_data.keys)\n\n # If tzdata is not present, zoneinfo_keys == available_keys,\n # otherwise it should be a subset.\n union = zoneinfo_keys & available_keys\n self.assertEqual(zoneinfo_keys, union)\n\n def test_available_timezones_weirdzone(self):\n with tempfile.TemporaryDirectory() as td:\n # Make a fictional zone at \"Mars/Olympus_Mons\"\n self.touch_zone(\"Mars/Olympus_Mons\", td)\n\n with self.tzpath_context([td]):\n available_keys = self.module.available_timezones()\n self.assertIn(\"Mars/Olympus_Mons\", available_keys)\n\n def test_folder_exclusions(self):\n expected = {\n \"America/Los_Angeles\",\n \"America/Santiago\",\n \"America/Indiana/Indianapolis\",\n \"UTC\",\n \"Europe/Paris\",\n \"Europe/London\",\n \"Asia/Tokyo\",\n \"Australia/Sydney\",\n }\n\n base_tree = list(expected)\n posix_tree = [f\"posix/{x}\" for x in base_tree]\n right_tree = [f\"right/{x}\" for x in base_tree]\n\n cases = [\n (\"base_tree\", base_tree),\n (\"base_and_posix\", base_tree + posix_tree),\n (\"base_and_right\", base_tree + right_tree),\n (\"all_trees\", base_tree + right_tree + posix_tree),\n ]\n\n with tempfile.TemporaryDirectory() as td:\n for case_name, tree in cases:\n tz_root = os.path.join(td, case_name)\n os.mkdir(tz_root)\n\n for key in tree:\n self.touch_zone(key, tz_root)\n\n with self.tzpath_context([tz_root]):\n with self.subTest(case_name):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n\n def test_exclude_posixrules(self):\n expected = {\n \"America/New_York\",\n \"Europe/London\",\n }\n\n tree = list(expected) + [\"posixrules\"]\n\n with tempfile.TemporaryDirectory() as td:\n for key in tree:\n self.touch_zone(key, td)\n\n with self.tzpath_context([td]):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TestModule","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.13","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_04.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS, requires_gil_enabled\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import OS_ENV_LOCK, TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\n\n\nclass ExtensionBuiltTest(unittest.TestCase):\n \"\"\"Smoke test to ensure that the C and Python extensions are both tested.\n\n Because the intention is for the Python and C versions of ZoneInfo to\n behave identically, these tests necessarily rely on implementation details,\n so the tests may need to be adjusted if the implementations change. Do not\n rely on these tests as an indication of stable properties of these classes.\n \"\"\"\n\n def test_cache_location(self):\n # The pure Python version stores caches on attributes, but the C\n # extension stores them in C globals (at least for now)\n self.assertFalse(hasattr(c_zoneinfo.ZoneInfo, \"_weak_cache\"))\n self.assertTrue(hasattr(py_zoneinfo.ZoneInfo, \"_weak_cache\"))\n\n @requires_gil_enabled(\"gh-117783: types may be immortalized\")\n def test_gc_tracked(self):\n import gc\n\n self.assertTrue(gc.is_tracked(py_zoneinfo.ZoneInfo))\n self.assertTrue(gc.is_tracked(c_zoneinfo.ZoneInfo))\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ExtensionBuiltTest","origin_revision":"v3.13.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_01.py","code":"from typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_02.py","code":"import typing\nx: typing.List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_03.py","code":"from typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: List[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> List[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_01.py","code":"from typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_02.py","code":"import typing\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_03.py","code":"from typing import List\nSomeAlias = list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: list[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> list[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_01.py","code":"x = lambda foo: None","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[lambdas do not have type annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_02.py","code":"from __future__ import annotations\nfrom typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_03.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not a PEP 585 type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_01.py","code":"from __future__ import annotations\ndef foo(var: \"MyClass\") -> \"MyClass\":\n x: \"MyClass\"\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Simple annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_02.py","code":"from __future__ import annotations\nasync def foo(var: \"MyClass\") -> \"MyClass\":\n ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[simple async annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_03.py","code":"from __future__ import annotations\ndef foo(*, inplace: \"bool\"): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Kwonly, typed]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_04.py","code":"from __future__ import annotations\ndef foo(*args: \"str\", **kwargs: \"int\"): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Vararg and kwarg typed]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_05.py","code":"from __future__ import annotations\nfrom typing import Tuple\nx: Tuple[\"MyClass\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_06.py","code":"from __future__ import annotations\nfrom typing import Callable\nx: Callable[[\"MyClass\"], None]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[List within Callable]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_07.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nclass Foo(NamedTuple):\n x: \"MyClass\"\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Inherit from NamedTuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_08.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\", foo=\"int\", total=False)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict keyword syntax]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_09.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\", {\"foo\": \"int\"})\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict dict syntax]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_10.py","code":"from __future__ import annotations\nimport typing\nclass D(typing.TypedDict):\n E: typing.TypedDict(\"E\", {\"foo\": \"int\"})\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[typing.TypedDict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_11.py","code":"from __future__ import annotations\nfrom typing import Annotated\nx: Annotated[\"str\", \"metadata\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Annotated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_12.py","code":"from __future__ import annotations\nimport typing\nx: typing.Annotated[\"str\", \"metadata\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[typing.Annotated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_13.py","code":"from __future__ import annotations\nx: Arg(\"str\", \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Arg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_14.py","code":"from __future__ import annotations\nx: DefaultArg(\"str\", \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_15.py","code":"from __future__ import annotations\nx: NamedArg(\"str\", \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_16.py","code":"from __future__ import annotations\nx: DefaultNamedArg(\"str\", \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_17.py","code":"from __future__ import annotations\nx: DefaultNamedArg(\"str\", name=\"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with one keyword argument]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_18.py","code":"from __future__ import annotations\nx: DefaultNamedArg(name=\"name\", type=\"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with keyword arguments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_19.py","code":"from __future__ import annotations\nx: VarArg(\"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[VarArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_20.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[List[List[\"MyClass\"]]]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Nested]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_21.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", [(\"foo\", \"int\"), (\"bar\", \"str\")])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, no kwarg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_22.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", fields=[(\"foo\", \"int\"), (\"bar\", \"str\")])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, one kwarg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_23.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(typename=\"X\", fields=[(\"foo\", \"int\")])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, two kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_24.py","code":"from __future__ import annotations\ndef foo(var0, /, var1: \"MyClass\") -> \"MyClass\":\n x: \"MyClass\"\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[posonly args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_25.py","code":"from __future__ import annotations\nx: (\n \"int | \"\n \"str\"\n)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[multiline implicit-concat annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_26.py","code":"def f(x: \"X\") -> \"Y\": pass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fixes_in_py314","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_27.py","code":"from __future__ import annotations\ndef f[T: \"int\"](t: T) -> T:\n return t\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_typevar_bound","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_01.py","code":"from __future__ import annotations\ndef foo(var: MyClass) -> MyClass:\n x: MyClass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Simple annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_02.py","code":"from __future__ import annotations\nasync def foo(var: MyClass) -> MyClass:\n ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[simple async annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_03.py","code":"from __future__ import annotations\ndef foo(*, inplace: bool): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Kwonly, typed]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_04.py","code":"from __future__ import annotations\ndef foo(*args: str, **kwargs: int): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Vararg and kwarg typed]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_05.py","code":"from __future__ import annotations\nfrom typing import Tuple\nx: Tuple[MyClass]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_06.py","code":"from __future__ import annotations\nfrom typing import Callable\nx: Callable[[MyClass], None]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[List within Callable]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_07.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nclass Foo(NamedTuple):\n x: MyClass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Inherit from NamedTuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_08.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\", foo=int, total=False)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict keyword syntax]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_09.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\", {\"foo\": int})\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict dict syntax]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_10.py","code":"from __future__ import annotations\nimport typing\nclass D(typing.TypedDict):\n E: typing.TypedDict(\"E\", {\"foo\": int})\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[typing.TypedDict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_11.py","code":"from __future__ import annotations\nfrom typing import Annotated\nx: Annotated[str, \"metadata\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Annotated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_12.py","code":"from __future__ import annotations\nimport typing\nx: typing.Annotated[str, \"metadata\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[typing.Annotated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_13.py","code":"from __future__ import annotations\nx: Arg(str, \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Arg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_14.py","code":"from __future__ import annotations\nx: DefaultArg(str, \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_15.py","code":"from __future__ import annotations\nx: NamedArg(str, \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_16.py","code":"from __future__ import annotations\nx: DefaultNamedArg(str, \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_17.py","code":"from __future__ import annotations\nx: DefaultNamedArg(str, name=\"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with one keyword argument]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_18.py","code":"from __future__ import annotations\nx: DefaultNamedArg(name=\"name\", type=str)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with keyword arguments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_19.py","code":"from __future__ import annotations\nx: VarArg(str)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[VarArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_20.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[List[List[MyClass]]]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Nested]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_21.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", [(\"foo\", int), (\"bar\", str)])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, no kwarg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_22.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", fields=[(\"foo\", int), (\"bar\", str)])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, one kwarg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_23.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(typename=\"X\", fields=[(\"foo\", int)])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, two kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_24.py","code":"from __future__ import annotations\ndef foo(var0, /, var1: MyClass) -> MyClass:\n x: MyClass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[posonly args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_25.py","code":"from __future__ import annotations\nx: (\n int | str\n)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[multiline implicit-concat annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_26.py","code":"def f(x: X) -> Y: pass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fixes_in_py314","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_27.py","code":"from __future__ import annotations\ndef f[T: int](t: T) -> T:\n return t\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_typevar_bound","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_01.py","code":"from typing import Literal\nx: \"str\"\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[missing __future__ import]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_02.py","code":"from __future__ import annotations\nfrom typing import Literal\nx: Literal[\"foo\", \"bar\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_03.py","code":"from __future__ import annotations\nfrom typing import TypeVar\nx = TypeVar(\"x\", \"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[TypeVar]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_04.py","code":"from __future__ import annotations\nfrom typing import cast\nx = cast(x, \"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[cast]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_05.py","code":"from __future__ import annotations\nfrom typing import List\nX = List[\"MyClass\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Alias]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_06.py","code":"from __future__ import annotations\nX: MyCallable(\"X\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Custom callable]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_07.py","code":"from __future__ import annotations\ndef foo(x, *args, **kwargs): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Untyped]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_08.py","code":"from __future__ import annotations\ndef foo(*, inplace): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Kwonly, untyped]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_09.py","code":"from __future__ import annotations\nfrom typing import Annotated\nx: Annotated[1:2] = ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Annotated with invalid slice]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_10.py","code":"from __future__ import annotations\ndef f[X](x: X) -> X: return x\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[TypeVar without bound]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_11.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict no type (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_12.py","code":"from __future__ import annotations\nfrom typing import Annotated\nx: Annotated[()]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Empty Annotated (garbage)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_13.py","code":"from __future__ import annotations\nx: DefaultNamedArg(name=\"name\", quox=\"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with invalid arguments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_14.py","code":"from __future__ import annotations\nx: DefaultNamedArg(name=\"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with no type (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_15.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", [(\"foo\",), (\"bar\",)])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with length-1 tuples (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_16.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", [\"foo\", \"bar\"])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with missing types (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_17.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple()\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with no args (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_01.py","code":"open(\"foo\", encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop_before_315","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_02.py","code":"open(\"foo\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_03.py","code":"open(\"foo\", encoding=\"latin1\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"latin1\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_04.py","code":"open(\"foo\", encoding=\"us-ascii\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"us-ascii\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_05.py","code":"open(\"foo\", \"r\", \"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", \"r\", \"utf-8\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_06.py","code":"open(\"foo\", encoding=\"utf-8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[simple case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_07.py","code":"open(\"foo\", encoding=\"UTF8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[alternative spelling]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_08.py","code":"open(*args, encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_18.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"async def c(): return f'{await 1+foo()}'","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_18.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_01.py","code":"if s.startswith(\"foo\"):\n s = s[len(\"foo\"):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_02.py","code":"if s.startswith(S):\n s = s[len(S):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_03.py","code":"if s.endswith(\"foo\"):\n s = s[:-1 * len(\"foo\")]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_04.py","code":"if s.endswith(S):\n s = s[:-1 * len(S)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_05.py","code":"if s.startswith(x):\n s = s[len(x):] # TODO: removeprefix\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_06.py","code":"if True:\n if s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_07.py","code":"if True:\n something_else()\n if s.startswith(x):\n s = s[len(x):]\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_08.py","code":"if (\n x.startswith(y)\n):\n x = x[len(y):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_01.py","code":"s = s.removeprefix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_02.py","code":"s = s.removeprefix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_03.py","code":"s = s.removesuffix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_04.py","code":"s = s.removesuffix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_05.py","code":"s = s.removeprefix(x)\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_06.py","code":"if True:\n s = s.removeprefix(x)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_07.py","code":"if True:\n something_else()\n s = s.removeprefix(x)\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_08.py","code":"x = x.removeprefix(y)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_01.py","code":"if x.startswith(S):\n x = x[len(S):]\nelif x.endswith(T):\n x = x[:-1 * len(T)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop_before_39","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_02.py","code":"if s.startswith(\"a\"):\n s = s.lstrip(\"a\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[unrelated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_03.py","code":"if s.startswith(x):\n s = s[2:]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[cannot prove x is 2]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_04.py","code":"if s.startswith(x):\n s = s[len(x):]\nelse:\n print(\"no!)\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has else]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_05.py","code":"if something:\n print(\"something!\")\nelif s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has elif]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_01.py","code":"from __future__ import annotations\nfrom typing import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_02.py","code":"from __future__ import annotations\nfrom typing_extensions import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing_extensions.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_03.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_04.py","code":"from __future__ import annotations\nfrom collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_05.py","code":"from collections.abc import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_06.py","code":"from collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_01.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_02.py","code":"from __future__ import annotations\nfrom typing_extensions import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing_extensions.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_03.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_04.py","code":"from __future__ import annotations\nfrom collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_05.py","code":"from collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_06.py","code":"from collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"unchanged","file":"type-param-defaults/unchanged_01.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_noop[already converted!]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"unchanged","file":"type-param-defaults/unchanged_02.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int, int, None]: yield 1\ndef g() -> Generator[int, int, int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_noop[non-None send/return type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_01.py","code":"from typing import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_02.py","code":"import typing\nD = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": typing.Literal[\"b\", b\"c\"]})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_05.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {\n # first comment\n \"a\": int, # inline comment\n # second comment\n \"b\": str,\n # third comment\n}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_07.py","code":"from typing_extensions import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_08.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_09.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int}, total=True)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nFoo = TypedDict(\"Foo\", {\"lsts\": List[List[int]]})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_11.py","code":"import typing\nif True:\n if False:\n pass\n D = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_12.py","code":"from typing import TypedDict\nFoo = TypedDict(\"Foo\", {\"union\": str | int | None})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_01.py","code":"from typing import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_02.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_03.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_04.py","code":"import typing\nclass D(typing.TypedDict):\n a: typing.Literal['b', b'c']\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_05.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_06.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n # first comment\n a: int # inline comment\n # second comment\n b: str\n # third comment\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_07.py","code":"from typing_extensions import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_08.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_09.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict, total=True):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nclass Foo(TypedDict):\n lsts: List[List[int]]","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_11.py","code":"import typing\nif True:\n if False:\n pass\n class D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_12.py","code":"from typing import TypedDict\nclass Foo(TypedDict):\n union: str | int | None","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_01.py","code":"from wat import TypedDict\nQ = TypedDict(\"Q\")\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[from imported from elsewhere]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_02.py","code":"import typing\nD = typing.TypedDict(\"D\")","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {}, a=int)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[both]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_05.py","code":"import typing\nD = typing.TypedDict(\"D\", 1)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[not a dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {1: str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not a string]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_07.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a-b\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not an identifier]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_08.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"class\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is a keyword]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_09.py","code":"import typing\nD = typing.TypedDict(\"D\", {**d, \"a\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[dictionary splat operator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_10.py","code":"import typing\nC = typing.TypedDict(\"C\", *types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_11.py","code":"import typing\nD = typing.TypedDict(\"D\", **types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starstarkwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_12.py","code":"import typing\nD = typing.TypedDict(\"D\", x=int, total=False)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[kw_typed_dict with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_01.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_02.py","code":"import typing\nx: typing.Union[int]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_03.py","code":"import typing\nx: typing.Union[Foo[str, int], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_04.py","code":"import typing\nx: typing.Union[typing.List[str], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_05.py","code":"import typing\nx: typing.Union[int, str,]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_06.py","code":"import typing\nx: typing.Union[(int, str)]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_07.py","code":"import typing\nx: typing.Union[\n int,\n str\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_08.py","code":"import typing\nx: typing.Union[\n int,\n str,\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_09.py","code":"from typing import Optional\nx: Optional[str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_10.py","code":"import typing\nx: typing.Optional[\n ComplicatedLongType[int]\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: Optional[\"str\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_12.py","code":"from typing import Union, Sequence\ndef f(x: Union[Union[A, B], Sequence[Union[C, D]]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_13.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_14.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_15.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_16.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> Union[int, str]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_01.py","code":"from typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_02.py","code":"x: int\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_03.py","code":"x: Foo[str, int] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_04.py","code":"x: list[str] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_05.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_06.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_07.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_08.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_09.py","code":"from typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_10.py","code":"x: None | (\n ComplicatedLongType[int]\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_12.py","code":"from typing import Union\nfrom collections.abc import Sequence\ndef f(x: A | B | Sequence[C | D]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_13.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x})\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_14.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x}(\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_15.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x}(\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_16.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x})\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: int | str) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> int | str: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_01.py","code":"from __future__ import annotations\nfrom typing import Union\nSomeAlias = Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[<3.9 not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_02.py","code":"from typing import Union\ndef f() -> Union[()]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ empty Union]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_03.py","code":"from typing import Optional\ndef f() -> Optional[\"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Optional of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_04.py","code":"from typing import Union\ndef f() -> Union[int, \"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Union of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_05.py","code":"from typing import Union\ndef f() -> Union[1:2]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[invalid Union slicing]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack[Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack [Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_03.py","code":"from typing import Unpack\ndef f(*args: Unpack[tuple[int, ...]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_03.py","code":"from typing import Unpack\ndef f(*args: *tuple[int, ...]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_01.py","code":"from typing import Unpack\nfoo(Unpack())","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_02.py","code":"from typing import TypeVarTuple, Unpack\nShape = TypeVarTuple(\"Shape\")\nclass Foo(Unpack[Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not inside a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_03.py","code":"from typing import Unpack\nfrom typing import TypedDict\nclass D(TypedDict):\n x: int\ndef f(**kwargs: Unpack[D]) -> None: pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[3.12 TypedDict for kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_01.py","code":"from contextvars import ContextVar\nfrom types import MappingProxyType\nimport re\nimport collections\nimport time\n\n# Okay\nContextVar(\"cv\")\nContextVar(\"cv\", default=())\nContextVar(\"cv\", default=(1, 2, 3))\nContextVar(\"cv\", default=\"foo\")\nContextVar(\"cv\", default=tuple())\nContextVar(\"cv\", default=frozenset())\nContextVar(\"cv\", default=MappingProxyType({}))\nContextVar(\"cv\", default=re.compile(\"foo\"))\nContextVar(\"cv\", default=float(1))\nContextVar(\"cv\", default=frozenset[str]())\nContextVar[frozenset[str]](\"cv\", default=frozenset[str]())\n\n# Bad\nContextVar(\"cv\", default=[])\nContextVar(\"cv\", default={})\nContextVar(\"cv\", default=list())\nContextVar(\"cv\", default=set())\nContextVar(\"cv\", default=dict())\nContextVar(\"cv\", default=[char for char in \"foo\"])\nContextVar(\"cv\", default={char for char in \"foo\"})\nContextVar(\"cv\", default={char: idx for idx, char in enumerate(\"foo\")})\nContextVar(\"cv\", default=collections.deque())\nContextVar(\"cv\", default=set[str]())\nContextVar[set[str]](\"cv\", default=set[str]())\n\ndef bar() -> list[int]:\n return [1, 2, 3]\n\nContextVar(\"cv\", default=bar())\nContextVar(\"cv\", default=time.time())\n\ndef baz(): ...\nContextVar(\"cv\", default=baz())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_02.py","code":"from contextvars import ContextVar\n\nfrom fastapi import Query\nContextVar(\"cv\", default=Query(None))\n\nfrom something_else import Depends\nContextVar(\"cv\", default=Depends())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039_extended.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_01.py","code":"import typing\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, Sequence\n\nKNOWINGLY_MUTABLE_DEFAULT = []\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = []\n immutable_annotation: typing.Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: typing.ClassVar[list[int]] = []\n\n\n@dataclass\nclass B:\n mutable_default: list[int] = []\n immutable_annotation: Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: ClassVar[list[int]] = []\n\n# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n@dataclass\nclass AWithQuotes:\n mutable_default: 'list[int]' = []\n immutable_annotation: 'typing.Sequence[int]' = []\n without_annotation = []\n correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: 'list[int]' = field(default_factory=list)\n class_variable: 'typing.ClassVar[list[int]]'= []\n\n\n# Mutable defaults wrapped in field() calls\n@dataclass\nclass C:\n mutable_default: list[int] = field(default=[]) # RUF008\n mutable_default2: dict[str, int] = field(default={}) # RUF008\n mutable_default3: set[int] = field(default=set()) # RUF008\n mutable_default4: dict[str, int] = field(default=dict()) # RUF008\n correct_factory: list[int] = field(default_factory=list) # okay\n immutable_default: tuple[int, ...] = field(default=()) # okay\n immutable_default2: str = field(default=\"hello\") # okay\n immutable_default3: int = field(default=1) # okay\n non_mutable_var: list[int] = field(default=KNOWINGLY_MUTABLE_DEFAULT) # okay\n class_variable: ClassVar[list[int]] = field(default=[]) # okay\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_02.py","code":"# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n\nfrom __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Example():\n \"\"\"Class that uses ClassVar.\"\"\"\n\n options: ClassVar[dict[str, str]] = {}\n\n\nif typing.TYPE_CHECKING:\n from typing import ClassVar\n\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_03.py","code":"import datetime\nimport re\nimport typing\nfrom dataclasses import dataclass, field\nfrom fractions import Fraction\nfrom pathlib import Path\nfrom typing import ClassVar, NamedTuple\n\n\ndef default_function() -> list[int]:\n return []\n\n\nclass ImmutableType(NamedTuple):\n something: int = 8\n\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\n fine_path: Path = Path()\n fine_date: datetime.date = datetime.date(2042, 1, 1)\n fine_timedelta: datetime.timedelta = datetime.timedelta(hours=7)\n fine_tuple: tuple[int] = tuple([1])\n fine_regex: re.Pattern = re.compile(r\".*\")\n fine_float: float = float(\"-inf\")\n fine_int: int = int(12)\n fine_complex: complex = complex(1, 2)\n fine_str: str = str(\"foo\")\n fine_bool: bool = bool(\"foo\")\n fine_fraction: Fraction = Fraction(1, 2)\n\n\nDEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES = ImmutableType(40)\nDEFAULT_A_FOR_ALL_DATACLASSES = A([1, 2, 3])\n\n\n@dataclass\nclass B:\n hidden_mutable_default: list[int] = default_function()\n another_dataclass: A = A()\n not_optimal: ImmutableType = ImmutableType(20)\n good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES\n okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES\n\n fine_dataclass_function: list[int] = field(default_factory=list)\n\n\nclass IntConversionDescriptor:\n def __init__(self, *, default):\n self._default = default\n\n def __set_name__(self, owner, name):\n self._name = \"_\" + name\n\n def __get__(self, obj, type):\n if obj is None:\n return self._default\n\n return getattr(obj, self._name, self._default)\n\n def __set__(self, obj, value):\n setattr(obj, self._name, int(value))\n\n\n@dataclass\nclass InventoryItem:\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\n\n\n# Regression tests for:\n# https://github.com/astral-sh/ruff/issues/6447\nfrom typing import NewType\n\nListOfStrings = NewType(\"ListOfStrs\", list[str])\nStringsToInts = NewType(\"IntsToStrings\", dict[str, int])\n\nSpecialString = NewType(name=\"SpecialString\", tp=str)\nNegativeInteger = NewType(\"NegInt\", tp=int)\n\nInvalid1 = NewType(*Foo)\nInvalid2 = NewType(\"Invalid2\", name=Foo)\nInvalid3 = NewType(\"Invalid3\", name=Foo, lorem=\"ipsum\")\n\n@dataclass\nclass DataclassWithNewTypeFields:\n # Errors\n a: ListOfStrings = ListOfStrings([])\n b: StringsToInts = StringsToInts()\n c: Invalid1 = Invalid1()\n d: Invalid2 = Invalid2()\n e: Invalid3 = Invalid3()\n\n # No errors\n e: SpecialString = SpecialString(\"Lorem ipsum\")\n f: NegativeInteger = NegativeInteger(-110)\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/15772\ndef f() -> int:\n return 0\n\n@dataclass\nclass ShouldMatchB008RuleOfImmutableTypeAnnotationIgnored:\n this_is_not_fine: list[int] = default_function()\n # ignored\n this_is_fine: int = f()\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/17424\n@dataclass(frozen=True)\nclass C:\n foo: int = 1\n\n\n@dataclass\nclass D:\n c: C = C()\n\n\n@dataclass\nclass E:\n c: C = C()\n\n# https://github.com/astral-sh/ruff/issues/20266\n@dataclass(frozen=True)\nclass C:\n @dataclass(frozen=True)\n class D:\n foo: int = 1\n\n d: D = D() # OK","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_04.py","code":"from dataclasses import dataclass \nfrom typing import TYPE_CHECKING\n\n\ndef default_function() ->list[int]:\n return []\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\nif TYPE_CHECKING:\n from typing import ClassVar\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_05.py","code":"from dataclasses import InitVar, KW_ONLY, MISSING, dataclass, field\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n # Errors\n no_annotation = r\"foo\"\n missing = MISSING\n field = field()\n\n # No errors\n __slots__ = (\"foo\", \"bar\")\n __radd__ = __add__\n _private_attr = 100\n\n with_annotation: str\n with_annotation_and_default: int = 42\n with_annotation_and_field_specifier: bytes = field()\n\n class_var_no_arguments: ClassVar = 42\n class_var_with_arguments: ClassVar[int] = 42\n\n init_var_no_arguments: InitVar = \"lorem\"\n init_var_with_arguments: InitVar[str] = \"ipsum\"\n\n kw_only: KW_ONLY\n tu, ple, [unp, ack, ing] = (0, 1, 2, [3, 4, 5])\n mul, [ti, ple] = (a, ssign), ment = {1: b\"3\", \"2\": 4}, [6j, 5]\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_06.py","code":"from dataclasses import dataclass\nfrom enum import Enum, Flag, IntEnum, IntFlag, StrEnum, ReprEnum\n\nimport attr\nimport attrs\n\n\n## Errors\n\n@dataclass\nclass E(Enum): ...\n\n\n@dataclass # Foobar\nclass E(Flag): ...\n\n\n@dataclass()\nclass E(IntEnum): ...\n\n\n@dataclass() # Foobar\nclass E(IntFlag): ...\n\n\n@dataclass(\n frozen=True\n)\nclass E(StrEnum): ...\n\n\n@dataclass( # Foobar\n frozen=True\n)\nclass E(ReprEnum): ...\n\n\n@dataclass(\n frozen=True\n) # Foobar\nclass E(Enum): ...\n\n\n## No errors\n\n@attrs.define\nclass E(Enum): ...\n\n\n@attrs.frozen\nclass E(Enum): ...\n\n\n@attrs.mutable\nclass E(Enum): ...\n\n\n@attr.s\nclass E(Enum): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"except-without-parens","pep":"758","introduced_in":"3.14","form":"modern","file":"except-without-parens/modern_01.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntry:\n pass\nexcept x, y:\n pass\ntry:\n pass\nexcept* x, y:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/except_stmt_unparenthesized_tuple_no_as_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"except-without-parens","pep":"758","introduced_in":"3.14","form":"modern","file":"except-without-parens/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ntry:\n pass\nexcept x, y:\n pass\ntry:\n pass\nexcept* x, y:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/except_stmt_unparenthesized_tuple_no_as_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_01.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ntry: ...\nexcept* ValueError: ...\nexcept* KeyError: ...\nexcept * Error: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/except_star_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_02.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntry:\n pass\nexcept x, y:\n pass\ntry:\n pass\nexcept* x, y:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/except_stmt_unparenthesized_tuple_no_as_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_03.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ntry: ...\nexcept* ValueError: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/except_star_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_04.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ntry:\n pass\nexcept x, y:\n pass\ntry:\n pass\nexcept* x, y:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/except_stmt_unparenthesized_tuple_no_as_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_01.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf'Magic wand: { bag['wand'] }' # nested quotes\nf\"{'\\n'.join(a)}\" # escape sequence\nf'''A complex trick: {\n bag['bag'] # comment\n}'''\nf\"{f\"{f\"{f\"{f\"{f\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nf\"{f'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nf\"{\n 1\n}\"\nf\"test {a \\\n } more\" # line continuation\nf\"\"\"{f\"\"\"{x}\"\"\"}\"\"\" # mark the whole triple quote\nf\"{'\\n'.join(['\\t', '\\v', '\\r'])}\" # multiple escape sequences, multiple errors\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/pep701_f_string_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\n# nested interpolations also need to be checked\nf'{1: abcd \"{'aa'}\" }'\nf'{1: abcd \"{\"\\n\"}\" }'\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/pep701_nested_interpolation_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_03.py","code":"# parse_options: {\"target-version\": \"3.12\"}\nf'Magic wand: { bag['wand'] }' # nested quotes\nf\"{'\\n'.join(a)}\" # escape sequence\nf'''A complex trick: {\n bag['bag'] # comment\n}'''\nf\"{f\"{f\"{f\"{f\"{f\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nf\"{f'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nf\"{\n 1\n}\"\nf\"test {a \\\n } more\" # line continuation\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep701_f_string_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_04.py","code":"# Empty f-strings\nf\"\"\nF\"\"\nf''\nf\"\"\"\"\"\"\nf''''''\n\nf\"{\" f\"}\"\nf\"{foo!s}\"\nf\"{3,}\"\nf\"{3!=4:}\"\nf'{3:{\"}\"}>10}'\nf'{3:{\"{\"}>10}'\nf\"{ foo = }\"\nf\"{ foo = :.3f }\"\nf\"{ foo = !s }\"\nf\"{ 1, 2 = }\"\nf'{f\"{3.1415=:.1f}\":*^20}'\n\n{\"foo \" f\"bar {x + y} \" \"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nf\"\\{foo}\\{bar:\\}\"\nf\"\\\\{{foo\\\\}}\"\nf\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nf\"{ ( foo ) = }\"\n\nf\"normal {foo} {{another}} {bar} {{{three}}}\"\nf\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nf\"normal {x:y + 2}\"\nf\"{x:{{1}.pop()}}\"\nf\"{(lambda x:{x})}\"\nf\"{x =}\"\nf\"{ x = }\"\nf\"{x=!a}\"\nf\"{x:.3f!r =}\"\nf\"{x = !r :.3f}\"\nf\"{x:.3f=!r}\"\n\"hello\" f\"{x}\"\nf\"{x}\" f\"{y}\"\nf\"{x}\" \"world\"\nf\"Invalid args in command: {command, *args}\"\n\"foo\" f\"{x}\" \"bar\"\n(\n f\"a\"\n F\"b\"\n \"c\"\n rf\"d\"\n fr\"e\"\n)\n\n# With unicode strings\nu\"foo\" f\"{bar}\" \"baz\" \" some\"\n\"foo\" f\"{bar}\" u\"baz\" \" some\"\n\"foo\" f\"{bar}\" \"baz\" u\" some\"\nu\"foo\" f\"bar {baz} really\" u\"bar\" \"no\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/f_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_01.py","code":"f\"hello {x:} world\"\nf\"hello {x:.3f} world\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/fstring_format_spec_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf\"{1:''}\" # but this is okay on all versions\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_nested_quote_in_format_spec_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_03.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf\"outer {'# not a comment'}\"\nf'outer {x:{\"# not a comment\"} }'\nf\"\"\"{f'''{f'{\"# not a comment\"}'}'''}\"\"\"\nf\"\"\"{f'''# before expression {f'# aro{f\"#{1+1}#\"}und #'}'''} # after expression\"\"\"\nf\"\"\"{\n 1\n}\"\"\"\nf\"escape outside of \\t {expr}\\n\"\nf\"test\\\"abcd\"\nf\"{1:\\x64}\" # escapes are valid in the format spec\nf\"{1:\\\"d\\\"}\" # this also means that escaped outer quotes are valid\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep701_f_string_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_01.py","code":"import typing\nimport typing_extensions\nfrom typing import Literal\n\n# Shouldn't affect non-union field types.\nfield1: Literal[1] # OK\n\n# Should emit for duplicate field types.\nfield2: Literal[1] | Literal[2] # Error\n\n# Should emit for union types in arguments.\ndef func1(arg1: Literal[1] | Literal[2]): # Error\n print(arg1)\n\n\n# Should emit for unions in return types.\ndef func2() -> Literal[1] | Literal[2]: # Error\n return \"my Literal[1]ing\"\n\n\n# Should emit in longer unions, even if not directly adjacent.\nfield3: Literal[1] | Literal[2] | str # Error\nfield4: str | Literal[1] | Literal[2] # Error\nfield5: Literal[1] | str | Literal[2] # Error\nfield6: Literal[1] | bool | Literal[2] | str # Error\n\n# Should emit for non-type unions.\nfield7 = Literal[1] | Literal[2] # Error\n\n# Should emit for parenthesized unions.\nfield8: Literal[1] | (Literal[2] | str) # Error\n\n# Should handle user parentheses when fixing.\nfield9: Literal[1] | (Literal[2] | str) # Error\nfield10: (Literal[1] | str) | Literal[2] # Error\n\n# Should emit for union in generic parent type.\nfield11: dict[Literal[1] | Literal[2], str] # Error\n\n# Should emit for unions with more than two cases\nfield12: Literal[1] | Literal[2] | Literal[3] # Error\nfield13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error\n\n# Should emit for unions with more than two cases, even if not directly adjacent\nfield14: Literal[1] | Literal[2] | str | Literal[3] # Error\n\n# Should emit for unions with mixed literal internal types\nfield15: Literal[1] | Literal[\"foo\"] | Literal[True] # Error\n\n# Shouldn't emit for duplicate field types with same value; covered by Y016\nfield16: Literal[1] | Literal[1] # OK\n\n# Shouldn't emit if in new parent type\nfield17: Literal[1] | dict[Literal[2], str] # OK\n\n# Shouldn't emit if not in a union parent\nfield18: dict[Literal[1], Literal[2]] # OK\n\n# Should respect name of literal type used\nfield19: typing.Literal[1] | typing.Literal[2] # Error\n\n# Should emit in cases with newlines\nfield20: typing.Union[\n Literal[\n 1 # test\n ],\n Literal[2],\n] # Error, newline and comment will not be emitted in message\n\n# Should handle multiple unions with multiple members\nfield21: Literal[1, 2] | Literal[3, 4] # Error\n\n# Should emit in cases with `typing.Union` instead of `|`\nfield22: typing.Union[Literal[1], Literal[2]] # Error\n\n# Should emit in cases with `typing_extensions.Literal`\nfield23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error\n\n# Should emit in cases with nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error\n\n# Should emit in cases with mixed `typing.Union` and `|`\nfield25: typing.Union[Literal[1], Literal[2] | str] # Error\n\n# Should emit only once in cases with multiple nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error\n\n# Should use the first literal subscript attribute when fixing\nfield25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error\n\nfrom typing import IO, Literal\n\nInlineOption = Literal[\"a\"] | Literal[\"b\"] | IO[str]\n\n# Should use unsafe fix when comments are deleted\nfield26: (\n # First comment\n Literal[\"a\", \"b\"]\n # Second comment\n | Literal[\"c\", \"d\"]\n)\nfield27: (\n Literal[\"a\", \"b\"] # First comment\n | Literal[\"c\", \"d\"] # Second comment\n)\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI030.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_02.py","code":"import typing\nfrom typing import Literal, TypeAlias, Union\n\nA: str | Literal[\"foo\"]\nB: TypeAlias = typing.Union[Literal[b\"bar\", b\"foo\"], bytes, str]\nC: TypeAlias = typing.Union[Literal[5], int, typing.Union[Literal[\"foo\"], str]]\nD: TypeAlias = typing.Union[Literal[b\"str_bytes\", 42], bytes, int]\nE: TypeAlias = typing.Union[typing.Union[typing.Union[typing.Union[Literal[\"foo\"], str]]]]\nF: TypeAlias = typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\nG: typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\n\ndef func(x: complex | Literal[1J], y: Union[Literal[3.14], float]): ...\n\n# OK\nA: Literal[\"foo\"]\nB: TypeAlias = Literal[b\"bar\", b\"foo\"]\nC: TypeAlias = typing.Union[Literal[5], Literal[\"foo\"]]\nD: TypeAlias = Literal[b\"str_bytes\", 42]\n\ndef func(x: Literal[1J], y: Literal[3.14]): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI051.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_03.py","code":"from typing import Literal\nimport typing as t\nimport typing_extensions\n\nx: Literal[True, False, True, False] # PYI062 twice here\n\ny: Literal[1, print(\"hello\"), 3, Literal[4, 1]] # PYI062 on the last 1\n\nz: Literal[{1, 3, 5}, \"foobar\", {1,3,5}] # PYI062 on the set literal\n\nLiteral[1, Literal[1]] # once\nLiteral[1, 2, Literal[1, 2]] # twice\nLiteral[1, Literal[1], Literal[1]] # twice\nLiteral[1, Literal[2], Literal[2]] # once\nt.Literal[1, t.Literal[2, t.Literal[1]]] # once\ntyping_extensions.Literal[1, 1, 1] # twice\nLiteral[\n 1, # comment\n Literal[ # another comment\n 1\n ]\n] # once\n\n# Ensure issue is only raised once, even on nested literals\nMyType = Literal[\"foo\", Literal[True, False, True], \"bar\"] # PYI062\n\nn: Literal[\"No\", \"duplicates\", \"here\", 1, \"1\"]\n\n\n# nested literals, all equivalent to `Literal[1]`\nLiteral[Literal[1]] # no duplicate\nLiteral[Literal[Literal[1], Literal[1]]] # once\nLiteral[Literal[1], Literal[Literal[Literal[1]]]] # once\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI062.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_01.py","code":"# parse_options: { \"target-version\": \"3.9\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/match_before_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_02.py","code":"match 2:\n case Class(x=x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_keyword_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_03.py","code":"match x:\n case [a] | [a]: ...\n case (x, y) | (x, y): ...\n case (x, (y | y)): ...\n case [a, _] | [a, _]: ...\n case [a] | [C(a)]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/different_match_pattern_bindings.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_04.py","code":"match x:\n case {x.a: 1, x.a: 2}: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/duplicate_match_key_attr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_05.py","code":"match x:\n case 2: ...\n case var: ...\nmatch x:\n case 2: ...\n case _: ...\nmatch x:\n case var if True: ... # don't try to refute a guarded pattern\n case 2: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/irrefutable_case_pattern_at_end.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_06.py","code":"# parse_options: { \"target-version\": \"3.10\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_after_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_07.py","code":"match foo:\n case foo_bar: ...\nmatch foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_08.py","code":"match foo:\n case case: ...\nmatch foo:\n case match: ...\nmatch foo:\n case type: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_09.py","code":"match foo:\n case match.bar: ...\n case case.bar: ...\n case type.bar: ...\n case match.case.type.bar.type.case.match: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_attr_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_10.py","code":"match foo:\n case _: ...\nmatch 1:\n case _: ...\nmatch 1.0:\n case _: ...\nmatch 1j:\n case _: ...\nmatch \"foo\":\n case _: ...\nmatch f\"foo {x}\":\n case _: ...\nmatch {1, 2}:\n case _: ...\nmatch ~foo:\n case _: ...\nmatch ...:\n case _: ...\nmatch not foo:\n case _: ...\nmatch await foo():\n case _: ...\nmatch lambda foo: foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_11.py","code":"match match:\n case _: ...\nmatch case:\n case _: ...\nmatch type:\n case _: ...\nmatch None:\n case _: ...\nmatch True:\n case _: ...\nmatch False:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_12.py","code":"match (1, 2) # Identifier\nmatch (1, 2): # Keyword\n case _: ...\nmatch [1:] # Identifier\nmatch [1, 2]: # Keyword\n case _: ...\nmatch * foo # Identifier\nmatch - foo # Identifier\nmatch -foo: # Keyword\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_or_identifier.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_13.py","code":"match subject:\n case [a, b]: ...\n case (a, b): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_parentheses_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_14.py","code":"match subject:\n case a if x: ...\n case a, b: ...\n case a, b if x: ...\n case a: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_15.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_16.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_17.py","code":"match 2:\n case Class(x) | [x] | x: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/multiple_assignment_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_18.py","code":"match ruff:\n case {\"lint\": {\"select\": x} | {\"extend-select\": x}} | {\"select\": x}:\n ...\nmatch 42:\n case [[x] | [x]] | x: ...\nmatch 42:\n case [[x | x] | [x]] | x: ...\nmatch 42:\n case ast.Subscript(n, ast.Constant() | ast.Slice()) | ast.Attribute(n): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/nested_alternative_patterns.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_19.py","code":"# Empty f-strings\nf\"\"\nF\"\"\nf''\nf\"\"\"\"\"\"\nf''''''\n\nf\"{\" f\"}\"\nf\"{foo!s}\"\nf\"{3,}\"\nf\"{3!=4:}\"\nf'{3:{\"}\"}>10}'\nf'{3:{\"{\"}>10}'\nf\"{ foo = }\"\nf\"{ foo = :.3f }\"\nf\"{ foo = !s }\"\nf\"{ 1, 2 = }\"\nf'{f\"{3.1415=:.1f}\":*^20}'\n\n{\"foo \" f\"bar {x + y} \" \"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nf\"\\{foo}\\{bar:\\}\"\nf\"\\\\{{foo\\\\}}\"\nf\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nf\"{ ( foo ) = }\"\n\nf\"normal {foo} {{another}} {bar} {{{three}}}\"\nf\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nf\"normal {x:y + 2}\"\nf\"{x:{{1}.pop()}}\"\nf\"{(lambda x:{x})}\"\nf\"{x =}\"\nf\"{ x = }\"\nf\"{x=!a}\"\nf\"{x:.3f!r =}\"\nf\"{x = !r :.3f}\"\nf\"{x:.3f=!r}\"\n\"hello\" f\"{x}\"\nf\"{x}\" f\"{y}\"\nf\"{x}\" \"world\"\nf\"Invalid args in command: {command, *args}\"\n\"foo\" f\"{x}\" \"bar\"\n(\n f\"a\"\n F\"b\"\n \"c\"\n rf\"d\"\n fr\"e\"\n)\n\n# With unicode strings\nu\"foo\" f\"{bar}\" \"baz\" \" some\"\n\"foo\" f\"{bar}\" u\"baz\" \" some\"\n\"foo\" f\"{bar}\" \"baz\" u\" some\"\nu\"foo\" f\"bar {baz} really\" u\"bar\" \"no\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/f_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_20.py","code":"# Empty t-strings\nt\"\"\nt\"\"\nt''\nt\"\"\"\"\"\"\nt''''''\n\nt\"{\" t\"}\"\nt\"{foo!s}\"\nt\"{3,}\"\nt\"{3!=4:}\"\nt'{3:{\"}\"}>10}'\nt'{3:{\"{\"}>10}'\nt\"{ foo = }\"\nt\"{ foo = :.3f }\"\nt\"{ foo = !s }\"\nt\"{ 1, 2 = }\"\nt'{t\"{3.1415=:.1f}\":*^20}'\n\n{t\"foo \" t\"bar {x + y} \" t\"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nt\"\\{foo}\\{bar:\\}\"\nt\"\\\\{{foo\\\\}}\"\nt\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nt\"{ ( foo ) = }\"\n\nt\"normal {foo} {{another}} {bar} {{{three}}}\"\nt\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nt\"normal {x:y + 2}\"\nt\"{x:{{1}.pop()}}\"\nt\"{(lambda x:{x})}\"\nt\"{x =}\"\nt\"{ x = }\"\nt\"{x=!a}\"\nt\"{x:.3f!r =}\"\nt\"{x = !r :.3f}\"\nt\"{x:.3f=!r}\"\nt\"hello\" t\"{x}\"\nt\"{x}\" t\"{y}\"\nt\"{x}\" t\"world\"\nt\"Invalid args in command: {command, *args}\"\nt\"foo\" t\"{x}\" t\"bar\"\n(\n t\"a\"\n t\"b\"\n t\"c\"\n rt\"d\"\n tr\"e\"\n)\n\n# Nesting\nt\"{f\"{t\"{this}\"}\"}\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/t_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_21.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_01.py","code":"match[0]: int\nmatch [x, y, z]: dict\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_annotated_assignment.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_02.py","code":"match not in case\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_03.py","code":"match\nmatch != foo\n(foo, match)\n[foo, match]\n{foo, match}\nmatch;\nmatch: int\nmatch,\nmatch.foo\nmatch / foo\nmatch << foo\nmatch and foo\nmatch is not foo\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_04.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_01.py","code":"# parse_options: {\"target-version\": \"3.8\"}\ndef foo(a, /): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pos_only_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_02.py","code":"lambda: a\nlambda: 1\nlambda x: 1\nlambda x, y: ...\nlambda a, b, c: 1\nlambda a, b=20, c=30: 1\nlambda x, y: x * y\nlambda y, z=1: z * y\nlambda *a: a\nlambda *a, z, x=0: ...\nlambda *, a, b, c: 1\nlambda *, a, b=20, c=30: 1\nlambda a, b, c, *, d, e: 0\nlambda **kwargs: f()\nlambda *args, **kwargs: f() + 1\nlambda *args, a, b=1, **kwargs: f() + 1\nlambda a, /: ...\nlambda a, /, b: ...\nlambda a=1, /,: ...\nlambda a, b, /, *, c: ...\nlambda kw=1, *, a: ...\nlambda a, b=20, /, c=30: 1\nlambda a, b, /, c, *, d, e: 0\nlambda a, b, /, c, *d, e, **f: 0","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/lambda.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_03.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"template-strings","pep":"750","introduced_in":"3.14","form":"modern","file":"template-strings/modern_01.py","code":"# parse_options: {\"target-version\": \"3.13\"}\nt\"{hey}\"\nt'{there}'\nt\"\"\"what's\nhappening?\"\"\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/template_strings_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"template-strings","pep":"750","introduced_in":"3.14","form":"modern","file":"template-strings/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\nt'Magic wand: { bag['wand'] }' # nested quotes\nt\"{'\\n'.join(a)}\" # escape sequence\nt'''A complex trick: {\n bag['bag'] # comment\n}'''\nt\"{t\"{t\"{t\"{t\"{t\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nt\"{t'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nt\"test {a \\\n } more\" # line continuation\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep750_t_string_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"template-strings","pep":"750","introduced_in":"3.14","form":"modern","file":"template-strings/modern_03.py","code":"# parse_options: {\"target-version\": \"3.14\"}\nt\"{hey}\"\nt'{there}'\nt\"\"\"what's\nhappening?\"\"\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/template_strings_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"template-strings","pep":"750","introduced_in":"3.14","form":"modern","file":"template-strings/modern_04.py","code":"# Empty t-strings\nt\"\"\nt\"\"\nt''\nt\"\"\"\"\"\"\nt''''''\n\nt\"{\" t\"}\"\nt\"{foo!s}\"\nt\"{3,}\"\nt\"{3!=4:}\"\nt'{3:{\"}\"}>10}'\nt'{3:{\"{\"}>10}'\nt\"{ foo = }\"\nt\"{ foo = :.3f }\"\nt\"{ foo = !s }\"\nt\"{ 1, 2 = }\"\nt'{t\"{3.1415=:.1f}\":*^20}'\n\n{t\"foo \" t\"bar {x + y} \" t\"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nt\"\\{foo}\\{bar:\\}\"\nt\"\\\\{{foo\\\\}}\"\nt\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nt\"{ ( foo ) = }\"\n\nt\"normal {foo} {{another}} {bar} {{{three}}}\"\nt\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nt\"normal {x:y + 2}\"\nt\"{x:{{1}.pop()}}\"\nt\"{(lambda x:{x})}\"\nt\"{x =}\"\nt\"{ x = }\"\nt\"{x=!a}\"\nt\"{x:.3f!r =}\"\nt\"{x = !r :.3f}\"\nt\"{x:.3f=!r}\"\nt\"hello\" t\"{x}\"\nt\"{x}\" t\"{y}\"\nt\"{x}\" t\"world\"\nt\"Invalid args in command: {command, *args}\"\nt\"foo\" t\"{x}\" t\"bar\"\n(\n t\"a\"\n t\"b\"\n t\"c\"\n rt\"d\"\n tr\"e\"\n)\n\n# Nesting\nt\"{f\"{t\"{this}\"}\"}\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/t_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_07.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\nclass D[S, T = int, U = uint](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_param_default_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_08.py","code":"type Alias[T] = list[T]\ndef f[T](t: T): ...\nclass C[T]: ...\nclass C[T, U, V]: ...\ntype Alias[T, U: str, V: (str, bytes), *Ts, **P, D = default] = ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_duplicate_type_parameter_names.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_09.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_default_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_10.py","code":"type X[**P] = int\ntype X[**P = int] = int\ntype X[T, **P] = int\ntype X[T, **P = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_param_spec.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_11.py","code":"type X[T] = int\ntype X[T = int] = int\ntype X[T: int = int] = int\ntype X[T: (int, int) = int] = int\ntype X[T: int = int, U: (int, int) = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_12.py","code":"type X[*Ts] = int\ntype X[*Ts = int] = int\ntype X[*Ts = *int] = int\ntype X[T, *Ts] = int\ntype X[T, *Ts = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var_tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_13.py","code":"class Test:\n ...\n\n\nclass Test():\n def __init__(self):\n pass\n\n\nclass Test(a=1, *A, **k):\n ...\n\n\nclass Test:\n def method():\n a, b = data\n\n\nclass Test(A, B):\n def __init__(self):\n pass\n\n def method_with_default(self, arg='default'):\n pass\n\n\n# Class with generic types:\n\n# TypeVar\nclass Test[T](): ...\n\n# TypeVar with default\nclass Test[T = str](): ...\n\n# TypeVar with bound\nclass Test[T: str](): ...\n\n# TypeVar with bound and default\nclass Test[T: int | str = int](): ...\n\n# TypeVar with tuple bound\nclass Test[T: (str, bytes)](): ...\n\n# Multiple TypeVar\nclass Test[T, U](): ...\n\n# Trailing comma\nclass Test[T, U,](): ...\n\n# TypeVarTuple\nclass Test[*Ts](): ...\n\n# TypeVarTuple with default\nclass Test[*Ts = Unpack[tuple[int, str]]](): ...\n\n# TypeVarTuple with starred default\nclass Test[*Ts = *tuple[int, str]](): ...\n\n# ParamSpec\nclass Test[**P](): ...\n\n# ParamSpec with default\nclass Test[**P = [int, str]](): ...\n\n# Mixed types\nclass Test[X, Y: str, *U, **P]():\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_14.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_01.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\nclass D[S, T = int, U = uint](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_param_default_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ntype x = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_stmt_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_03.py","code":"# parse_options: {\"target-version\": \"3.12\"}\nclass Foo[S: (str, bytes), T: float, *Ts, **P]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_type_params_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_04.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ndef foo[T](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/function_type_params_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_05.py","code":"type Alias[T] = list[T]\ndef f[T](t: T): ...\nclass C[T]: ...\nclass C[T, U, V]: ...\ntype Alias[T, U: str, V: (str, bytes), *Ts, **P, D = default] = ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_duplicate_type_parameter_names.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_06.py","code":"return; import a; from x import y; z; type T = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/simple_stmts_with_semicolons.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_07.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_default_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_08.py","code":"type X[**P] = int\ntype X[**P = int] = int\ntype X[T, **P] = int\ntype X[T, **P = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_param_spec.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_09.py","code":"type X[T] = int\ntype X[T = int] = int\ntype X[T: int = int] = int\ntype X[T: (int, int) = int] = int\ntype X[T: int = int, U: (int, int) = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_10.py","code":"type X[*Ts] = int\ntype X[*Ts = int] = int\ntype X[*Ts = *int] = int\ntype X[T, *Ts] = int\ntype X[T, *Ts = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var_tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_11.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype x = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_stmt_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_12.py","code":"class Test:\n ...\n\n\nclass Test():\n def __init__(self):\n pass\n\n\nclass Test(a=1, *A, **k):\n ...\n\n\nclass Test:\n def method():\n a, b = data\n\n\nclass Test(A, B):\n def __init__(self):\n pass\n\n def method_with_default(self, arg='default'):\n pass\n\n\n# Class with generic types:\n\n# TypeVar\nclass Test[T](): ...\n\n# TypeVar with default\nclass Test[T = str](): ...\n\n# TypeVar with bound\nclass Test[T: str](): ...\n\n# TypeVar with bound and default\nclass Test[T: int | str = int](): ...\n\n# TypeVar with tuple bound\nclass Test[T: (str, bytes)](): ...\n\n# Multiple TypeVar\nclass Test[T, U](): ...\n\n# Trailing comma\nclass Test[T, U,](): ...\n\n# TypeVarTuple\nclass Test[*Ts](): ...\n\n# TypeVarTuple with default\nclass Test[*Ts = Unpack[tuple[int, str]]](): ...\n\n# TypeVarTuple with starred default\nclass Test[*Ts = *tuple[int, str]](): ...\n\n# ParamSpec\nclass Test[**P](): ...\n\n# ParamSpec with default\nclass Test[**P = [int, str]](): ...\n\n# Mixed types\nclass Test[X, Y: str, *U, **P]():\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_13.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_14.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"unchanged","file":"type-param-syntax/unchanged_01.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/param_with_star_annotation_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_05.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_06.py","code":"def foo(*args: *int | str): ...\ndef foo(*args: *(int or str)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_07.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_08.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/star_index_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_09.py","code":"*a\n*(a + 1)\n*x.attr\n\narray_slice = array[0, *indexes, -1]\narray[0, *indexes, -1] = array_slice\narray[*indexes_to_select, *indexes_to_select]\narray[3:5, *indexes_to_select]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/starred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_10.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_11.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_12.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nout[(*(slice(None) for _ in range(2)), *ind)] = 1\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_01.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/decorator_named_expression_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_02.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_03.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_comp_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_04.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{x := 1, 2, 3}\n{1, x := 2, 3}\n{1, 2, x := 3}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_literal_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_05.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/walrus_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_06.py","code":"# parse_options: { \"target-version\": \"3.9\" }\n@buttons[0].clicked.connect\ndef spam(): ...\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/decorator_expression_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_07.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_08.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_09.py","code":"[a := 0 for x in range(0)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_rebound_comprehension_variable.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_10.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[(x:=1)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_11.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{(x := 1), 2, 3}\n{(last := x) for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_12.py","code":"# parse_options: {\"target-version\": \"3.9\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_index_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_13.py","code":"# parse_options: {\"target-version\": \"3.9\"}\n{x := 1, 2, 3}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_14.py","code":"class F(y := list): ...\ndef f():\n class G((yield 1)): ...\n class H((yield from 1)): ...\nasync def f():\n class G((await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_15.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_function_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_16.py","code":"# parse_options: {\"target-version\": \"3.13\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_17.py","code":"# parse_options: { \"target-version\": \"3.8\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/walrus_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_18.py","code":"# This only tests the call arguments and not the expression before the opening parenthesis.\n\n# Simple\ncall()\ncall(x, y)\ncall(x, y,) # Trailing comma\ncall(x=1, y=2)\ncall(*x)\ncall(**x)\n\n# Order\ncall(x, y=1)\ncall(x, *y)\ncall(x, **y)\ncall(x=1, *y)\ncall(x=1, **y)\ncall(*x, **y)\ncall(*x, y, z)\ncall(**x, y=1, z=2)\ncall(*x1, *x2, **y1, **y2)\ncall(x=1, **y, z=1)\n\n# Keyword expression\ncall(x=1 if True else 2)\ncall(x=await y)\ncall(x=lambda y: y)\ncall(x=(y := 1))\n\n# Yield expression\ncall((yield x))\ncall((yield from x))\n\n# Named expression\ncall(x := 1)\ncall(x := 1 for i in iter)\n\n# Starred expressions\ncall(*x and y)\ncall(*x | y)\ncall(*await x)\ncall(*lambda x: x)\ncall(*x if True else y)\n\n# Double starred\ncall(**x)\ncall(**x and y)\ncall(**await x)\ncall(**x if True else y)\ncall(**(yield x))\ncall(**lambda x: x)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/arguments.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_19.py","code":"# Simple\n{}\n{1: 2}\n{1: 2, a: 1, b: 'hello'}\n\n# Mixed indentations\n{\n}\n{\n 1:\n 2,\n 3\n :4\n}\n\n# Nested\n{{1: 2}: {3: {4: 5}}}\n\n# Lambda expressions\n{lambda x: x: 1}\n{'A': lambda p: None, 'B': C,}\n\n# Named expressions\n{(x := 1): y}\n{(x := 1): (y := 2)}\n\n# Double star unpacking\n{**d}\n{a: b, **d}\n{**a, **b}\n{\"a\": \"b\", **c, \"d\": \"e\"}\n{1: 2, **{'nested': 'dict'}}\n{x * 1: y ** 2, **call()}\n# Here, `not` isn't allowed but parentheses resets the precedence\n{**(not x)}\n\n# Random expressions\n{1: x if True else y}\n{x if True else y: y for x in range(10) for y in range(10)}\n{{1, 2}: 3, x: {1: 2,},}\n{(x): (y), (z): (a)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/dictionary.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_20.py","code":"(x for target in iter)\n(x async for target in iter)\n(x for target in iter if x in y if a and b if c)\n(x for target1 in iter1 if x and y for target2 in iter2 if a > b)\n(x for target1 in iter1 if x and y async for target2 in iter2 if a > b)\n\n# Named expression\n(x := y + 1 for y in z)\n\n# If expression\n(x if y else y for y in z)\n\n# Arguments\n\" \".join(\n sql\n for sql in (\n \"LIMIT %d\" % limit if limit else None,\n (\"OFFSET %d\" % offset) if offset else None,\n )\n)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/generator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_21.py","code":"# Simple lists\n[]\n[1]\n[1,]\n[1, 2, 3]\n[1, 2, 3,]\n\n# Mixed with indentations\n[\n]\n[\n 1\n]\n[\n 1,\n 2,\n]\n\n# Nested\n[[[1]]]\n[[1, 2], [3, 4]]\n\n# Named expression\n[x := 2]\n[x := 2,]\n[1, x := 2, 3]\n\n# Star expression\n[1, *x, 3]\n[1, *x | y, 3]\n\n# Random expressions\n[1 + 2, [1, 2, 3, 4], (a, b + c, d), {a, b, c}, {a: 1}, x := 2]\n[call1(call2(value.attr()) for element in iter)]\n[item in xs]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/list.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_22.py","code":"(name := 0)\n(name := (x * y))\n(name := 1 + 1)\n(name := (*x, y))\n(name := x if True else y)\n(name := lambda x: x)\n(name := (yield x))\n(name := (yield from x))","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/named.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_23.py","code":"(expr)\n(expr)()\n(expr)()()()\n\n(a and b or c)\n(lambda x: x)\n(x := 2)\n(yield x)\n(yield from x)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/parenthesized.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_24.py","code":"# Simple sets\n{}\n{1}\n{1,}\n{1, 2, 3}\n{1, 2, 3,}\n\n# Mixed with indentations\n{\n}\n{\n 1\n}\n{\n 1,\n 2,\n}\n\n# Nested\n{{1}}\n{{1, 2}, {3, 4}}\n\n# Named expression\n{x := 2}\n{1, x := 2, 3}\n{1, (x := 2),}\n\n# Star expression\n{1, *x, 3}\n{1, *x | y, 3}\n\n# Random expressions\n{1 + 2, (a, b), {1, 2, 3}, {a: b, **d}}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/set.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_25.py","code":"# Various combinations\nx[:]\nx[1:]\nx[:2]\nx[1:2]\nx[::]\nx[1::]\nx[:2:]\nx[1:2:]\nx[::3]\nx[1::3]\nx[:2:3]\nx[1:2:3]\n\n# Named expression\nx[y := 2]\nx[(y := 2):]\nx[y := 2,]\n\n# These are two separate slice elements\nx[1,:2,]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/slice.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_26.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_27.py","code":"# With parentheses\n()\n(())\n((()), ())\n(a,)\n(a, b)\n(a, b,)\n((a, b))\n\n# Without parentheses\na,\na, b\na, b,\n\n# Starred expression\n*a,\na, *b\n*a | b, *await x, (), *()\n(*a,)\n(a, *b)\n(*a | b, *await x, (), *())\n\n# Named expression\n(x := 1,)\n(x, y := 2)\n(x, y := 2, z)\nx, (y := 2), z\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_28.py","code":"# Simple\n-1\n+1\n~1\nnot x\n\n# Multiple\n---1\n-+~1\nnot-+~1\nnot not x\n\n# Precedence check\n- await 1\n+ await 1 ** -2\n~(1, 2)\n-1 + 2\n\n# Precedence check for `not` operator because it is higher than other unary operators\nnot a and b or not c | d and not e\nnot (x := 1)\nnot a | (not b)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/unary_op.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_29.py","code":"yield\nyield x\nyield x + 1\nyield x and y\nyield call()\nyield [1, 2]\nyield {3, 4}\nyield {x: 5}\nyield x, y\nyield (x, y)\nyield x == y\nyield (x := 1)\nyield x, *y\nyield *x,\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_30.py","code":"yield from x\nyield from x + 1\nyield from x and y\nyield from call()\nyield from [1, 2]\nyield from {3, 4}\nyield from {x: 5}\nyield from (x, y)\nyield from x == y\nyield from (x := 1)\nyield from (x, *x | y)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield_from.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_31.py","code":"@function_decorator\ndef test():\n pass\n\n\n@class_decorator\nclass Test:\n pass\n\n\n@decorator\ndef f(): ...\n\n\n@a.b.c\ndef f(): ...\n\n\n@a\n@a.b.c\ndef f(): ...\n\n\n@a\n@1 | 2\n@a.b.c\nclass T: ...\n\n\n@x := 1\n@x if True else y\n@lambda x: x\n@x and y\n@(yield x)\n@(*x, *y)\ndef f(): ...\n\n\n# This is not multiple decorators on the same line but rather a binary (`@`) expression\n@x @y\ndef foo(): ...\n\n\n@x\n\n\n@y\n\n\ndef foo(): ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/other/decorator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_32.py","code":"# These test cases specifically tests out parsing a list of with items that start with a\n# left parenthesis. This makes parsing ambiguous as to whether the left parenthesis is to\n# parenthesize the with items or part of a parenthesized expression. It's not to test the\n# with statement itself.\n\n# The following sections basically separates between which node does the\n# start parenthesis belongs to.\n\n# Parenthesized with items\n# ------------------------\n#\n# - The opening parenthesis belongs to the with statement.\n# - The range of the first with item shouldn't include the parenthesis.\nwith (item): ...\nwith (item,): ... # with a trailing comma\nwith (((item))): ...\nwith (item1, item2): ...\nwith (item1, item2,): ... # with a trailing comma\nwith ((item1), (item2), item3 as f, (item4)): ...\nwith ((item1, item2), item3): ...\nwith ((x, y) as f): ...\nwith (item1 as f1, item2 as f2): ...\nwith (item1 as f1, item2 as f2,): ... # with a trailing comma\nwith (item == 10,): ...\nwith ((item := 10)): ...\nwith ((item := 10,)): ...\nwith ((*item,)): ...\nwith ((item1 := 10), item2): ...\nwith (item1 as f, (item2 := 10)): ...\nwith (foo()): ...\nwith (foo(),): ...\nwith (foo() as f): ...\nwith (f\"{item := 42}\"): ...\nwith (f\"{(item := 42)}\"): ...\nwith ((x for x in range(10)), item): ...\nwith (item, (x for x in range(10))): ...\nwith (item, (x for x in range(10)), item): ...\nwith (data[1:2]): ...\nwith (data[1:2] as f): ...\nwith ((x for x in iter) as y): ...\n\n# Parenthesized expression\n# ------------------------\n#\n# - The opening parenthesis belongs to the context expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (item) as f: ...\nwith (item := 10): ...\nwith (item := 10) as f: ...\nwith ( item := 1 ): ...\nwith (item1 := 42), item2: ...\nwith (root + filename).read(): ... # Postfix expression\nwith (root + filename).read() as f: ... # Postfix expression\nwith (foo)(): ... # Postfix expression\nwith (foo)() as f: ... # Postfix expression\nwith (foo()) as f: ...\nwith (data[1:2]) as f: ...\nwith (1, 2, 3)[0]: ... # Postfix expression\nwith (1, 2, 3)[0] as f: ... # Postfix expression\nwith (item1), (item2): ...\nwith (open('a.py')), (open('b.py')): ...\nwith (yield x): ...\nwith ((yield x)): ...\nwith (yield from x): ...\nwith ((yield from x)): ...\nwith (yield x) as f: ...\nwith (yield x,) as f: ...\n\n\n# Tuple expression\n# ----------------\n#\n# - This is a sub-case of the parenthesized expression and requires transforming the list of\n# with items from the speculative parsing to a single with item containing a tuple expression.\n# - The opening parenthesis belongs to the tuple expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (): ...\nwith () as f: ...\nwith (item := 42,): ...\nwith (1, item := 2): ...\nwith (item1 := 10, item2): ...\nwith (item1, item2 := 2, item3) as f: ...\nwith (item,) as f: ...\nwith (*item,): ...\nwith (*item,) as f: ...\nwith (item1, item2) as f: ...\nwith (item1, item2,) as f: ...\nwith (item1, item2), item3: ...\nwith ((item1, item2), item3) as f: ...\nwith (item1,), item2, (item3, item4) as f: ...\nwith (item1, item2) as f1, item3 as f2: ...\nwith (item1, *item2): ...\nwith (item1, *item2) as f: ...\nwith (item1 := 10, *item2): ...\nwith ((item1 := 10), *item2): ...\n\n\n# Parenthesized generator expression\n# ----------------------------------\n#\n# - The opening parenthesis belongs to the generator expression\n# - The range of the with item should include the parenthesis\nwith (x for x in range(10)): ...\nwith (x async for x in range(10)): ...\nwith (x for x in range(10)), item: ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/ambiguous_lpar_with_items.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_33.py","code":"if 1: 10\nelif 2: 20\nelse: 30\n\nif True:\n 1\n ...\nif x < 1:\n ...\nelse:\n pass\n\nif a:\n pass\nelif b:\n ...\n\nif a and b:\n ...\nelif True:\n ...\nelif c:\n ...\nelif d:\n ...\nelse:\n f()\n\n# Valid test expression\nif a := b: ...\nelif a := b: ...\nif lambda x: x: ...\nelif lambda x: x: ...\nif await x: ...\nelif await x: ...\nif (yield x): ...\nelif (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/if.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_34.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_35.py","code":"return\nreturn x\nreturn *x, *y\nreturn (x := 1)\nreturn None\nreturn x and y\nreturn 1 < 2\nreturn 1, 2,\nreturn call()\nreturn attr.value()\nreturn await x\nreturn lambda x: y\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/return.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_36.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_37.py","code":"while x:\n ...\n\nwhile (x > 1) and y:\n pass\nelse:\n ...\n\nwhile x and y:\n ...\n print('Hello World!')\n\nelse:\n print('Olá, Mundo!')\n ...\n\nwhile a := b: ...\nwhile (a := b) and c: ...\nwhile lambda x: x: ...\nwhile await x: ...\n\nif True:\n while x:\n pass\n else:\n pass\nelse:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/while.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.14","idiom_id":"annotated","pep":"593","introduced_in":"3.9","form":"modern","file":"annotated/modern_01.py","code":"\"\"\"\nTests the typing.Annotated special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#annotated\n\n# > The first argument to Annotated must be a valid type\n\nfrom dataclasses import InitVar, dataclass\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Literal,\n NotRequired,\n Required,\n TypeAlias,\n TypeVar,\n TypedDict,\n Union,\n)\n\nT = TypeVar(\"T\")\n\n\nGood1: Annotated[Union[int, str], \"\"]\nGood2: Annotated[int | None, \"\"]\nGood3: Annotated[list[int], \"\"]\nGood4: Annotated[Any, \"\"]\nGood5: Annotated[tuple[int, ...] | list[int], \"\"]\nGood6: Annotated[Callable[..., int], \"\"]\nGood7: Annotated[\"int | str\", \"\"]\nGood8: Annotated[list[\"int | str\"], \"\"]\n\n\nBad1: Annotated[[int, str], \"\"] # E: invalid type expression\nBad2: Annotated[((int, str),), \"\"] # E: invalid type expression\nBad3: Annotated[[int for i in range(1)], \"\"] # E: invalid type expression\nBad4: Annotated[{\"a\": \"b\"}, \"\"] # E: invalid type expression\nBad5: Annotated[(lambda: int)(), \"\"] # E: invalid type expression\nBad6: Annotated[[int][0], \"\"] # E: invalid type expression\nBad7: Annotated[int if 1 < 3 else str, \"\"] # E: invalid type expression\nBad8: Annotated[var1, \"\"] # E: invalid type expression\nBad9: Annotated[True, \"\"] # E: invalid type expression\nBad10: Annotated[1, \"\"] # E: invalid type expression\nBad11: Annotated[list or set, \"\"] # E: invalid type expression\nBad12: Annotated[f\"{'int'}\", \"\"] # E: invalid type expression\n\n\n# > Multiple type annotations are supported (Annotated supports variadic arguments):\n\nMulti1: Annotated[int | str, 3, \"\"]\nMulti2: Annotated[int | str, 3, \"\", lambda x: x, max(1, 2)]\n\n# > Annotated must be called with at least two arguments ( Annotated[int] is not valid)\n\nBad13: Annotated[int] # E: requires at least two arguments\n\n\n# > Annotated types can be nested\n\nNested1: list[Annotated[dict[str, Annotated[str, \"\"]], \"\"]]\nNested2: Annotated[list[Annotated[dict[str, Annotated[Literal[1, 2, 3], \"\"]], \"\"]], \"\"]\n\n\n# > Annotated is not type compatible with type or type[T]\nSmallInt: TypeAlias = Annotated[int, \"\"]\n\nnot_type1: type[Any] = Annotated[int, \"\"] # E\nnot_type2: type[Any] = SmallInt # E\n\n\ndef func4(x: type[T]) -> T:\n return x()\n\n\nfunc4(Annotated[str, \"\"]) # E\nfunc4(SmallInt) # E\n\n\n# > An attempt to call Annotated (whether parameterized or not) should be\n# > treated as a type error by type checkers.\n\nAnnotated() # E\nAnnotated[int, \"\"]() # E\nSmallInt(1) # E\n\n\nclass ClassA:\n a: ClassVar[Annotated[int, \"\"]] = 1\n b: Annotated[ClassVar[int], \"\"] = 1\n c: Final[Annotated[int, \"\"]] = 1\n d: Annotated[Final[int], \"\"] = 1\n\n\n@dataclass\nclass ClassB:\n a: InitVar[Annotated[int, \"\"]]\n b: Annotated[InitVar[int], \"\"]\n\n\nclass ClassC(TypedDict):\n a: Annotated[Required[int], \"\"]\n b: Required[Annotated[int, \"\"]]\n c: Annotated[NotRequired[int], \"\"]\n d: NotRequired[Annotated[int, \"\"]]\n\n\nTA1: TypeAlias = Annotated[int | str, \"\"]\nTA2 = Annotated[Literal[1, 2], \"\"]\nTA3 = Annotated[T, \"\"]\n","source":"typing_tests","origin":"conformance/tests/qualifiers_annotated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_07.py","code":"\"\"\"\nTests the handling of builtins.type[T].\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#type\n\n\nfrom typing import Any, Callable, Generic, Type, TypeAlias, TypeVar, assert_type\n\n\nclass User:\n ...\n\n\nclass BasicUser(User):\n ...\n\n\nclass ProUser(User):\n ...\n\n\nclass TeamUser(User):\n ...\n\n\ndef func1(user_class: type) -> User:\n return user_class()\n\n\ndef func2(user_class: type[User]) -> User:\n return user_class()\n\n\nU = TypeVar(\"U\", bound=User)\n\n\ndef func3(user_class: type[U]) -> U:\n return user_class()\n\n\nassert_type(func1(TeamUser), User)\nassert_type(func2(TeamUser), User)\nassert_type(func3(TeamUser), TeamUser)\n\n\n# > Note that it is legal to use a union of classes as the parameter for type[].\n\n\ndef func4(user_class: type[BasicUser | ProUser]) -> User:\n return user_class()\n\n\nassert_type(func4(BasicUser), User)\nassert_type(func4(ProUser), User)\nfunc4(TeamUser) # E\n\n\n# > Any other special constructs like Callable are not allowed as an argument to type.\n\nT = TypeVar(\"T\")\n\n\ndef func5(x: type[T]) -> None:\n pass\n\n\nfunc5(User) # OK\nfunc5(tuple) # OK\nfunc5(Callable) # E\n\n\n# > When type is parameterized it requires exactly one parameter. Plain type\n# > without brackets, the root of Python’s metaclass hierarchy, is equivalent to type[Any].\n\nbad_type1: type[int, str] # E\n\n\nclass MyMetaA(type):\n ...\n\n\ndef func6(a: type, b: type[Any]):\n assert_type(a, type[Any])\n a = b # OK\n b = a # OK\n a = type # OK\n b = type # OK\n\n\n# > Regarding the behavior of type[Any] (or type), accessing attributes of a\n# > variable with this type only provides attributes and methods defined by\n# > type (for example, __repr__() and __mro__). Such a variable can be called\n# > with arbitrary arguments, and the return type is Any.\n\n\ndef func7(a: type, b: type[Any], c: Type, d: Type[Any]):\n assert_type(a.__mro__, tuple[type, ...])\n assert_type(a.unknown, Any)\n assert_type(a.unknown(), Any)\n\n assert_type(b.__mro__, tuple[type, ...])\n assert_type(b.unknown, Any)\n assert_type(b.unknown(), Any)\n\n assert_type(c.__mro__, tuple[type, ...])\n assert_type(c.unknown, Any)\n assert_type(c.unknown(), Any)\n\n assert_type(d.__mro__, tuple[type, ...])\n assert_type(d.unknown, Any)\n assert_type(d.unknown(), Any)\n\n\ndef func8(a: type[object], b: Type[object]):\n assert_type(a.__name__, str)\n a.unknown # E\n\n assert_type(b.__name__, str)\n b.unknown # E\n\n\n# > type is covariant in its parameter, because type[Derived] is a subtype of type[Base]:\n\n\ndef func9(pro_user_class: type[ProUser]):\n assert_type(func3(pro_user_class), ProUser)\n\n\nTA1: TypeAlias = Type\nTA2: TypeAlias = Type[Any]\nTA3: TypeAlias = type\nTA4: TypeAlias = type[Any]\n\n\ndef func10(a: TA1, b: TA2, c: TA3, d: TA4):\n assert_type(a, type[Any])\n assert_type(b, type[Any])\n assert_type(c, type[Any])\n assert_type(d, type[Any])\n\n\nTA1.unknown # E\nTA2.unknown # E\nTA3.unknown # E\nTA4.unknown # E\n\nTA7: TypeAlias = type[T]\nTA8: TypeAlias = Type[T]\n\n\ndef func11(t1: TA7[T]) -> T:\n return t1()\n\n\ndef func12(t1: TA8[T]) -> T:\n return t1()\n\n\nassert_type(func11(int), int)\nassert_type(func12(int), int)\n\n\ndef func13(v: type):\n x1: Callable[..., Any] = v # OK\n x2: Callable[[int, int], int] = v # OK\n x3: object = v # OK\n x4: type = v # OK\n x5: type[int] = v # OK\n x6: type[Any] = v # OK\n\n\nclass ClassA(Generic[T]):\n def method1(self, v: type) -> type[T]:\n return v # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_type.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_08.py","code":"\"\"\"\nTests the handling of builtins.tuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#tuple-type-form\n\n# > The type of a tuple can be expressed by listing the element types.\nfrom typing import Literal\n\n\nt1: tuple[int] = (1,) # OK\nt1 = (1, 2) # E\nt2: tuple[int, int] = (1, 2) # OK\nt2 = (1,) # E\nt2 = (1, \"\") # E\n\n\ndef func1() -> tuple[Literal[1], Literal[2]]:\n return (1, 2)\n\n\n# > The empty tuple can be typed as tuple[()].\n\nt10: tuple[()] = () # OK\nt10 = (1,) # E\n\n\ndef func2() -> list[tuple[()]]:\n return [(), (), ()]\n\n\n# > Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis.\nt20: tuple[int, ...] = () # OK\nt20 = (1,) # OK\nt20 = (1, 2, 3, 4) # OK\nt20 = (1, 2, 3, \"\") # E\n\n\nt30: tuple[int, ...] # OK\nt31: tuple[int, int, ...] # E\nt32: tuple[...] # E\nt33: tuple[..., int] # E\nt34: tuple[int, ..., int] # E\nt35: tuple[*tuple[str], ...] # E\nt36: tuple[*tuple[str, ...], ...] # E\n","source":"typing_tests","origin":"conformance/tests/tuples_type_form.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_01.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a base class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Generic, TypeVar, dataclass_transform\n\nT = TypeVar(\"T\")\n\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelBase:\n not_a_field: str\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n def __init__(self, not_a_field: str) -> None:\n self.not_a_field = not_a_field\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen dataclass cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass GenericModelBase(Generic[T]):\n not_a_field: T\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass GenericCustomer(GenericModelBase[int]):\n id: int = model_field()\n\n\ngc_1 = GenericCustomer(id=3)\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelBaseFrozen:\n not_a_field: str\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_02.py","code":"\"\"\"\nTests the dataclass_transform mechanism supports the \"converter\" parameter\nin a field specifier class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#converters\n\nfrom typing import (\n Any,\n Callable,\n TypeVar,\n dataclass_transform,\n overload,\n)\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n\ndef model_field(\n *,\n converter: Callable[[S], T],\n default: S | None = None,\n default_factory: Callable[[], S] | None = None,\n) -> T:\n raise NotImplementedError\n\n\n@dataclass_transform(field_specifiers=(model_field,))\nclass ModelBase:\n ...\n\n\n# > The converter must be a callable that must accept a single positional\n# > argument (but may accept other optional arguments, which are ignored for\n# > typing purposes).\n\n\ndef bad_converter1() -> int:\n return 0\n\n\ndef bad_converter2(*, x: int) -> int:\n return 0\n\n\nclass DC1(ModelBase):\n field1: int = model_field(converter=bad_converter1) # E\n field2: int = model_field(converter=bad_converter2) # E\n\n\n# > The type of the first positional parameter provides the type of the\n# > synthesized __init__ parameter for the field.\n\n# > The return type of the callable must be assignable to the field’s\n# > declared type.\n\n\ndef converter_simple(s: str) -> int:\n return int(s)\n\n\ndef converter_with_param_before_args(s: str, *args: int, **kwargs: int) -> int:\n return int(s)\n\n\ndef converter_with_args(*args: str) -> int:\n return int(args[0])\n\n\n@overload\ndef overloaded_converter(s: str) -> int:\n ...\n\n\n@overload\ndef overloaded_converter(s: list[str]) -> int:\n ...\n\n\ndef overloaded_converter(s: str | list[str], *args: str) -> int | str:\n return 0\n\n\nclass ConverterClass:\n @overload\n def __init__(self, val: str) -> None:\n ...\n\n @overload\n def __init__(self, val: bytes) -> None:\n ...\n\n def __init__(self, val: str | bytes) -> None:\n pass\n\n\nclass DC2(ModelBase):\n field0: int = model_field(converter=converter_simple)\n field1: int = model_field(converter=converter_with_param_before_args)\n field2: int = model_field(converter=converter_with_args)\n field3: ConverterClass = model_field(converter=ConverterClass)\n field4: int = model_field(converter=overloaded_converter)\n field5: dict[str, str] = model_field(converter=dict, default=())\n\n\nDC2(1, \"f1\", \"f2\", b\"f3\", []) # E\nDC2(\"f0\", \"f1\", \"f2\", 1, []) # E\nDC2(\"f0\", \"f1\", \"f2\", \"f3\", 3j) # E\n\n\ndc1 = DC2(\"f0\", \"f1\", \"f2\", b\"f6\", [])\n\ndc1.field0 = \"f1\"\ndc1.field3 = \"f6\"\ndc1.field3 = b\"f6\"\n\ndc1.field0 = 1 # E\ndc1.field3 = 1 # E\n\ndc2 = DC2(\"f0\", \"f1\", \"f2\", \"f6\", \"1\", ((\"a\", \"1\"), (\"b\", \"2\")))\n\n\n# > If default or default_factory are provided, the type of the default value\n# > should be assignable to the first positional parameter of the converter.\n\n\nclass DC3(ModelBase):\n field0: int = model_field(converter=converter_simple, default=\"\")\n field1: int = model_field(converter=converter_simple, default=1) # E\n\n field2: int = model_field(converter=converter_simple, default_factory=str)\n field3: int = model_field(converter=converter_simple, default_factory=int) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_converter.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_03.py","code":"\"\"\"\nTests the dataclass_transform mechanism honors implicit default values\nin field parameters.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#field-specifier-parameters\n\nfrom typing import Any, Callable, Literal, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n# > Field specifier functions can use overloads that implicitly specify the\n# > value of init using a literal bool value type (Literal[False] or Literal[True]).\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any],\n init: Literal[False] = False,\n) -> Any:\n ...\n\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: None = None,\n init: Literal[True] = True,\n) -> Any:\n ...\n\n\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any] | None = None,\n init: bool = True,\n) -> Any:\n ...\n\n\ndef field2(*, init: bool = False, kw_only: bool = True) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(kw_only_default=True, field_specifiers=(field1, field2))\ndef create_model(*, init: bool = True) -> Callable[[type[T]], type[T]]:\n raise NotImplementedError\n\n\n@create_model()\nclass CustomerModel1:\n id: int = field1(resolver=lambda: 0)\n name: str = field1(default=\"Voldemort\")\n\n\nCustomerModel1()\nCustomerModel1(name=\"hi\")\n\n# This should generate an error because \"id\" is not\n# supposed to be part of the init function.\nCustomerModel1(id=1, name=\"hi\") # E\n\n\n@create_model()\nclass CustomerModel2:\n id: int = field2()\n name: str = field2(init=True)\n\n\n# This should generate an error because kw_only is True\n# by default for field2.\nCustomerModel2(1) # E\n\nCustomerModel2(name=\"Fred\")\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_field.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_04.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a decorator function.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Callable, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n\n@overload\n@dataclass_transform(kw_only_default=True, order_default=True)\ndef create_model(cls: T) -> T:\n ...\n\n\n@overload\ndef create_model(\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n) -> Callable[[T], T]:\n ...\n\n\ndef create_model(*args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n\n@create_model(kw_only=False, order=False)\nclass Customer1:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2Subclass(Customer2):\n salary: float\n\n\nc1_1 = Customer1(id=3, name=\"Sue\")\nc1_1.id = 4\n\nc1_2 = Customer1(3, \"Sue\")\nc1_2.name = \"Susan\"\n\n# This should generate an error because of a type mismatch.\nc1_2.name = 3 # E\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\n# This should generate an error because salary is not\n# a defined field.\nc1_3 = Customer1(id=3, name=\"Sue\", salary=40000) # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_2 = Customer2(0, \"John\") # E\n\nv2 = c2_1 < c2_2\n\n\n@dataclass_transform(kw_only_default=True, order_default=True, frozen_default=True)\ndef create_model_frozen(cls: T) -> T:\n raise NotImplementedError\n\n\n@create_model_frozen\nclass Customer3:\n id: int\n name: str\n\n\n# This should generate an error because a non-frozen class\n# cannot inherit from a frozen class.\n@create_model # E[Customer3Subclass]\nclass Customer3Subclass(Customer3): # E[Customer3Subclass]\n age: int\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_func.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_05.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a metaclass.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\n\nfrom typing import Any, dataclass_transform\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelMeta(type):\n not_a_field: str\n\n def __init__(self, *args, **kwargs) -> None:\n self.not_a_field: str = \"not a field\"\n\n\nclass ModelBase(metaclass=ModelMeta):\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen class cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1, frozen=False): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\n# OK (other_name is optional).\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelMetaFrozen(type):\n pass\n\n\nclass ModelBaseFrozen(metaclass=ModelMetaFrozen):\n ...\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_meta.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_07.py","code":"\"\"\"\nTests the handling of descriptors within a dataclass.\n\"\"\"\n\n# This portion of the dataclass spec is under-specified in the documentation,\n# but its behavior can be determined from the runtime implementation.\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, TypeVar, assert_type, overload\n\nT = TypeVar(\"T\")\n\n\nclass Desc1:\n @overload\n def __get__(self, __obj: None, __owner: Any) -> \"Desc1\":\n ...\n\n @overload\n def __get__(self, __obj: object, __owner: Any) -> int:\n ...\n\n def __get__(self, __obj: object | None, __owner: Any) -> \"int | Desc1\":\n raise NotImplementedError\n\n def __set__(self, __obj: object, __value: int) -> None:\n ...\n\n\n@dataclass\nclass DC1:\n y: Desc1 = Desc1()\n\n\ndc1 = DC1(3)\n\nassert_type(dc1.y, int)\nassert_type(DC1.y, Desc1)\n\n\nclass Desc2(Generic[T]):\n @overload\n def __get__(self, instance: None, owner: Any) -> list[T]:\n ...\n\n @overload\n def __get__(self, instance: object, owner: Any) -> T:\n ...\n\n def __get__(self, instance: object | None, owner: Any) -> list[T] | T:\n raise NotImplementedError\n\n\n@dataclass\nclass DC2:\n x: Desc2[int]\n y: Desc2[str]\n z: Desc2[str] = Desc2()\n\n\nassert_type(DC2.x, list[int])\nassert_type(DC2.y, list[str])\nassert_type(DC2.z, list[str])\n\ndc2 = DC2(Desc2(), Desc2(), Desc2())\nassert_type(dc2.x, int)\nassert_type(dc2.y, str)\nassert_type(dc2.z, str)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_descriptors.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_08.py","code":"\"\"\"\nTests validation of frozen dataclass instances.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#frozen-instances\n\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass DC1:\n a: float\n b: str\n\ndc1 = DC1(1, \"\")\n\ndc1.a = 1 # E: dataclass is frozen\ndc1.b = \"\" # E: dataclass is frozen\n\n\n# This should generate an error because a non-frozen dataclass\n# cannot inherit from a frozen dataclass.\n@dataclass # E[DC2]\nclass DC2(DC1): # E[DC2]\n pass\n\n@dataclass\nclass DC3:\n a: int\n\n# This should generate an error because a frozen dataclass\n# cannot inherit from a non-frozen dataclass.\n@dataclass(frozen=True) # E[DC4]\nclass DC4(DC3): # E[DC4]\n pass\n\n\n@dataclass(frozen=True)\nclass DC1Child(DC1):\n # This should be allowed because attributes within a frozen\n # dataclass are covariant rather than invariant.\n a: int\n","source":"typing_tests","origin":"conformance/tests/dataclasses_frozen.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_09.py","code":"\"\"\"\nTests the synthesis of the __hash__ method in a dataclass.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Callable, Hashable, assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n\n\nassert_type(DC1.__hash__, None)\n\n# These should generate errors because DC1 isn't hashable.\nDC1(0).__hash__() # E\nv1: Hashable = DC1(0) # E\n\n\n@dataclass(eq=True, frozen=True)\nclass DC2:\n a: int\n\n\ndc2_hash: Callable[..., int] = DC2.__hash__ # OK\nDC2(0).__hash__() # OK\nv2: Hashable = DC2(0) # OK\n\n\n@dataclass(eq=True)\nclass DC3:\n a: int\n\n\nassert_type(DC3.__hash__, None)\n\n# These should generate errors because DC3 isn't hashable.\nDC3(0).__hash__() # E\nv3: Hashable = DC3(0) # E\n\n\n@dataclass(frozen=True)\nclass DC4:\n a: int\n\n\ndc4_hash: Callable[..., int] = DC4.__hash__ # OK\nDC4(0).__hash__() # OK\nv4: Hashable = DC4(0) # OK\n\n\n@dataclass(eq=True, unsafe_hash=True)\nclass DC5:\n a: int\n\n\ndc5_hash: Callable[..., int] = DC5.__hash__ # OK\nDC5(0).__hash__() # OK\nv5: Hashable = DC5(0) # OK\n\n\n@dataclass(eq=True)\nclass DC6:\n a: int\n\n def __hash__(self) -> int:\n return 0\n\n\ndc6_hash: Callable[..., int] = DC6.__hash__ # OK\nDC6(0).__hash__() # OK\nv6: Hashable = DC6(0) # OK\n\n\n@dataclass(frozen=True)\nclass DC7:\n a: int\n\n def __eq__(self, other) -> bool:\n return self.a == other.a\n\n\ndc7_hash: Callable[..., int] = DC7.__hash__ # OK\nDC7(0).__hash__() # OK\nv7: Hashable = DC7(0) # OK\n","source":"typing_tests","origin":"conformance/tests/dataclasses_hash.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_10.py","code":"\"\"\"\nTests inheritance rules for dataclasses.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#inheritance\n\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar\n\n\n@dataclass\nclass DC1:\n a: int\n b: str = \"\"\n\n\n@dataclass\nclass DC2(DC1):\n b: str = \"\"\n a: int = 1\n\n\ndc2_1 = DC2(1, \"\")\n\ndc2_2 = DC2()\n\n\n@dataclass\nclass DC3:\n x: float = 15.0\n y: str = \"\"\n\n\n@dataclass\nclass DC4(DC3):\n z: tuple[int] = (10,)\n x: float = 15\n\n\ndc4_1 = DC4(0.0, \"\", (1,))\n\n\n@dataclass\nclass DC5:\n # While this generates an error at runtime for the stdlib dataclass,\n # other libraries that use dataclass_transform don't have similar\n # restrictions. It is therefore not required that a type checker\n # report an error here.\n x: list[int] = [] # E?\n\n\n@dataclass\nclass DC6:\n x: int\n y: ClassVar[int] = 1\n\n\n@dataclass\nclass DC7(DC6):\n # This should generate an error because a ClassVar cannot override\n # an instance variable of the same name.\n x: ClassVar[int] # E\n\n # This should generate an error because an instance variable cannot\n # override a class variable of the same name.\n y: int # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_11.py","code":"\"\"\"\nTests the keyword-only feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY, field\n\n\n@dataclass\nclass DC1:\n a: str\n _: KW_ONLY\n b: int = 0\n\n\nDC1(\"hi\")\nDC1(a=\"hi\")\nDC1(a=\"hi\", b=1)\nDC1(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC1(\"hi\", 1) # E\n\n\n@dataclass\nclass DC2:\n b: int = field(kw_only=True, default=3)\n a: str\n\n\nDC2(\"hi\")\nDC2(a=\"hi\")\nDC2(a=\"hi\", b=1)\nDC2(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC2(\"hi\", 1) # E\n\n\n@dataclass(kw_only=True)\nclass DC3:\n a: str = field(kw_only=False)\n b: int = 0\n\n\nDC3(\"hi\")\nDC3(a=\"hi\")\nDC3(a=\"hi\", b=1)\nDC3(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC3(\"hi\", 1) # E\n\n\n@dataclass\nclass DC4(DC3):\n c: float\n\n\nDC4(\"\", 0.2, b=3)\nDC4(a=\"\", b=3, c=0.2)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_kwonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_12.py","code":"\"\"\"\nTests the match_args feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY\nfrom typing import assert_type, Literal\n\n# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method\n\n@dataclass(match_args=True)\nclass DC1:\n x: int\n _: KW_ONLY\n y: str\n\nassert_type(DC1.__match_args__, tuple[Literal['x']])\n\n# The match_args default is True\n\n@dataclass\nclass DC2:\n x: int\n\nassert_type(DC2.__match_args__, tuple[Literal['x']])\n\n# __match_args__ is created even if __init__() is not generated\n\n@dataclass(match_args=True, init=False)\nclass DC3:\n x: int = 0\n\nassert_type(DC3.__match_args__, tuple[Literal['x']])\n\n# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.\n\n@dataclass(match_args=False)\nclass DC4:\n x: int\n\nDC4.__match_args__ # E\n\n@dataclass(match_args=True)\nclass DC5:\n __match_args__ = ()\n x: int\n\nassert_type(DC5.__match_args__, tuple[()])\n","source":"typing_tests","origin":"conformance/tests/dataclasses_match_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_13.py","code":"\"\"\"\nTests the synthesized comparison methods for dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass DC1:\n a: str\n b: int\n\n\n@dataclass(order=True)\nclass DC2:\n a: str\n b: int\n\n\ndc1_1 = DC1(\"\", 0)\ndc1_2 = DC1(\"\", 0)\n\nif dc1_1 < dc1_2:\n pass\n\nif dc1_1 <= dc1_2:\n pass\n\nif dc1_1 > dc1_2:\n pass\n\nif dc1_1 >= dc1_2:\n pass\n\nif dc1_1 == dc1_2:\n pass\n\nif dc1_1 != dc1_2:\n pass\n\nif dc1_1 == None:\n pass\n\nif dc1_1 != None:\n pass\n\ndc2_1 = DC2(\"hi\", 2)\n\n# This should generate an error because the types are\n# incompatible.\nif dc1_1 < dc2_1: # E:\n pass\n\nif dc1_1 != dc2_1:\n pass\n","source":"typing_tests","origin":"conformance/tests/dataclasses_order.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_14.py","code":"\"\"\"\nTests type checking of the __post_init__ method in a dataclass.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#post-init-processing\n\nfrom dataclasses import InitVar, dataclass, field, replace\nfrom typing import assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n b: int\n x: InitVar[int]\n c: int\n y: InitVar[str]\n\n def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y\n pass\n\n\ndc1 = DC1(1, 2, 3, 4, \"\")\n\nassert_type(dc1.a, int)\nassert_type(dc1.b, int)\nassert_type(dc1.c, int)\nprint(dc1.x) # E: cannot access InitVar\nprint(dc1.y) # E: cannot access InitVar\n\n@dataclass\nclass DC2:\n x: InitVar[int]\n y: InitVar[str]\n\n def __post_init__(self, x: int) -> None: # E: missing y\n pass\n\n\n@dataclass\nclass DC3:\n _name: InitVar[str] = field()\n name: str = field(init=False)\n\n def __post_init__(self, _name: str):\n ...\n\n\n@dataclass\nclass DC4(DC3):\n _age: InitVar[int] = field()\n age: int = field(init=False)\n\n def __post_init__(self, _name: str, _age: int):\n ...\n","source":"typing_tests","origin":"conformance/tests/dataclasses_postinit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_15.py","code":"\"\"\"\nTests the slots functionality of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass\n\n# This should generate an error because __slots__ is already defined.\n@dataclass(slots=True) # E[DC1]\nclass DC1: # E[DC1]\n x: int\n\n __slots__ = ()\n\n\n@dataclass(slots=True)\nclass DC2:\n x: int\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass(slots=False)\nclass DC3:\n x: int\n\n __slots__ = (\"x\",)\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass\nclass DC4:\n __slots__ = (\"y\", \"x\")\n x: int\n y: str\n\n\nDC4(1, \"bar\")\n\n\n@dataclass(slots=True)\nclass DC5:\n a: int\n\n\nDC5.__slots__\nDC5(1).__slots__\n\n\n@dataclass\nclass DC6:\n a: int\n\n\n# This should generate an error because __slots__ is not defined.\nDC6.__slots__ # E\n\n# This should generate an error because __slots__ is not defined.\nDC6(1).__slots__ # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_slots.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_16.py","code":"\"\"\"\nTests basic handling of the dataclass factory.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html\n# Also, see https://peps.python.org/pep-0557/\n\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar, assert_type\nimport sys\n\nT = TypeVar(\"T\")\n\n\n@dataclass(order=True)\nclass InventoryItem:\n x = 0\n name: str\n unit_price: float\n quantity_on_hand: int = 0\n\n def total_cost(self) -> float:\n return self.unit_price * self.quantity_on_hand\n\n\nv1 = InventoryItem(\"soap\", 2.3)\n\n\nclass InventoryItemInitProto(Protocol):\n def __call__(\n self, name: str, unit_price: float, quantity_on_hand: int = ...\n ) -> None: ...\n\n\n# Validate the type of the synthesized __init__ method.\nx1: InventoryItemInitProto = v1.__init__\n\n# Make sure the following additional methods were synthesized.\nprint(v1.__repr__)\nprint(v1.__eq__)\nprint(v1.__ne__)\nprint(v1.__lt__)\nprint(v1.__le__)\nprint(v1.__gt__)\nprint(v1.__ge__)\n\nassert_type(v1.name, str)\nassert_type(v1.unit_price, float)\nassert_type(v1.quantity_on_hand, int)\n\nv2 = InventoryItem(\"name\") # E: missing unit_price\nv3 = InventoryItem(\"name\", \"price\") # E: incorrect type for unit_price\nv4 = InventoryItem(\"name\", 3.1, 3, 4) # E: too many arguments\n\n\n# > TypeError will be raised if a field without a default value follows a\n# > field with a default value. This is true either when this occurs in a\n# > single class, or as a result of class inheritance.\n@dataclass # E[DC1]\nclass DC1:\n a: int = 0 # E[DC1]: field with default should follow a field with no default.\n b: int # E[DC1]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC2]\nclass DC2:\n a: int = field(default=1) # E[DC2]: field with default should follow a field with no default.\n b: int # E[DC2]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC3]\nclass DC3:\n a: InitVar[int] = 0 # E[DC3]: field with default should follow a field with no default.\n b: int # E[DC3]: field with no default cannot follow field with default.\n\n\n@dataclass\nclass DC4:\n a: int = field(init=False)\n b: int\n\n\nv5 = DC4(0)\nv6 = DC4(0, 1) # E: too many parameters\n\n\n@dataclass\nclass DC5:\n a: int = field(default_factory=str) # E: type mismatch\n\n\ndef f(s: str) -> int:\n return int(s)\n\n\n@dataclass\nclass DC6:\n a: ClassVar[int] = 0\n b: str\n c: Callable[[str], int] = f\n\n\ndc6 = DC6(\"\")\nassert_type(dc6.a, int)\nassert_type(DC6.a, int)\nassert_type(dc6.b, str)\nassert_type(dc6.c, Callable[[str], int])\n\n\n@dataclass\nclass DC7:\n x: int\n\n\n@dataclass(init=False)\nclass DC8(DC7):\n y: int\n\n def __init__(self, a: DC7, y: int):\n self.__dict__ = a.__dict__\n self.y = y\n\n\na = DC7(3)\nb = DC8(a, 5)\n\n# This should generate an error because there is an extra parameter\nDC7(3, 4) # E\n\n# This should generate an error because there is one too few parameters\nDC8(a) # E\n\n\n@dataclass\nclass DC9:\n a: str = field(init=False, default=\"s\")\n b: bool = field()\n\n\n@dataclass\nclass DC10(DC9):\n a: str = field()\n b: bool = field()\n\n\n@dataclass(init=False)\nclass DC11:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC11(3)\n\n\n@dataclass(init=True)\nclass DC12:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC12(3)\n\n\n@dataclass(init=False)\nclass DC13:\n x: int\n x_squared: int\n\n\n# This should generate an error because there is no matching\n# override __init__ method and no synthesized __init__.\nDC13(3) # E\n\n\n@dataclass\nclass DC14:\n prop_1: str = field(init=False)\n prop_2: str = field(default=\"hello\")\n prop_3: str = field(default_factory=lambda: \"hello\")\n\n\n@dataclass\nclass DC15(DC14):\n prop_2: str = \"\"\n\n\ndc15 = DC15(prop_2=\"test\")\n\nassert_type(dc15.prop_1, str)\nassert_type(dc15.prop_2, str)\nassert_type(dc15.prop_3, str)\n\n\nclass DataclassProto(Protocol):\n __dataclass_fields__: ClassVar[dict[str, Any]]\n\n\nv7: DataclassProto = dc15\n\n\n@dataclass\nclass DC16(Generic[T]):\n value: T\n\n\nassert_type(DC16(1), DC16[int])\n\n\nclass DC17(DC16[str]):\n pass\n\n\nassert_type(DC17(\"\"), DC17)\n\n\n@dataclass\nclass DC18:\n x: int = field()\n # This may generate a type checker error because an unannotated field\n # will result in a runtime exception.\n y = field() # E?\n\n\n# > Dataclass fields may be conditional, via checks of the same\n# > statically-known conditions that a type-checker understands elsewhere,\n# > such as Python version:\n\n@dataclass\nclass DC19:\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nDC19(1, 2)\nDC19(1, 2, 3) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"deprecated-decorator","pep":"702","introduced_in":"3.13","form":"modern","file":"deprecated-decorator/modern_01.py","code":"\"\"\"\nTests the warnings.deprecated function.\n\"\"\"\n\n# pyright: reportDeprecated=true\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#deprecated\n# See also https://peps.python.org/pep-0702/\n\nfrom typing import Protocol, override\nfrom typing_extensions import deprecated\n\n# > Type checkers should produce a diagnostic whenever they encounter a usage of an object\n# > marked as deprecated. [...] For deprecated classes and functions, this includes:\n\n# > * `from` imports\n\nfrom _directives_deprecated_library import Ham # E: Use of deprecated class Ham\nimport _directives_deprecated_library as library\n\n\n# > * References through module, class, or instance attributes\n\nlibrary.norwegian_blue(1) # E: Use of deprecated function norwegian_blue\nmap(library.norwegian_blue, [1, 2, 3]) # E: Use of deprecated function norwegian_blue\n\n\n# > For deprecated overloads, this includes all calls that resolve to the deprecated overload.\n\nlibrary.foo(1) # E: Use of deprecated overload for foo\nlibrary.foo(\"x\") # OK\n\n\nham = Ham() # E?: OK (already reported above)\n\n\n# > * Any syntax that indirectly triggers a call to the function.\n\nspam = library.Spam()\n\n_ = spam + 1 # E: Use of deprecated method Spam.__add__\nspam += 1 # E: Use of deprecated method Spam.__add__\n\nspam.greasy # E: Use of deprecated property Spam.greasy\nspam.shape # OK\n\nspam.shape = \"cube\" # E: Use of deprecated property setter Spam.shape\nspam.shape += \"cube\" # E: Use of deprecated property setter Spam.shape\n\n\nclass Invocable:\n @deprecated(\"Deprecated\")\n def __call__(self) -> None:\n ...\n\n\ninvocable = Invocable()\ninvocable() # E: Use of deprecated method __call__\n\n\n# > * Any usage of deprecated objects in their defining module\n\n\n@deprecated(\"Deprecated\")\ndef lorem() -> None:\n ...\n\n\nlorem() # E: Use of deprecated function lorem\n\n\n# > There are additional scenarios where deprecations could come into play.\n# > For example, an object may implement a `typing.Protocol`,\n# > but one of the methods required for protocol compliance is deprecated.\n# > As scenarios such as this one appear complex and relatively unlikely to come up in practice,\n# > this PEP does not mandate that type checkers detect them.\n\n\nclass SupportsFoo1(Protocol):\n @deprecated(\"Deprecated\")\n def foo(self) -> None:\n ...\n\n def bar(self) -> None:\n ...\n\n\nclass FooConcrete1(SupportsFoo1):\n @override\n def foo(self) -> None: # E?: Implementation of deprecated method foo\n ...\n\n def bar(self) -> None:\n ...\n\n\ndef foo_it(f: SupportsFoo1) -> None:\n f.foo() # E: Use of deprecated method foo\n f.bar()\n\n\nclass SupportsFoo2(Protocol):\n def foo(self) -> None:\n ...\n\n\nclass FooConcrete2:\n @deprecated(\"Deprecated\")\n def foo(self) -> None:\n ...\n\n\ndef takes_foo(f: SupportsFoo2) -> None:\n ...\n\n\ndef caller(c: FooConcrete2) -> None:\n takes_foo(\n c\n ) # E?: FooConcrete2 is a SupportsFoo2, but only because of a deprecated method\n","source":"typing_tests","origin":"conformance/tests/directives_deprecated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_01.py","code":"\"\"\"\nTests the handling of ClassVar and Final in dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import assert_type, ClassVar, Final\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#dataclass-semantics\n\n# > A final class variable on a dataclass must be explicitly annotated as\n# e.g. x: ClassVar[Final[int]] = 3.\n\n\n@dataclass\nclass D:\n final_no_default: Final[int]\n final_with_default: Final[str] = \"foo\"\n final_classvar: ClassVar[Final[int]] = 4\n # we don't require support for Final[ClassVar[...]] because the dataclasses\n # runtime implementation won't recognize it as a ClassVar either\n\n\n# An explicitly marked ClassVar can be accessed on the class:\nassert_type(D.final_classvar, int)\n\n# ...but not assigned to, because it's Final:\nD.final_classvar = 10 # E: can't assign to final attribute\n\n# A non-ClassVar attribute (with or without default) is a dataclass field:\nd = D(final_no_default=1, final_with_default=\"bar\")\nassert_type(d.final_no_default, int)\nassert_type(d.final_with_default, str)\n\n# ... but can't be assigned to (on the class or on an instance):\nd.final_no_default = 10 # E: can't assign to final attribute\nd.final_with_default = \"baz\" # E: can't assign to final attribute\nD.final_no_default = 10 # E: can't assign to final attribute\nD.final_with_default = \"baz\" # E: can't assign to final attribute\n","source":"typing_tests","origin":"conformance/tests/dataclasses_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_02.py","code":"\"\"\"\nTests the typing.Final special form.\n\"\"\"\n\nfrom typing import ClassVar, Final, Literal, NamedTuple, TypedDict, assert_type\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#id1\n\nID1: Final[int] = 1\n\nID2: Final = 1\nassert_type(ID2, Literal[1])\n\n# > If the right hand side is omitted, there must be an explicit type argument to Final.\n\nBAD1: Final # E: missing assignment\n\nBAD2: Final[str, int] = \"\" # E: only one type argument allowed\n\n# > There can be at most one final declaration per module or class for a given\n# > attribute.\n\n# > As self.id: Final = 1 (also optionally with a type in square brackets).\n# > This is allowed only in __init__ methods, so that the final instance\n# > attribute is assigned only once when an instance is created.\n\n\nclass ClassA:\n ID1: Final = 1\n\n # > In class bodies and stub files you can omit the right hand side and just\n # > write ID: Final[float]. If the right hand side is omitted, there must be\n # > an explicit type argument to Final.\n ID2: Final # E: missing initialization\n\n # > A final attribute declared in a class body without an initializer must\n # > be initialized in the __init__ method (except in stub files):\n ID3: Final[int] # E: missing initialization\n\n ID4: Final[int] # OK because initialized in __init__\n\n ID5: Final[int] = 0\n\n ID6: Final[int]\n\n ID7: Final[int] = 0\n\n def __init__(self, cond: bool) -> None:\n self.id1: Final = 1\n self.id2: Final[int] = 1\n\n self.ID4 = 1\n\n self.ID5 = 0 # E: Already initialized\n\n if cond:\n self.ID6 = 1\n else:\n self.ID6 = 2\n\n def method1(self) -> None:\n self.id3: Final = 1 # E: not allowed outside of __init__ method.\n self.id4: Final[int] = 1 # E: not allowed outside of __init__ method.\n\n self.ID7 = 0 # E: cannot modify Final value\n\n self.ID7 += 1 # E: cannot modify Final value\n\n\nRATE: Final = 3000\nRATE = 300 # E: Cannot redefine Final value\n\n# > There can’t be separate class-level and instance-level constants\n# > with the same name.\n\n\nclass ClassB:\n DEFAULT_ID: Final = 0\n\n\nClassB.DEFAULT_ID = 0 # E: Cannot redefined value\n\n\n# > A type checker should prevent final attributes from being overridden in a subclass:\n\n\nclass ClassC:\n BORDER_WIDTH: Final = 2.5\n\n __private: Final = 0\n\n\nclass ClassCChild(ClassC):\n BORDER_WIDTH = 2.5 # E: Cannot override Final value\n\n __private = 0 # OK\n\n\n# > Type checkers should infer a final attribute that is initialized in a class\n# > body as being a class variable. Variables should not be annotated with both\n# > ClassVar and Final. (Except in a dataclass; see dataclasses_final.py.)\n\n\nclass ClassD:\n VALUE1: Final = 1\n\n VALUE2: ClassVar[Final] = 1 # E: Final cannot be used with ClassVar\n VALUE3: Final[ClassVar] = 1 # E: Final cannot be used with ClassVar\n\n\nClassD.VALUE1 # OK\n\n\n# > Final may only be used as the outermost type in assignments or variable\n# > annotations. Using it in any other position is an error. In particular,\n# > Final can’t be used in annotations for function arguments.\n\nx: list[Final[int]] = [] # E\n\n\ndef func1(x: Final[list[int]]) -> None: # E\n ...\n\n\n# > ``Final`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithFinal(TypedDict):\n a: int\n b: Final[int] # E: Final not allowed in a TypedDict\n\n\nclass NTWithFinal(NamedTuple):\n a: int\n b: Final[int] # E: Final not allowed in a NamedTuple\n\n\n# > Type checkers should treat uses of a final name that was initialized with\n# > a literal as if it was replaced by the literal. For example, the following\n# > should be allowed:\n\nX: Final = \"x\"\nY: Final = \"y\"\nN = NamedTuple(\"N\", [(X, int), (Y, int)])\n\nN(x=3, y=4) # OK\nN(a=1) # E\nN(x=\"\", y=\"\") # E\n\n\ndef func2() -> None:\n global ID1\n\n ID1 = 2 # E: cannot modify Final value\n\n x: Final = 3\n\n x += 1 # E: cannot modify Final value\n\n a = (x := 4) # E: cannot modify Final value\n\n for x in [1, 2, 3]: # E: cannot modify Final value\n pass\n\n with open(\"FileName\") as x: # E: cannot modify Final value\n pass\n\n (a, x) = (1, 2) # E: cannot modify Final value\n\n\n# > If a module declares a ``Final`` variable and another module imports that\n# > variable in an import statement by name or wildcard, the imported symbol\n# > inherits the ``Final`` type qualifier. Any attempt to assign a different value\n# > to this symbol should be flagged as an error by a type checker.\n\n\nfrom _qualifiers_final_annotation_1 import TEN\n\nTEN = 9 # E: Cannot redefine Final value\n\nfrom _qualifiers_final_annotation_2 import *\n\nPI = 3.14159 # E: Cannot redefine Final value\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_03.py","code":"\"\"\"\nTests the @final decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#final\n\nfrom typing import final, overload\nfrom _qualifiers_final_decorator import Base3, Base4\n\n# > A type checker should prohibit any class decorated with @final from being\n# > subclassed and any method decorated with @final from being overridden in a\n# > subclass. The method decorator version may be used with all of instance\n# > methods, class methods, static methods, and properties.\n\n\n@final\nclass Base1:\n ...\n\n\nclass Derived1(Base1): # E: Cannot inherit from final class \"Base\"\n ...\n\n\nclass Base2:\n @final\n def method1(self) -> None:\n pass\n\n @final\n @classmethod\n def method2(cls) -> None:\n pass\n\n @final\n @staticmethod\n def method3() -> None:\n pass\n\n # > For overloaded methods, @final should be placed on the implementation.\n\n @overload\n def method4(self, x: int) -> int:\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @final\n def method4(self, x: int | str) -> int | str:\n return 0\n\n\nclass Derived2(Base2):\n def method1(self) -> None: # E\n pass\n\n @classmethod # E[method2]\n def method2(cls) -> None: # E[method2]\n pass\n\n @staticmethod # E[method3]\n def method3() -> None: # E[method3]\n pass\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n def method4(self, x: int | str) -> int | str: # E[method4]\n return 0\n\n\nclass Derived3(Base3):\n @overload # E[Derived3]\n def method(self, x: int) -> int: # E[Derived3]\n ...\n\n @overload # E[Derived3-2]\n @final # E[Derived3-2]: should be applied only to implementation\n def method(self, x: str) -> str: # E[Derived3-2]\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived3]\n return 0\n\n\nclass Derived4(Base4):\n @overload # E[Derived4]\n def method(self, x: int) -> int: # E[Derived4]\n ...\n\n @overload\n def method(self, x: str) -> str:\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived4]\n return 0\n\n\nclass Base5_1:\n ...\n\n\nclass Base5_2:\n @final\n def method(self, v: int) -> None:\n ...\n\n\n# Test multiple inheritance case.\nclass Derived5(Base5_1, Base5_2):\n def method(self) -> None: # E\n ...\n\n\n# > It is an error to use @final on a non-method function.\n\n\n@final # E[func]: not allowed on non-method function.\ndef func1() -> int: # E[func]\n return 0\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_decorator.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_04.py","code":"\"\"\"\nTests the use of Final values when used with TypedDicts.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#use-of-final-values-and-literal-types\n\nfrom typing import Final, Literal, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\n# > Type checkers should allow final names (PEP 591) with string values to be\n# > used instead of string literals in operations on TypedDict objects.\nYEAR: Final = \"year\"\n\nm: Movie = {\"name\": \"Alien\", \"year\": 1979}\nyears_since_epoch = m[YEAR] - 1970\n\n\n# > An expression with a suitable literal type (PEP 586) can be used instead of\n# > a literal value.\ndef get_value(movie: Movie, key: Literal[\"year\", \"name\"]) -> int | str:\n return movie[key]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"literal-string","pep":"675","introduced_in":"3.11","form":"modern","file":"literal-string/modern_01.py","code":"\"\"\"\nTests handling of the LiteralString special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#literalstring\n\n\nfrom typing import (\n Any,\n Generic,\n Literal,\n LiteralString,\n Sequence,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nvariable_annotation: LiteralString\n\n\ndef my_function(literal_string: LiteralString) -> LiteralString:\n raise NotImplementedError\n\n\nclass Foo:\n my_attribute: LiteralString = \"\"\n\n\ntype_argument: list[LiteralString]\n\nT = TypeVar(\"T\", bound=LiteralString)\n\n\nbad_union: Literal[\"hello\", LiteralString] # E\nbad_nesting: Literal[LiteralString] # E\n\n\ndef func1(a: Literal[\"one\"], b: Literal[\"two\"]):\n x1: LiteralString = a\n\n x2: Literal[\"\"] = b # E\n\n\ndef func2(a: LiteralString, b: LiteralString, non_literal: str):\n # > Addition: x + y is of type LiteralString if both x and y are compatible with LiteralString.\n assert_type(a + b, LiteralString)\n\n # > Joining: sep.join(xs) is of type LiteralString if sep’s type is\n # > compatible with LiteralString and xs’s type is compatible with Iterable[LiteralString].\n assert_type(\",\".join((a, b)), LiteralString)\n assert_type(\",\".join((a, non_literal)), str)\n\n # > In-place addition: If s has type LiteralString and x has type compatible with\n # > LiteralString, then s += x preserves s’s type as LiteralString.\n a += \"hello\"\n b += a\n\n # > String formatting: An f-string has type LiteralString if and only if its constituent\n # > expressions are literal strings. s.format(...) has type LiteralString if and only if\n # > s and the arguments have types compatible with LiteralString.\n assert_type(f\"{a} {b}\", LiteralString)\n\n x1: LiteralString = f\"{a} {non_literal}\" # E\n\n assert_type(a + non_literal, str)\n\n # > LiteralString is compatible with the type str\n x2: str = a\n\n # > Other literal types, such as literal integers, are not compatible with LiteralString.\n x3: LiteralString = 3 # E\n x4: LiteralString = b\"test\" # E\n\n\n# > Conditional statements and expressions work as expected.\ndef condition1() -> bool:\n raise NotImplementedError\n\n\ndef return_literal_string() -> LiteralString:\n return \"foo\" if condition1() else \"bar\" # OK\n\n\ndef return_literal_str2(literal_string: LiteralString) -> LiteralString:\n return \"foo\" if condition1() else literal_string # OK\n\n\ndef return_literal_str3() -> LiteralString:\n result: LiteralString\n if condition1():\n result = \"foo\"\n else:\n result = \"bar\"\n\n return result # OK\n\n\n# > TypeVars can be bound to LiteralString.\nTLiteral = TypeVar(\"TLiteral\", bound=LiteralString)\n\n\ndef literal_identity(s: TLiteral) -> TLiteral:\n return s\n\n\ndef func3(s: Literal[\"hello\"]):\n y = literal_identity(s)\n assert_type(y, Literal[\"hello\"])\n\n\ndef func4(s: LiteralString):\n y2 = literal_identity(s)\n assert_type(y2, LiteralString)\n\n\ndef func5(s: str):\n literal_identity(s) # E\n\n\n# > LiteralString can be used as a type argument for generic classes.\nclass Container(Generic[T]):\n def __init__(self, value: T) -> None:\n self.value = value\n\n\ndef func6(s: LiteralString):\n x: Container[LiteralString] = Container(s) # OK\n\n\ndef func7(s: str):\n x_error: Container[LiteralString] = Container(s) # E\n\n\n# > Standard containers like List work as expected.\nxs: list[LiteralString] = [\"foo\", \"bar\", \"baz\"]\n\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\n\n@overload\ndef func8(x: Literal[\"foo\"]) -> C:\n ...\n\n\n@overload\ndef func8(x: LiteralString) -> B:\n ...\n\n\n@overload\ndef func8(x: str) -> A:\n ...\n\n\ndef func8(x: Any) -> Any:\n raise NotImplementedError\n\n\ndef call_func8(x: str) -> None:\n assert_type(func8(\"foo\"), C) # First overload\n assert_type(func8(\"bar\"), B) # Second overload\n assert_type(func8(x), A) # Third overload\n\n\ndef func9(val: list[LiteralString]):\n x1: list[str] = val # E\n\n\ndef func10(val: Sequence[LiteralString]):\n x1: Sequence[str] = val # OK\n","source":"typing_tests","origin":"conformance/tests/literals_literalstring.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_04.py","code":"\"\"\"\nTests interactions between Literal types and other typing features.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#interactions-with-other-types-and-features\nfrom enum import Enum\nfrom typing import IO, Any, Final, Generic, Literal, TypeVar, LiteralString, assert_type, overload\n\n\ndef func1(v: tuple[int, str, list[bool]], a: Literal[0], b: Literal[5], c: Literal[-5]):\n assert_type(v[a], int)\n assert_type(v[2], list[bool])\n\n v[b] # E: index out of range\n v[c] # E: index out of range\n v[4] # E: index out of range\n v[-4] # E: index out of range\n\n\n_PathType = str | bytes | int\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"r\", \"w\", \"a\", \"x\", \"r+\", \"w+\", \"a+\", \"x+\"],\n) -> IO[str]:\n ...\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"rb\", \"wb\", \"ab\", \"xb\", \"r+b\", \"w+b\", \"a+b\", \"x+b\"],\n) -> IO[bytes]:\n ...\n\n\n@overload\ndef open(path: _PathType, mode: str) -> IO[Any]:\n ...\n\n\ndef open(path: _PathType, mode: Any) -> Any:\n raise NotImplementedError\n\n\nassert_type(open(\"path\", \"r\"), IO[str])\nassert_type(open(\"path\", \"wb\"), IO[bytes])\nassert_type(open(\"path\", \"other\"), IO[Any])\n\n\nA = TypeVar(\"A\", bound=int)\nB = TypeVar(\"B\", bound=int)\nC = TypeVar(\"C\", bound=int)\n\n\nclass Matrix(Generic[A, B]):\n def __add__(self, other: \"Matrix[A, B]\") -> \"Matrix[A, B]\":\n raise NotImplementedError\n\n def __matmul__(self, other: \"Matrix[B, C]\") -> \"Matrix[A, C]\":\n raise NotImplementedError\n\n def transpose(self) -> \"Matrix[B, A]\":\n raise NotImplementedError\n\n\ndef func2(a: Matrix[Literal[2], Literal[3]], b: Matrix[Literal[3], Literal[7]]):\n c = a @ b\n assert_type(c, Matrix[Literal[2], Literal[7]])\n\n\nT = TypeVar(\"T\", Literal[\"a\"], Literal[\"b\"], Literal[\"c\"])\nS = TypeVar(\"S\", bound=Literal[\"foo\"])\n\n\nclass Status(Enum):\n SUCCESS = 0\n INVALID_DATA = 1\n FATAL_ERROR = 2\n\n\ndef parse_status1(s: str | Status) -> None:\n if s is Status.SUCCESS:\n assert_type(s, Literal[Status.SUCCESS])\n elif s is Status.INVALID_DATA:\n assert_type(s, Literal[Status.INVALID_DATA])\n elif s is Status.FATAL_ERROR:\n assert_type(s, Literal[Status.FATAL_ERROR])\n else:\n assert_type(s, str)\n\n\n# > Type checkers may optionally perform additional analysis for both\n# > enum and non-enum Literal types beyond what is described in the section above.\n#\n# > For example, it may be useful to perform narrowing based on things\n# > like containment or equality checks:\n\ndef expects_bad_status(status: Literal[\"MALFORMED\", \"ABORTED\"]):\n ...\n\n\ndef expects_pending_status(status: Literal[\"PENDING\"]):\n ...\n\n\ndef parse_status2(status: LiteralString) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n\n# Narrowing `str` to `Literal` strings is unsound given the possiblity of\n# user-defined `str` subclasses that could have custom equality semantics,\n# but is explicitly listed by the spec as optional analysis that type checkers\n# may perform.\ndef parse_status3(status: str) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n\nfinal_val1: Final = 3\nassert_type(final_val1, Literal[3])\n\nfinal_val2: Final = True\nassert_type(final_val2, Literal[True])\n","source":"typing_tests","origin":"conformance/tests/literals_interactions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_05.py","code":"\"\"\"\nTests legal and illegal parameterizations of Literal.\n\"\"\"\n\n# > Literal must be parameterized with at least one type.\n\nfrom typing import Any, Literal, TypeVar\nfrom enum import Enum\n\n\nclass Color(Enum):\n RED = 0\n GREEN = 1\n BLUE = 2\n\n\ngood1: Literal[26]\ngood2: Literal[0x1A]\ngood3: Literal[-4]\ngood4: Literal[+5]\ngood5: Literal[\"hello world\"]\ngood6: Literal[b\"hello world\"]\ngood7: Literal[\"hello world\"]\ngood8: Literal[True]\ngood9: Literal[Color.RED]\ngood10: Literal[None]\n\nReadOnlyMode = Literal[\"r\", \"r+\"]\nWriteAndTruncateMode = Literal[\"w\", \"w+\", \"wt\", \"w+t\"]\nWriteNoTruncateMode = Literal[\"r+\", \"r+t\"]\nAppendMode = Literal[\"a\", \"a+\", \"at\", \"a+t\"]\n\nAllModes = Literal[ReadOnlyMode, WriteAndTruncateMode, WriteNoTruncateMode, AppendMode]\n\ngood11: Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n\nvariable = 3\nT = TypeVar(\"T\")\n\n# > Arbitrary expressions [are illegal]\nbad1: Literal[3 + 4] # E\nbad2: Literal[\"foo\".replace(\"o\", \"b\")] # E\nbad3: Literal[4 + 3j] # E\nbad4: Literal[~5] # E\nbad5: Literal[not False] # E\nbad6: Literal[(1, \"foo\", \"bar\")] # E\nbad7: Literal[{\"a\": \"b\", \"c\": \"d\"}] # E\nbad8: Literal[int] # E\nbad9: Literal[variable] # E\nbad10: Literal[T] # E\nbad11: Literal[3.14] # E\nbad12: Literal[Any] # E\nbad13: Literal[...] # E\n\n\ndef my_function(x: Literal[1 + 2]) -> int: # E\n return x * 3\n\n\nx: Literal # E\ny: Literal[my_function] = my_function # E\n\n\ndef func2(a: Literal[Color.RED]):\n x1: Literal[\"Color.RED\"] = a # E\n\n x2: \"Literal[Color.RED]\" = a # OK\n","source":"typing_tests","origin":"conformance/tests/literals_parameterizations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_06.py","code":"\"\"\"\nTests the semantics of the Literal special form.\n\"\"\"\n\nfrom typing import Literal\nfrom typing import Literal as L\n\n\nv1: Literal[3] = 3\nv2: Literal[3] = 4 # E\n\nv3: L[-3] = -3\n\n\n# > Literal[20] and Literal[0x14] are equivalent\ndef func1(a: Literal[20], b: Literal[0x14], c: Literal[0b10100]):\n x1: Literal[0x14] = a\n x2: Literal[0x14] = b\n x3: Literal[0x14] = c\n\n\n# > Literal[0] and Literal[False] are not equivalent\ndef func2(a: Literal[0], b: Literal[False]):\n x1: Literal[False] = a # E\n x2: Literal[0] = b # E\n\n\n# > Given some value v that is a member of type T, the type Literal[v] shall\n# > be treated as a subtype of T. For example, Literal[3] is a subtype of int.\ndef func3(a: L[3, 4, 5]):\n b = a.__add__(3)\n c = a + 3\n a += 3 # E\n\n\n# > When a Literal is parameterized with more than one value, it’s treated\n# > as exactly equivalent to the union of those types.\ndef func4(a: L[None, 3] | L[3, \"foo\", b\"bar\", True]):\n x1: Literal[3, b\"bar\", True, \"foo\", None] = a\n a = x1\n","source":"typing_tests","origin":"conformance/tests/literals_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"override-decorator","pep":"698","introduced_in":"3.12","form":"modern","file":"override-decorator/modern_01.py","code":"\"\"\"\nTests the typing.override decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#override\n\nfrom typing import Any, Callable, overload, override\n\n\ndef wrapper(func: Callable[..., Any], /) -> Any:\n def wrapped(*args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n return wrapped\n\n\nclass ParentA:\n def method1(self) -> int:\n return 1\n\n @overload\n def method2(self, x: int) -> int:\n ...\n\n @overload\n def method2(self, x: str) -> str:\n ...\n\n def method2(self, x: int | str) -> int | str:\n return 0\n\n def method5(self):\n pass\n\n\nclass ChildA(ParentA):\n @override\n def method1(self) -> int: # OK\n return 2\n\n @overload\n def method2(self, x: int) -> int:\n ...\n\n @overload\n def method2(self, x: str) -> str:\n ...\n\n def method2(self, x: int | str) -> int | str: # OK\n return 0\n\n @override # E[method3]\n def method3(self) -> int: # E[method3]: no matching signature in ancestor\n return 1\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @override # E[method4]\n def method4(self, x: int | str) -> int | str: # E[method4]: no matching signature in ancestor\n return 0\n\n @override\n @wrapper\n def method5(self): # OK\n pass\n\n # > The @override decorator should be permitted anywhere a type checker\n # > considers a method to be a valid override, which typically includes not\n # > only normal methods but also @property, @staticmethod, and @classmethod.\n\n @staticmethod\n @override # E[static_method1]\n def static_method1() -> int: # E[static_method1]: no matching signature in ancestor\n return 1\n\n @classmethod\n @override # E[class_method1]\n def class_method1(cls) -> int: # E[class_method1]: no matching signature in ancestor\n return 1\n\n @property\n @override # E[property1]\n def property1(self) -> int: # E[property1]: no matching signature in ancestor\n return 1\n\n\n# Test the case where the parent derives from Any\n\nclass ParentB(Any):\n pass\n\n\nclass ChildB(ParentB):\n @override\n def method1(self) -> None: # OK\n pass\n\n\n# > When type checkers encounter a method decorated with @typing.override they\n# > should treat it as a type error unless that method is overriding a method or\n# > attribute in some ancestor class, and the type of the overriding method is\n# > assignable to the type of the overridden method.\n\n# ``__init__`` and ``__new__`` are normally exempt from override compatibility\n# checks, since constructors are not subject to the Liskov substitution\n# principle. However, when they are explicitly decorated with ``@override`` the\n# decorator's assignability check should still be honored.\n# See https://github.com/python/typing/issues/2222\n\n\nclass ParentC:\n def __init__(self, x: int) -> None: ...\n\n def __new__(cls, x: int) -> \"ParentC\":\n raise NotImplementedError\n\n\nclass ChildC1(ParentC):\n @override\n def __init__(self, x: int) -> None: ... # OK\n\n @override\n def __new__(cls, x: int) -> \"ChildC1\": # OK\n raise NotImplementedError\n\n\nclass ChildC2(ParentC):\n @override # E[init]\n def __init__(self, x: str) -> None: ... # E[init]: not assignable to \"ParentC.__init__\"\n\n @override # E[new]\n def __new__(cls, x: str) -> \"ChildC2\": # E[new]: not assignable to \"ParentC.__new__\"\n raise NotImplementedError\n\n\n# Without ``@override`` an incompatible constructor signature is allowed, since\n# ``__init__`` and ``__new__`` are exempt from the usual override checks.\n\n\nclass ChildC3(ParentC):\n def __init__(self, x: str) -> None: ... # OK\n\n def __new__(cls, x: str) -> \"ChildC3\": # OK\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/classes_override.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_01.py","code":"\"\"\"\nTests basic usage of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#paramspec-variables\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeAlias\n\nP = ParamSpec(\"P\") # OK\nWrongName = ParamSpec(\"NotIt\") # E: name inconsistency\n\n\n# > Valid use locations\n\nTA1: TypeAlias = P # E\n\nTA2: TypeAlias = Callable[P, None] # OK\nTA3: TypeAlias = Callable[Concatenate[int, P], None] # OK\nTA4: TypeAlias = Callable[..., None] # OK\nTA5: TypeAlias = Callable[..., None] # OK\n\n\ndef func1(x: P) -> P: # E\n raise NotImplementedError\n\n\ndef func2(x: Concatenate[int, P]) -> int: # E\n raise NotImplementedError\n\n\ndef func3(x: list[P]) -> None: # E\n ...\n\n\ndef func4(x: Callable[[int, str], P]) -> None: # E\n ...\n\n\ndef func5(*args: P, **kwargs: P) -> None: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_02.py","code":"\"\"\"\nTests the usage of a ParamSpec and its components (P.args, P.kwargs).\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#the-components-of-a-paramspec\n\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef puts_p_into_scope1(f: Callable[P, int]) -> None:\n def inner(*args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def mixed_up(*args: P.kwargs, **kwargs: P.args) -> None: # E\n pass\n\n def misplaced1(x: P.args) -> None: # E\n pass\n\n def bad_kwargs1(*args: P.args, **kwargs: P.args) -> None: # E\n pass\n\n def bad_kwargs2(*args: P.args, **kwargs: Any) -> None: # E\n pass\n\n\ndef out_of_scope(*args: P.args, **kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef puts_p_into_scope2(f: Callable[P, int]) -> None:\n stored_args: P.args # E\n stored_kwargs: P.kwargs # E\n\n def just_args(*args: P.args) -> None: # E\n pass\n\n def just_kwargs(**kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef decorator(f: Callable[P, int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n assert_type(f(*args, **kwargs), int) # OK\n\n f(*kwargs, **args) # E\n\n f(1, *args, **kwargs) # E\n\n return foo # OK\n\n\ndef add(f: Callable[P, int]) -> Callable[Concatenate[str, P], None]:\n def foo(s: str, *args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def bar(*args: P.args, s: str, **kwargs: P.kwargs) -> None: # E\n pass\n\n return foo # OK\n\n\ndef remove(f: Callable[Concatenate[int, P], int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n f(1, *args, **kwargs) # OK\n\n f(*args, 1, **kwargs) # E\n\n f(*args, **kwargs) # E\n\n return foo # OK\n\n\ndef outer(f: Callable[P, None]) -> Callable[P, None]:\n def foo(x: int, *args: P.args, **kwargs: P.kwargs) -> None:\n f(*args, **kwargs)\n\n def bar(*args: P.args, **kwargs: P.kwargs) -> None:\n foo(1, *args, **kwargs) # OK\n foo(x=1, *args, **kwargs) # E\n\n return bar\n\n\ndef twice(f: Callable[P, int], *args: P.args, **kwargs: P.kwargs) -> int:\n return f(*args, **kwargs) + f(*args, **kwargs)\n\n\ndef a_int_b_str(a: int, b: str) -> int:\n return 0\n\n\ntwice(a_int_b_str, 1, \"A\") # OK\ntwice(a_int_b_str, b=\"A\", a=1) # OK\ntwice(a_int_b_str, \"A\", 1) # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_components.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_03.py","code":"\"\"\"\nTests semantics of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#semantics\n\n\nfrom typing import Callable, Concatenate, Generic, ParamSpec, TypeVar, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef changes_return_type_to_str(x: Callable[P, int]) -> Callable[P, str]:\n raise NotImplementedError\n\n\ndef returns_int(a: str, b: bool, /) -> int:\n raise NotImplementedError\n\n\nf1 = changes_return_type_to_str(returns_int)\nassert_type(f1, Callable[[str, bool], str])\n\nv1 = f1(\"A\", True) # OK\nassert_type(v1, str)\nf1(a=\"A\", b=True) # E: positional-only\nf1(\"A\", \"A\") # E: wrong type\n\n\ndef func1(x: Callable[P, int], y: Callable[P, int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\ndef x_y(x: int, y: str) -> int:\n raise NotImplementedError\n\n\ndef y_x(y: int, x: str) -> int:\n raise NotImplementedError\n\n\nf2 = func1(x_y, x_y)\nassert_type(f2(1, \"\"), bool)\nassert_type(f2(y=\"\", x=1), bool)\n\nf3 = func1(x_y, y_x) # E?: Could return (a: int, b: str, /) -> bool\n# (a callable with two positional-only parameters)\n# This works because both callables have types that are\n# behavioral subtypes of Callable[[int, str], int]\n# Also OK for type checkers to reject this.\n\n\ndef keyword_only_x(*, x: int) -> int:\n raise NotImplementedError\n\n\ndef keyword_only_y(*, y: int) -> int:\n raise NotImplementedError\n\n\nfunc1(keyword_only_x, keyword_only_y) # E\n\n\nU = TypeVar(\"U\")\n\n\nclass Y(Generic[U, P]):\n f: Callable[P, str]\n prop: U\n\n def __init__(self, f: Callable[P, str], prop: U) -> None:\n self.f = f\n self.prop = prop\n\n\ndef callback_a(q: int, /) -> str:\n raise NotImplementedError\n\n\ndef func(x: int) -> None:\n y1 = Y(callback_a, x)\n assert_type(y1, Y[int, [int]])\n y2 = y1.f\n assert_type(y2, Callable[[int], str])\n\n\ndef bar(x: int, *args: bool) -> int:\n raise NotImplementedError\n\n\ndef add(x: Callable[P, int]) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\na1 = add(bar) # Should return (a: str, /, x: int, *args: bool) -> bool\nassert_type(a1(\"\", 1, False, True), bool)\nassert_type(a1(\"\", x=1), bool)\na1(1, x=1) # E\n\n\ndef remove(x: Callable[Concatenate[int, P], int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\nr1 = remove(bar) # Should return (*args: bool) -> bool\nassert_type(r1(False, True, True), bool)\nassert_type(r1(), bool)\nr1(1) # E\n\n\ndef transform(\n x: Callable[Concatenate[int, P], int]\n) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\nt1 = transform(bar) # Should return (a: str, /, *args: bool) -> bool\nassert_type(t1(\"\", True, False, True), bool)\nassert_type(t1(\"\"), bool)\nt1(1) # E\n\n\ndef expects_int_first(x: Callable[Concatenate[int, P], int]) -> None:\n ...\n\n\n@expects_int_first # E\ndef one(x: str) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef two(*, x: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef three(**kwargs: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # OK\ndef four(*args: int) -> int:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_04.py","code":"\"\"\"\nTests the handling of a ParamSpec specialization.\n\"\"\"\n\nfrom typing import Any, Callable, Concatenate, Generic, ParamSpec, TypeVar, cast\n\n\nT = TypeVar(\"T\")\nP1 = ParamSpec(\"P1\")\nP2 = ParamSpec(\"P2\")\n\n\nclass ClassA(Generic[T, P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\nclass ClassB(ClassA[T, P1], Generic[T, P1, P2]):\n f1: Callable[P1, int] = cast(Any, \"\")\n f2: Callable[P2, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\ndef func20(x: ClassA[int, P2]) -> str: # OK\n return \"\"\n\n\ndef func21(x: ClassA[int, Concatenate[int, P2]]) -> str: # OK\n return \"\"\n\n\ndef func22(x: ClassB[int, [int, bool], ...]) -> str: # OK\n return \"\"\n\n\ndef func23(x: ClassA[int, ...]) -> str: # OK\n return \"\"\n\n\ndef func24(x: ClassB[int, [], []]) -> str: # OK\n return \"\"\n\n\ndef func25(x: ClassA[int, int]) -> str: # E\n return \"\"\n\n\nclass ClassC(Generic[P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n\n\ndef func30(x: ClassC[[int, str, bool]]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n\n\ndef func31(x: ClassC[int, str, bool]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_05.py","code":"\"\"\"\nTests variance of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance-inference\n\n\nfrom typing import Callable, Generic, ParamSpec\n\n\nclass InvariantParamSpec[**InOutP]:\n a: Callable[InOutP, None]\n\nin_out_obj: InvariantParamSpec[object] = InvariantParamSpec[int]() # E\nin_out_int: InvariantParamSpec[int] = InvariantParamSpec[object]() # E\n\n\nclass ContravariantParamSpec[**InP]:\n def f(self, *args: InP.args, **kwargs: InP.kwargs): ...\n\nin_obj: ContravariantParamSpec[object] = ContravariantParamSpec[int]() # E\nin_int: ContravariantParamSpec[int] = ContravariantParamSpec[object]() # OK\n\n\nclass CovariantParamSpec[**OutP]:\n def f(self, fn: Callable[OutP, None]) -> None:\n raise NotImplementedError\n\n\nout_int: CovariantParamSpec[int] = CovariantParamSpec[object]() # E\nout_obj: CovariantParamSpec[object] = CovariantParamSpec[int]() # OK\n\n# cases involving keyword-only, positional-only parameters, parameter names, defaults and differing callable arities\nclass Box[T]:\n t: T\n\n def __init__(self, t: T): ...\n\n\ndef f(a: int): ...\ndef kw(*, a: int): ...\ndef pos(a: int, /): ...\ndef names(b: int): ...\ndef default(a: int = 1): ...\ndef arity(a: int, b: str): ...\n\n\nclass InitP[**P]: # contravariant\n def __init__(self, fn: Callable[P, None]): ...\n\n def usage(self) -> Callable[P, None]:\n \"\"\"infer contravariance\"\"\"\n raise NotImplementedError\n\n\n# `InitP` produces a `Callable[P, None]`, so a replacement is only safe if it\n# accepts every call form that `InitP[(a: int)]` accepts.\nin_box = Box(InitP(f))\n\nin_kw_p = InitP(kw)\nin_box.t = in_kw_p # E\nin_pos_p = InitP(pos)\nin_box.t = in_pos_p # E\nin_names_p = InitP(names)\nin_box.t = in_names_p # E\nin_default_p = InitP(default)\nin_box.t = in_default_p # OK\nin_arity_p = InitP(arity)\nin_box.t = in_arity_p # E\n\n\nclass OutitP[**P]: # covariant\n def __init__(self, fn: Callable[P, None]): ...\n\n def usage(self, fn: Callable[P, None]):\n \"\"\"infer covariance\"\"\"\n\n\n# `OutitP` consumes a `Callable[P, None]`, so the safe direction is reversed: a\n# replacement is only safe if `Callable[(a: int), None]` can be passed to it.\nout_box = Box(OutitP(f))\n\nout_kw_p = OutitP(kw)\nout_box.t = out_kw_p # OK\nout_pos_p = OutitP(pos)\nout_box.t = out_pos_p # OK\nout_names_p = OutitP(names)\nout_box.t = out_names_p # E\nout_default_p = OutitP(default)\nout_box.t = out_default_p # E\nout_arity_p = OutitP(arity)\nout_box.t = out_arity_p # E\n\n\n# old style\nP = ParamSpec(\"P\") # OK\nInP = ParamSpec(\"InP\", contravariant=True) # OK\nOutP = ParamSpec(\"OutP\", covariant=True) # OK\nInferP = ParamSpec(\"InferP\", infer_variance=True) # OK\nInvP1 = ParamSpec(\"InvP1\", covariant=True, contravariant=True) # E\nInvP2 = ParamSpec(\"InvP2\", covariant=True, infer_variance=True) # E\nInvP3 = ParamSpec(\"InvP3\", contravariant=True, infer_variance=True) # E\n\nclass InvariantParamSpecOld(Generic[P]):\n def f(self, fn: Callable[P, None]) -> Callable[P, None]: # OK\n raise NotImplementedError\n\nin_out_old: InvariantParamSpecOld[int]\nin_out_old = InvariantParamSpecOld[int]() # OK\nin_out_old = InvariantParamSpecOld[bool]() # E\nin_out_old = InvariantParamSpecOld[object]() # E\n\nclass ContravariantParamSpecOld(Generic[InP]):\n def in_f(self) -> Callable[InP, None]: # OK\n raise NotImplementedError\n\n def out_f(self, fn: Callable[InP, None]) -> None: # E\n raise NotImplementedError\n\n\nin_obj_old: ContravariantParamSpecOld[object] = ContravariantParamSpecOld[int]() # E\nin_int_old: ContravariantParamSpecOld[int] = ContravariantParamSpecOld[object]() # OK\n\n\nclass CovariantParamSpecOld(Generic[OutP]):\n def in_f(self) -> Callable[OutP, None]: # E\n raise NotImplementedError\n def out_f(self, fn: Callable[OutP, None]) -> None: # OK\n raise NotImplementedError\n\n\nout_int_old: CovariantParamSpecOld[int] = CovariantParamSpecOld[object]() # E\nout_obj_old: CovariantParamSpecOld[object] = CovariantParamSpecOld[int]() # OK\n\n\n# `infer_variance=True` on a traditional `ParamSpec`\nclass InferredContravariantParamSpecOld(Generic[InferP]):\n def in_f(self) -> Callable[InferP, None]: # OK\n raise NotImplementedError\n\n\ninfer_in_obj_old: InferredContravariantParamSpecOld[object] = InferredContravariantParamSpecOld[int]() # E\ninfer_in_int_old: InferredContravariantParamSpecOld[int] = InferredContravariantParamSpecOld[object]() # OK\n\n\nclass InferredCovariantParamSpecOld(Generic[InferP]):\n def out_f(self, fn: Callable[InferP, None]) -> None: # OK\n raise NotImplementedError\n\n\ninfer_out_int_old: InferredCovariantParamSpecOld[int] = InferredCovariantParamSpecOld[object]() # E\ninfer_out_obj_old: InferredCovariantParamSpecOld[object] = InferredCovariantParamSpecOld[int]() # OK\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_01.py","code":"\"\"\"\nTests handling of callback protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#callback-protocols\n\nfrom typing import Any, Callable, ParamSpec, Protocol, TypeVar, cast, overload\n\nInputT = TypeVar(\"InputT\", contravariant=True)\nOutputT = TypeVar(\"OutputT\", covariant=True)\n\n\nclass Proto1(Protocol):\n def __call__(self, *vals: bytes, max_len: int | None = None) -> list[bytes]:\n ...\n\n\ndef cb1_good1(*vals: bytes, max_len: int | None = None) -> list[bytes]:\n return []\n\n\ndef cb1_bad1(*vals: bytes, max_items: int | None) -> list[bytes]:\n return []\n\n\ndef cb1_bad2(*vals: bytes) -> list[bytes]:\n return []\n\n\ndef cb1_bad3(*vals: bytes, max_len: str | None) -> list[bytes]:\n return []\n\n\ncb1: Proto1 = cb1_good1 # OK\ncb1 = cb1_bad1 # E: different names\ncb1 = cb1_bad2 # E: parameter types\ncb1 = cb1_bad3 # E: default argument\n\n\nclass Proto2(Protocol):\n def __call__(self, *vals: bytes, **kwargs: str) -> None:\n pass\n\n\ndef cb2_good1(*a: bytes, **b: str):\n pass\n\n\ndef cb2_bad1(*a: bytes):\n pass\n\n\ndef cb2_bad2(*a: str, **b: str):\n pass\n\n\ndef cb2_bad3(*a: bytes, **b: bytes):\n pass\n\n\ndef cb2_bad4(**b: str):\n pass\n\n\ncb2: Proto2 = cb2_good1 # OK\n\ncb2 = cb2_bad1 # E: missing **kwargs\ncb2 = cb2_bad2 # E: parameter type\ncb2 = cb2_bad3 # E: parameter type\ncb2 = cb2_bad4 # E: missing parameter\n\n\nclass Proto3(Protocol):\n def __call__(self) -> None:\n pass\n\n\ncb3: Proto3 = cb2_good1 # OK\ncb3 = cb2_bad1 # OK\ncb3 = cb2_bad2 # OK\ncb3 = cb2_bad3 # OK\ncb3 = cb2_bad4 # OK\n\n\n# A callback protocol with other attributes.\nclass Proto4(Protocol):\n other_attribute: int\n\n def __call__(self, x: int) -> None:\n pass\n\n\ndef cb4_bad1(x: int) -> None:\n pass\n\n\nvar4: Proto4 = cb4_bad1 # E: missing attribute\n\n\nclass Proto5(Protocol):\n def __call__(self, *, a: int, b: str) -> int:\n ...\n\n\ndef cb5_good1(a: int, b: str) -> int:\n return 0\n\n\ncb5: Proto5 = cb5_good1 # OK\n\n\nclass NotProto6:\n def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]:\n return []\n\n\ndef cb6_bad1(*vals: bytes, max_len: int | None = None) -> list[bytes]:\n return []\n\n\ncb6: NotProto6 = cb6_bad1 # E: NotProto6 isn't a protocol class\n\n\nclass Proto7(Protocol[InputT, OutputT]):\n def __call__(self, inputs: InputT) -> OutputT:\n ...\n\n\nclass Class7_1:\n # Test for unannotated parameter.\n def __call__(self, inputs) -> int:\n return 5\n\n\ncb7_1: Proto7[int, int] = Class7_1() # OK\n\n\nclass Class7_2:\n # Test for parameter with type Any.\n def __call__(self, inputs: Any) -> int:\n return 5\n\n\ncb7_2: Proto7[int, int] = Class7_2() # OK\n\n\nclass Proto8(Protocol):\n @overload\n def __call__(self, x: int) -> int:\n ...\n\n @overload\n def __call__(self, x: str) -> str:\n ...\n\n def __call__(self, x: Any) -> Any:\n ...\n\n\ndef cb8_good1(x: Any) -> Any:\n return x\n\n\ndef cb8_bad1(x: int) -> Any:\n return x\n\n\ncb8: Proto8 = cb8_good1 # OK\ncb8 = cb8_bad1 # E: parameter type\n\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\", covariant=True)\n\n\nclass Proto9[**P, R](Protocol):\n other_attribute: int\n\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\ndef decorator1(f: Callable[P, R]) -> Proto9[P, R]:\n converted = cast(Proto9[P, R], f)\n converted.other_attribute = 1\n converted.other_attribute = \"str\" # E: incompatible type\n converted.xxx = 3 # E: unknown attribute\n return converted\n\n\n@decorator1\ndef cb9_good(x: int) -> str:\n return \"\"\n\n\nprint(cb9_good.other_attribute) # OK\nprint(cb9_good.other_attribute2) # E: unknown attribute\n\ncb9_good(x=3)\n\n\nclass Proto10(Protocol):\n __name__: str\n __module__: str\n __qualname__: str\n __annotations__: dict[str, Any]\n\n def __call__(self) -> None:\n ...\n\n\ndef cb10_good() -> None:\n pass\n\n\ncb10: Proto10 = cb10_good # OK\n\n\nclass Proto11(Protocol):\n def __call__(self, x: int, /, y: str) -> Any:\n ...\n\n\ndef cb11_good1(x: int, /, y: str, z: None = None) -> Any:\n raise NotImplementedError\n\n\ndef cb11_good2(x: int, y: str, z: None = None) -> Any:\n raise NotImplementedError\n\n\ndef cb11_bad1(x: int, y: str, /) -> Any:\n raise NotImplementedError\n\n\ncb11: Proto11 = cb11_good1 # OK\ncb11 = cb11_good2 # OK\ncb11 = cb11_bad1 # E: y is position-only\n\n\nclass Proto12(Protocol):\n def __call__(self, *args: Any, kwarg0: Any, kwarg1: Any) -> None:\n ...\n\n\ndef cb12_good1(*args: Any, kwarg0: Any, kwarg1: Any) -> None:\n pass\n\n\ndef cb12_good2(*args: Any, **kwargs: Any) -> None:\n pass\n\n\ndef cb12_bad1(*args: Any, kwarg0: Any) -> None:\n pass\n\n\ncb12: Proto12 = cb12_good1 # OK\ncb12 = cb12_good2 # OK\ncb12 = cb12_bad1 # E: missing kwarg1\n\n\nclass Proto13_Default(Protocol):\n # Callback with positional parameter with default arg value\n def __call__(self, path: str = ...) -> str:\n ...\n\n\nclass Proto13_NoDefault(Protocol):\n # Callback with positional parameter but no default arg value\n def __call__(self, path: str) -> str:\n ...\n\n\ndef cb13_default(path: str = \"\") -> str:\n return \"\"\n\n\ndef cb13_no_default(path: str) -> str:\n return \"\"\n\n\ncb13_1: Proto13_Default = cb13_default # OK\ncb13_2: Proto13_Default = cb13_no_default # E: no default\n\ncb13_3: Proto13_NoDefault = cb13_default # OK\ncb13_4: Proto13_NoDefault = cb13_no_default # OK\n\n\nclass Proto14_Default(Protocol):\n # Callback with keyword parameter with default arg value\n def __call__(self, *, path: str = ...) -> str:\n ...\n\n\nclass Proto14_NoDefault(Protocol):\n # Callback with keyword parameter with no default arg value\n def __call__(self, *, path: str) -> str:\n ...\n\n\ndef cb14_default(*, path: str = \"\") -> str:\n return \"\"\n\n\ndef cb14_no_default(*, path: str) -> str:\n return \"\"\n\n\ncb14_1: Proto14_Default = cb14_default # OK\ncb14_2: Proto14_Default = cb14_no_default # E: no default\ncb14_3: Proto14_NoDefault = cb14_default # OK\ncb14_4: Proto14_NoDefault = cb14_no_default # OK\n","source":"typing_tests","origin":"conformance/tests/callables_protocol.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_02.py","code":"\"\"\"\nTests the handling of class objects as implementations of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#type-and-class-objects-vs-protocols\n\n# > Variables and parameters annotated with Type[Proto] accept only concrete\n# (non-protocol) subtypes of Proto.\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Protocol\n\n\nclass Proto(Protocol):\n @abstractmethod\n def meth(self) -> int:\n ...\n\n\nclass Concrete:\n def meth(self) -> int:\n return 42\n\n\ndef fun(cls: type[Proto]) -> int:\n return cls().meth() # OK\n\n\nfun(Proto) # E\nfun(Concrete) # OK\n\n\nvar: type[Proto]\nvar = Proto # E\nvar = Concrete # OK\nvar().meth() # OK\n\n\n# > A class object is considered an implementation of a protocol if accessing\n# > all members on it results in types compatible with the protocol members.\n\n\nclass ProtoA1(Protocol):\n def method1(self, x: int) -> int:\n ...\n\n\nclass ProtoA2(Protocol):\n def method1(_self, self: Any, x: int) -> int:\n ...\n\n\nclass ConcreteA:\n def method1(self, x: int) -> int:\n return 0\n\n\npa1: ProtoA1 = ConcreteA # E: signatures don't match\npa2: ProtoA2 = ConcreteA # OK\n\n\nclass ProtoB1(Protocol):\n @property\n def prop1(self) -> int:\n ...\n\n\nclass ConcreteB:\n @property\n def prop1(self) -> int:\n return 0\n\n\npb1: ProtoB1 = ConcreteB # E\n\n\nclass ProtoC1(Protocol):\n attr1: ClassVar[int]\n\n\nclass ProtoC2(Protocol):\n attr1: int\n\n\nclass ConcreteC1:\n attr1: ClassVar[int] = 1\n\n\nclass ConcreteC2:\n attr1: int = 1\n\n\nclass CMeta(type):\n attr1: int\n\n def __init__(self, *args, **kwargs) -> None:\n self.attr1: int = 1\n\n\nclass ConcreteC3(metaclass=CMeta):\n pass\n\n\npc1: ProtoC1 = ConcreteC1 # E\npc2: ProtoC2 = ConcreteC1 # OK\npc3: ProtoC1 = ConcreteC2 # E\npc4: ProtoC2 = ConcreteC2 # E\npc5: ProtoC1 = ConcreteC3 # E?: Explicit ClassVar matching is unspecified\npc6: ProtoC2 = ConcreteC3 # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_class_objects.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_03.py","code":"\"\"\"\nTests the basic definition rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#defining-a-protocol\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Iterable, NamedTuple, Protocol, Sequence\nfrom dataclasses import dataclass\n\n\nclass SupportsClose(Protocol):\n def close(self) -> None:\n ...\n\n\nclass Resource:\n def close(self) -> None:\n pass\n\n\ndef close_all(things: Iterable[SupportsClose]) -> None:\n for t in things:\n t.close()\n\n\nf = open(\"foo.txt\")\nr = Resource()\nclose_all([f, r]) # OK\nclose_all([1]) # E: 'int' has no 'close' method\n\n\nclass Example(Protocol):\n def first(self) -> int: # This is a protocol member\n return 42\n\n @abstractmethod\n def second(self) -> int: # Method without a default implementation\n raise NotImplementedError\n\n # > Static methods, class methods, and properties are equally allowed in protocols.\n\n @staticmethod\n def third() -> int:\n ...\n\n @classmethod\n def fourth(cls) -> int:\n ...\n\n @property\n def fifth(self) -> int:\n ...\n\n\n# > To define a protocol variable, one can use PEP 526 variable annotations\n# > in the class body. Additional attributes only defined in the body of a\n# > method by assignment via self are not allowed.\n\n\nclass Template(Protocol):\n name: str # This is a protocol member\n value: int = 0 # This one too (with default)\n\n def method(self) -> None:\n self.name = \"name\" # OK\n self.temp: list[int] = [] # E: use of self variables not allowed\n\n\nclass Concrete:\n def __init__(self, name: str, value: int) -> None:\n self.name = name\n self.value = value\n\n def method(self) -> None:\n return\n\n\nvar: Template = Concrete(\"value\", 42) # OK\n\n\n# > To distinguish between protocol class variables and protocol instance\n# > variables, the special ClassVar annotation should be used as specified\n# > by PEP 526. By default, protocol variables as defined above are considered\n# > readable and writable. To define a read-only protocol variable, one can\n# > use an (abstract) property.\n\n\nclass Template2(Protocol):\n val1: ClassVar[Sequence[int]]\n\n\nclass Concrete2_Good1:\n val1: ClassVar[Sequence[int]] = [2]\n\n\nclass Concrete2_Bad1:\n ...\n\n\nclass Concrete2_Bad2:\n val1: Sequence[float] = [2]\n\n\nclass Concrete2_Bad3:\n val1: list[int] = [2]\n\n\nclass Concrete2_Bad4:\n val1: Sequence[int] = [2]\n\n\nv2_good1: Template2 = Concrete2_Good1() # OK\nv2_bad1: Template2 = Concrete2_Bad1() # E\nv2_bad2: Template2 = Concrete2_Bad2() # E\nv2_bad3: Template2 = Concrete2_Bad3() # E\nv2_bad4: Template2 = Concrete2_Bad4() # E?: Explicit ClassVar matching is unspecified\n\n\nclass Template3(Protocol):\n val1: Sequence[int]\n\n\nclass Concrete3_Good1:\n val1: Sequence[int] = [0]\n\n\nclass Concrete3_Good2:\n def __init__(self) -> None:\n self.val1: Sequence[int] = [0]\n\n\nclass Concrete3_Bad1:\n ...\n\n\nclass Concrete3_Bad2:\n val1: ClassVar[Sequence[int]] = [0]\n\n\nclass Concrete3_Bad3:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete3_Bad4:\n val1: Sequence[float] = [0]\n\n\nclass Concrete3_Bad5:\n val1: list[int] = [0]\n\n\nv3_good1: Template3 = Concrete3_Good1() # OK\nv3_bad1: Template3 = Concrete3_Bad1() # E\nv3_bad2: Template3 = Concrete3_Bad2() # E\nv3_bad3: Template3 = Concrete3_Bad3() # E\nv3_bad4: Template3 = Concrete3_Bad4() # E\nv3_bad5: Template3 = Concrete3_Bad5() # E\n\n\nclass Template4(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n\nclass Concrete4_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete4_Good2:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete4_Good3:\n val1: Sequence[float] = [0]\n\n\nclass Concrete4_Good4:\n val1: Sequence[int] = [0]\n\n\nclass Concrete4_Good5:\n val1: list[float] = [0]\n\n\nclass Concrete4_Good6(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete4_Good7:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete4_Bad1:\n def val1(self) -> Sequence[int]: # Not a property\n return [0]\n\n\nclass Concrete4_Bad2:\n ...\n\n\nv4_good1: Template4 = Concrete4_Good1() # OK\nv4_good2: Template4 = Concrete4_Good2() # OK\nv4_good3: Template4 = Concrete4_Good3() # OK\nv4_good4: Template4 = Concrete4_Good4() # OK\nv4_good5: Template4 = Concrete4_Good5() # OK\nv4_good6: Template4 = Concrete4_Good6() # OK\nv4_good7: Template4 = Concrete4_Good7() # OK\nv4_bad1: Template4 = Concrete4_Bad1() # E\nv4_bad2: Template4 = Concrete4_Bad2() # E\n\n\nclass Template5(Protocol):\n def method1(self, a: int, b: int) -> float:\n ...\n\n\nclass Concrete5_Good1:\n def method1(self, a: float, b: float) -> int:\n return 0\n\n\nclass Concrete5_Good2:\n def method1(self, *args: float, **kwargs: float) -> Any:\n return 0.0\n\n\nclass Concrete5_Good3:\n def method1(self, a, b) -> Any:\n return 0.0\n\n\nclass Concrete5_Good4:\n @classmethod\n def method1(cls, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Good5:\n @staticmethod\n def method1(a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad1:\n def method1(self, a, c) -> int:\n return 0\n\n\nclass Concrete5_Bad2:\n def method1(self, a: int, c: int) -> int:\n return 0\n\n\nclass Concrete5_Bad3:\n def method1(self, *, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad4:\n def method1(self, a: int, b: int, /) -> float:\n return 0\n\n\nclass Concrete5_Bad5:\n @staticmethod\n def method1(self, a: int, b: int) -> float:\n return 0\n\n\nv5_good1: Template5 = Concrete5_Good1() # OK\nv5_good2: Template5 = Concrete5_Good2() # OK\nv5_good3: Template5 = Concrete5_Good3() # OK\nv5_good4: Template5 = Concrete5_Good4() # OK\nv5_good5: Template5 = Concrete5_Good5() # OK\nv5_bad1: Template5 = Concrete5_Bad1() # E\nv5_bad2: Template5 = Concrete5_Bad2() # E\nv5_bad3: Template5 = Concrete5_Bad3() # E\nv5_bad4: Template5 = Concrete5_Bad4() # E\nv5_bad5: Template5 = Concrete5_Bad5() # E\n\n\nclass Template6(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n ...\n\n\nclass Concrete6_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n pass\n\n\nclass Concrete6_Good2:\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete6_Good3:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete6_Bad1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete6_Bad2(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=True)\nclass Concrete6_Bad3:\n val1: Sequence[float] = (0,)\n\n\nv6_good1: Template6 = Concrete6_Good1() # OK\nv6_good2: Template6 = Concrete6_Good2() # OK\nv6_good3: Template6 = Concrete6_Good3() # OK\nv6_bad1: Template6 = Concrete6_Bad1() # E\nv6_bad2: Template6 = Concrete6_Bad2() # E: named tuple is immutable\nv6_bad3: Template6 = Concrete6_Bad3() # E: dataclass is frozen\n\n\n# The specification leaves two possible interpretations of a ClassVar protocol\n# member. One interpretation requires the implementing attribute to be explicitly\n# declared with ClassVar. The other interpretation imposes only structural\n# requirements: the attribute must be readable and writable on the class object\n# and readable on instances of the class. Both interpretations therefore require\n# the following assignments to be rejected.\n\n\nclass Template7(Protocol):\n val1: ClassVar[int]\n\n\nclass Concrete7_Bad1:\n def __init__(self) -> None:\n self.val1: int = 42\n\n\nclass Concrete7Meta(type):\n val1: int = 42\n\n\nclass Concrete7_Bad2(metaclass=Concrete7Meta):\n pass\n\n\nv7_bad1: Template7 = Concrete7_Bad1() # E: val1 is not readable on the class object\nv7_bad2: Template7 = Concrete7_Bad2() # E: val1 is not readable on instances\n","source":"typing_tests","origin":"conformance/tests/protocols_definition.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_04.py","code":"\"\"\"\nTests the handling of explicit protocol classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#explicitly-declaring-implementation\n\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar, Protocol\n\n\nclass PColor(Protocol):\n @abstractmethod\n def draw(self) -> str:\n ...\n\n def complex_method(self) -> int:\n return 1\n\n\nclass NiceColor(PColor):\n def draw(self) -> str:\n return \"deep blue\"\n\n\nclass BadColor(PColor):\n def draw(self) -> str:\n return super().draw() # E: no default implementation\n\n\nclass ImplicitColor: # Note no 'PColor' base here\n def draw(self) -> str:\n return \"probably gray\"\n\n def complex_method(self) -> int:\n return 0\n\n\nv1: PColor = NiceColor() # OK\nv2: PColor = ImplicitColor() # OK\n\n\nclass RGB(Protocol):\n rgb: tuple[int, int, int]\n other: int\n\n @abstractmethod\n def intensity(self) -> int:\n return 1\n\n def transparency(self) -> int:\n ...\n\n\nclass Point(RGB):\n def __init__(self, red: int, green: int, blue: str) -> None:\n self.rgb = red, green, blue # E: 'blue' must be 'int'\n self.other = 0\n\n\np = Point(0, 0, \"\") # E: Cannot instantiate abstract class\n\n\nclass Proto1(Protocol):\n cm1: ClassVar[int]\n cm2: ClassVar[int] = 0\n\n im1: int\n im2: int = 2\n im3: int\n\n def __init__(self):\n self.im3 = 3\n\n\nclass Proto2(Protocol):\n cm10: int\n\n\nclass Proto3(Proto2, Protocol):\n cm11: int\n\n\nclass Concrete1(Proto1):\n def __init__(self):\n self.im1 = 1\n self.im3 = 3\n\n\nc1 = Concrete1() # E: cannot instantiate abstract class\n\n\nclass Concrete2(Proto1):\n cm1 = 3\n im1 = 0\n\n\nc2 = Concrete2()\n\n\nclass Concrete3(Proto1, Proto3):\n cm1 = 3\n\n def __init__(self):\n self.im1 = 0\n self.cm10 = 10\n self.cm11 = 11\n\n\nc3 = Concrete3()\n\n\nclass Concrete4(Proto1, Proto3):\n cm1 = 3\n cm10 = 3\n\n def __init__(self):\n self.im1 = 3\n self.im10 = 10\n self.cm11 = 3\n\n\nc4 = Concrete4()\n\n\nclass Proto5(Protocol):\n def method1(self) -> int:\n ...\n\n\nclass Concrete5(Proto5):\n pass\n\n\nc5 = Concrete5() # E: cannot instantiate abstract class\n\n\nclass Proto6(Protocol):\n x: int\n\n\nclass Mixin:\n x = 3\n\n\nclass Concrete6(Mixin, Proto6):\n pass\n\n\nclass Proto7(Protocol):\n @abstractmethod\n def method1(self):\n ...\n\n\nclass Mixin7(Proto7, ABC):\n def method1(self) -> None:\n pass\n\n\nclass Concrete7A(Proto7):\n pass\n\n\nc7a = Concrete7A() # E: cannot instantiate abstract class\n\n\nclass Concrete7B(Mixin7, Proto7):\n pass\n\n\nc7b = Concrete7B()\n","source":"typing_tests","origin":"conformance/tests/protocols_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_05.py","code":"\"\"\"\nTests the handling of generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\n\nfrom typing import Callable, Generic, Iterator, Protocol, Self, TypeVar, assert_type\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Iterable(Protocol[T_co]):\n def __iter__(self) -> Iterator[T_co]:\n ...\n\n\n# > Protocol[T, S, ...] is allowed as a shorthand for Protocol, Generic[T, S, ...].\n# In particular, the implicit order of type parameters is dictated by\n# the order in which they appear in the `Protocol` subscript.\n\n\nclass Proto1(Iterable[T_co], Protocol[S, T_co]):\n def method1(self, x: S) -> S:\n ...\n\n\nclass Concrete1:\n def __iter__(self) -> Iterator[int]:\n return (x for x in [1, 2, 3])\n\n def method1(self, x: str) -> str:\n return \"\"\n\n\np1: Proto1[str, int] = Concrete1() # OK\np2: Proto1[int, str] = Concrete1() # E: incompatible type\n\n\n# > It is an error to combine the shorthand with Generic[T, S, ...]\nclass Proto2(Protocol[T_co], Generic[T_co]): # E\n ...\n\n\n# > User-defined generic protocols support explicitly declared variance.\nclass Box(Protocol[T_co]):\n def content(self) -> T_co:\n ...\n\n\ndef func1(box_int: Box[int], box_float: Box[float]):\n v1: Box[float] = box_int # OK\n v2: Box[int] = box_float # E\n\n\nclass Sender(Protocol[T_contra]):\n def send(self, data: T_contra) -> int:\n return 0\n\n\ndef func2(sender_int: Sender[int], sender_float: Sender[float]):\n v1: Sender[int] = sender_float # OK\n v2: Sender[float] = sender_int # E\n\n\nclass AttrProto(Protocol[T]):\n attr: T\n\n\ndef func3(attr_int: AttrProto[int], attr_float: AttrProto[float]):\n v1: AttrProto[float] = attr_int # E\n v2: AttrProto[int] = attr_float # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n# > The self-types in protocols follow the rules for other methods.\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n# > In addition, the first argument in an instance method can be annotated\n# > with a type variable. In this case the return type may use the same\n# > type variable, thus making that method a generic function.\n\n\nT_bounded = TypeVar(\"T_bounded\", bound=\"HasParent\")\n\n\nclass HasParent(Protocol):\n def get_parent(self: T_bounded) -> T_bounded:\n ...\n\n\nGenericHasParent = TypeVar(\"GenericHasParent\", bound=HasParent)\n\n\ndef generic_get_parent(n: GenericHasParent) -> GenericHasParent:\n return n.get_parent()\n\n\nclass ConcreteHasParent:\n def get_parent(self) -> Self:\n return self\n\n\nparent = generic_get_parent(ConcreteHasParent()) # OK\nassert_type(parent, ConcreteHasParent)\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > `Self` is valid within Protocols, similar to its use in classes:\n\n\nclass HasParentProperty(Protocol):\n @property\n def parent(self) -> Self:\n ...\n\n\nclass ConcreteParentProperty:\n @property\n def parent(self) -> Self:\n return self\n\n\nclass InvalidParentProperty:\n @property\n def parent(self) -> HasParentProperty:\n return ConcreteParentProperty()\n\n\nhp1: HasParentProperty = ConcreteParentProperty() # OK\nhp2: HasParentProperty = InvalidParentProperty() # E\n\n\n\nclass HasMethod(Protocol):\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n ...\n\n\nclass ConcreteHasMethod:\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n return \"\"\n\n\nclass InvalidHasMethod:\n def m(self, item: int, callback: Callable[[int], str]) -> str:\n return \"\"\n\n\nhm1: HasMethod = ConcreteHasMethod() # OK\nhm2: HasMethod = InvalidHasMethod() # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > Checking a class for assignability to a protocol: If a protocol uses `Self`\n# > in methods or attribute annotations, then a class `Foo` is assignable\n# > to the protocol if its corresponding methods and attribute annotations use\n# > either `Self` or `Foo` or any of `Foo`'s subclasses.\n\n\nclass HasGreaterThan(Protocol):\n def __gt__(self, other: Self) -> bool:\n ...\n\n\nclass ConcreteGreaterThan1:\n def __gt__(self, other: Self) -> bool:\n return False\n\n\nclass ConcreteGreaterThan2:\n def __gt__(self, other: \"ConcreteGreaterThan2\") -> bool:\n return False\n\n\nclass InvalidGreaterThan:\n def __gt__(self, other: int) -> bool:\n return False\n\n\nhg1: HasGreaterThan = ConcreteGreaterThan1() # OK\nhg2: HasGreaterThan = ConcreteGreaterThan2() # OK\nhg3: HasGreaterThan = InvalidGreaterThan() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_generic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_06.py","code":"\"\"\"\nTests merging and extending of protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#merging-and-extending-protocols\n\nfrom abc import abstractmethod\nfrom typing import Protocol\nfrom collections.abc import Sized\n\n\nclass SizedAndClosable1(Sized, Protocol):\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable2(Protocol):\n def __len__(self) -> int:\n ...\n\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable3(SizedAndClosable1): # Note: not a protocol\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete1:\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete2:\n def close(self) -> None:\n pass\n\n\ns1: SizedAndClosable1 = SCConcrete1() # OK\ns2: SizedAndClosable2 = SCConcrete1() # OK\ns3: SizedAndClosable1 = SizedAndClosable3() # OK\ns4: SizedAndClosable2 = SizedAndClosable3() # OK\ns5: Sized = SCConcrete1() # OK\n\ns6: SizedAndClosable1 = SCConcrete2() # E: doesn't implement `__len__`\ns7: SizedAndClosable2 = SCConcrete2() # E: doesn't implement `__len__`\ns8: SizedAndClosable3 = SCConcrete2() # E: SizedAndClosable3 is not a protocol\n\n\ndef func1(s1: SizedAndClosable1, s2: SizedAndClosable2):\n # > The two definitions of SizedAndClosable are equivalent.\n v1: SizedAndClosable2 = s1\n v2: SizedAndClosable1 = s2\n\n\n# > If Protocol is included in the base class list, all the other base classes\n# > must be protocols.\n\n\nclass BadProto(SizedAndClosable3, Protocol): # E: SizedAndClosable3 is not a protocol\n ...\n\n\n# > Without this base, the class is “downgraded” to a regular ABC that\n# > cannot be used with structural subtyping.\nclass SizedAndClosable4(SizedAndClosable1):\n def __len__(self) -> int:\n return 0\n\n @abstractmethod\n def close(self) -> None:\n raise NotImplementedError\n\n\nx = SizedAndClosable4() # E: cannot instantiate abstract class\ny: SizedAndClosable4 = SCConcrete1() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_merging.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_07.py","code":"\"\"\"\nTests the handling of modules as the implementation of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#modules-as-implementations-of-protocols\n\n# > A module object is accepted where a protocol is expected if the public\n# > interface of the given module is compatible with the expected protocol.\n\nimport _protocols_modules1\nimport _protocols_modules2\nfrom typing import Protocol\n\n\nclass Options1(Protocol):\n timeout: int\n one_flag: bool\n other_flag: bool\n\n\nclass Options2(Protocol):\n timeout: str\n\n\nop1: Options1 = _protocols_modules1 # OK\nop2: Options2 = _protocols_modules1 # E\n\n\nclass Reporter1(Protocol):\n def on_error(self, x: int) -> None:\n ...\n\n def on_success(self) -> None:\n ...\n\n\nclass Reporter2(Protocol):\n def on_error(self, x: int) -> int:\n ...\n\n\nclass Reporter3(Protocol):\n def not_implemented(self, x: int) -> int:\n ...\n\n\nrp1: Reporter1 = _protocols_modules2 # OK\nrp2: Reporter2 = _protocols_modules2 # E\nrp3: Reporter3 = _protocols_modules2 # E\n","source":"typing_tests","origin":"conformance/tests/protocols_modules.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_08.py","code":"\"\"\"\nTests the handling of recursive protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#recursive-protocols\n\n\nfrom typing import Generic, Iterable, Never, Protocol, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Traversable(Protocol):\n def leaves(self) -> Iterable[\"Traversable\"]:\n ...\n\n\nclass SimpleTree:\n def leaves(self) -> list[\"SimpleTree\"]:\n return []\n\n\nroot: Traversable = SimpleTree() # OK\n\n\nclass Tree(Generic[T]):\n def leaves(self) -> list[\"Tree[T]\"]:\n return []\n\n\ndef walk(graph: Traversable) -> None:\n pass\n\n\ntree: Tree[float] = Tree()\nwalk(tree) # OK\n\n\nclass ProtoA(Protocol[T_co, T_contra]):\n def method1(self) -> \"ProtoA[T_co, T_contra]\":\n ...\n\n @classmethod\n def method2(cls, value: T_contra) -> None:\n ...\n\n\nclass ProtoB(Protocol[T_co, T_contra]):\n def method3(self) -> ProtoA[T_co, T_contra]:\n ...\n\n\nclass ImplA:\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls, value: int) -> None:\n pass\n\n\nclass ImplB:\n def method3(self) -> ImplA:\n return ImplA()\n\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls: type[ProtoB[object, T]], value: list[T]) -> None:\n pass\n\n\ndef func1(x: ProtoA[Never, T]) -> T:\n raise NotImplementedError\n\n\nv1 = func1(ImplB())\nassert_type(v1, list[int])\n","source":"typing_tests","origin":"conformance/tests/protocols_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_09.py","code":"\"\"\"\nTests the handling of the @runtime_checkable decorator for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#runtime-checkable-decorator-and-narrowing-types-by-isinstance\n\n# > A protocol can be used as a second argument in isinstance() and\n# > issubclass() only if it is explicitly opt-in by @runtime_checkable decorator.\n\nfrom typing import Any, Protocol, runtime_checkable\n\n\nclass Proto1(Protocol):\n name: str\n\n\n@runtime_checkable\nclass Proto2(Protocol):\n name: str\n\n\ndef func1(a: Any):\n if isinstance(a, Proto1): # E: not runtime_checkable\n return\n\n if isinstance(a, Proto2): # OK\n return\n\n\n# > isinstance() can be used with both data and non-data protocols, while\n# > issubclass() can be used only with non-data protocols.\n\n\n@runtime_checkable\nclass DataProtocol(Protocol):\n name: str\n\n def method1(self) -> int:\n ...\n\n\n@runtime_checkable\nclass NonDataProtocol(Protocol):\n def method1(self) -> int:\n ...\n\n\ndef func2(a: Any):\n if isinstance(a, DataProtocol): # OK\n return\n\n if isinstance(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, DataProtocol): # E\n return\n\n if issubclass(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, (NonDataProtocol, DataProtocol)): # E\n return\n\n\n# > Type checkers should reject an isinstance() or issubclass() call if there\n# > is an unsafe overlap between the type of the first argument and the protocol.\n\n\n@runtime_checkable\nclass Proto3(Protocol):\n def method1(self, a: int) -> int:\n ...\n\n\nclass Concrete3A:\n def method1(self, a: str) -> None:\n pass\n\n\nclass Concrete3B:\n method1: int = 1\n\n\ndef func3():\n if isinstance(Concrete3A(), Proto2): # OK\n pass\n\n if isinstance(Concrete3A(), Proto3): # E: unsafe overlap\n pass\n\n if isinstance(Concrete3B(), (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n\n if issubclass(Concrete3A, (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n","source":"typing_tests","origin":"conformance/tests/protocols_runtime_checkable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_10.py","code":"\"\"\"\nTests the handling of annotated \"self\" parameters in a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n\nfrom typing import Generic, Protocol, Self, TypeVar\n\n\nC = TypeVar(\"C\", bound=\"Copyable\")\n\n\nclass Copyable(Protocol):\n def copy(self: C) -> C:\n return self\n\n\nclass One:\n def copy(self) -> \"One\":\n return One()\n\n\nT = TypeVar(\"T\", bound=\"Other\")\n\n\nclass Other:\n def copy(self: T) -> T:\n return self\n\n\nc: Copyable\nc = One() # OK\nc = Other() # OK\n\n\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT2_co = TypeVar(\"T2_co\", covariant=True)\n\n\nclass P1Parent(Protocol[T2_co]):\n def f0(self, /) -> Self:\n ...\n\n\nclass P1Child(P1Parent[T2_co], Protocol[T2_co]):\n ...\n\n\nclass C1(Generic[T1_co]):\n def f0(self, /) -> Self:\n return self\n\n\na1: P1Parent[str] = C1[str]()\nb1: P1Child[str] = C1[str]()\n\n\nclass P2Parent(Protocol[T1_co]):\n def f0(self, right: Self, /) -> \"P2Parent[T1_co]\":\n return right\n\n\nclass P2Child(P2Parent[T1_co], Protocol[T1_co]):\n ...\n\n\nclass C2(Generic[T2_co]):\n def f0(self, other: Self) -> \"C2[T2_co]\":\n return other\n\n\na2: P2Parent[str] = C2[str]() # OK\nb2: P2Child[str] = C2[str]() # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_self.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_11.py","code":"\"\"\"\nTests subtyping rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#subtyping-relationships-with-other-types\n\n# > Protocols cannot be instantiated.\n\nfrom typing import Hashable, Iterable, Protocol, Sequence, TypeVar\n\n\nclass Proto1(Protocol):\n pass\n\n\np1 = Proto1() # E: protocol cannot be instantiated\n\n\n# > A protocol is never a subtype of a concrete type.\n\n# > A concrete type X is a subtype of protocol P if and only if X implements\n# > all protocol members of P with compatible types. In other words, subtyping\n# > with respect to a protocol is always structural.\n\n\nclass Proto2(Protocol):\n def method1(self) -> None:\n ...\n\n\nclass Concrete2:\n def method1(self) -> None:\n pass\n\n\ndef func1(p2: Proto2, c2: Concrete2):\n v1: Proto2 = c2 # OK\n v2: Concrete2 = p2 # E\n\n\n# > A protocol P1 is a subtype of another protocol P2 if P1 defines all\n# > protocol members of P2 with compatible types.\n\n\nclass Proto3(Protocol):\n def method1(self) -> None:\n ...\n\n def method2(self) -> None:\n ...\n\n\ndef func2(p2: Proto2, p3: Proto3):\n v1: Proto2 = p3 # OK\n v2: Proto3 = p2 # E\n\n\n# > Generic protocols follow the rules for generic abstract classes, except\n# > for using structural compatibility instead of compatibility defined by\n# > inheritance relationships.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n\nclass Proto4(Protocol[S, T]):\n def method1(self, a: S, b: T) -> tuple[S, T]:\n ...\n\n\nclass Proto5(Protocol[T]):\n def method1(self, a: T, b: T) -> tuple[T, T]:\n ...\n\n\ndef func3(p4_int: Proto4[int, int], p5_int: Proto5[int]):\n v1: Proto4[int, int] = p5_int # OK\n v2: Proto5[int] = p4_int # OK\n v3: Proto4[int, float] = p5_int # E\n v4: Proto5[float] = p4_int # E\n\n\nS_co = TypeVar(\"S_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Proto6(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\nclass Proto7(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\ndef func4(p6: Proto6[float, float]):\n v1: Proto7[object, int] = p6 # OK\n v2: Proto7[float, float] = p6 # OK\n v3: Proto7[complex, int] = p6 # OK\n\n v4: Proto7[int, float] = p6 # E\n v5: Proto7[float, object] = p6 # E\n\n\n# > Unions of protocol classes behaves the same way as for non-protocol classes.\n\n\nclass SupportsExit(Protocol):\n def exit(self) -> int:\n ...\n\n\nclass SupportsQuit(Protocol):\n def quit(self) -> int | None:\n ...\n\n\ndef finish(task: SupportsExit | SupportsQuit) -> int:\n return 0\n\n\nclass DefaultJob:\n def quit(self) -> int:\n return 0\n\n\nfinish(DefaultJob()) # OK\n\n\n# > One can use multiple inheritance to define an intersection of protocols.\n\n\nclass HashableFloats(Iterable[float], Hashable, Protocol):\n pass\n\n\ndef cached_func(args: HashableFloats) -> float:\n return 0.0\n\n\ncached_func((1, 2, 3)) # OK, tuple is both hashable and iterable\n","source":"typing_tests","origin":"conformance/tests/protocols_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_12.py","code":"\"\"\"\nTests type variable variance inference for generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\nfrom typing import Protocol, TypeVar\nfrom typing_extensions import ParamSpec\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", bound=int)\nT3 = TypeVar(\"T3\", bytes, str)\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT1_contra = TypeVar(\"T1_contra\", contravariant=True)\nP = ParamSpec(\"P\", contravariant=True)\nR = TypeVar(\"R\", covariant=True)\n\n# > Type checkers will warn if the inferred variance is different from the\n# > declared variance.\n\n\nclass AnotherBox(Protocol[T1]): # E: T should be covariant\n def content(self) -> T1:\n ...\n\n\nclass Protocol1(Protocol[T1, T2, T3]): # OK\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1 | T2:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n def m4(self) -> T3:\n ...\n\n\nclass Protocol2(Protocol[T1, T2, T3]): # E: T3 should be contravariant\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n\nclass Protocol3(Protocol[T1_co]):\n def m1(self) -> None:\n pass\n\n\nclass Protocol4(Protocol[T1]): # E: T1 should be contravariant\n def m1(self, p0: T1) -> None:\n ...\n\n\nclass Protocol5(Protocol[T1_co]): # E[covariant_in_input+]\n def m1(self, p0: T1_co) -> None: # E[covariant_in_input+]\n ...\n\n\nclass Protocol6(Protocol[T1]): # E: T1 should be covariant\n def m1(self) -> T1:\n ...\n\n\nclass Protocol7(Protocol[T1_contra]): # E[contravariant_in_output+]\n def m1(self) -> T1_contra: # E[contravariant_in_output+]\n ...\n\n\nclass Protocol8(Protocol[T1]): # OK\n def m1(self) -> T1:\n ...\n\n def m2(self, p1: T1) -> None:\n pass\n\n\nclass Callback(Protocol[P, R]): # OK\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\nclass Protocol9(Protocol[T1_co]): # OK\n @property\n def prop1(self) -> T1_co:\n ...\n\n\nclass Protocol10(Protocol[T1_co]): # OK\n def m1(self) -> type[T1_co]:\n ...\n\n\nclass Protocol11(Protocol[T1]): # OK\n x: T1 | None\n\n\nclass Protocol12(Protocol[T1]): # E: T1 should be covariant\n # __init__ method is exempt from variance calculations.\n def __init__(self, x: T1) -> None:\n ...\n\n\nclass Protocol13(Protocol[T1_contra]): # OK\n def m1(self: \"Protocol13[T1_contra]\", x: T1_contra) -> None:\n ...\n\n @classmethod\n def m2(cls: \"type[Protocol13[T1_contra]]\") -> None:\n ...\n\n\nclass Protocol14(Protocol[T1]): # OK\n def m1(self) -> list[T1]:\n ...\n","source":"typing_tests","origin":"conformance/tests/protocols_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_01.py","code":"\"\"\"\nTests typing.ReadOnly qualifier introduced in PEP 705.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Annotated, NotRequired, Required, TypedDict\nfrom typing_extensions import ReadOnly\n\n\n# > The ``typing.ReadOnly`` type qualifier is used to indicate that an item\n# > declared in a ``TypedDict`` definition may not be mutated (added, modified,\n# > or removed).\n\n\nclass Band(TypedDict):\n name: str\n members: ReadOnly[list[str]]\n\n\nb1: Band = {\"name\": \"blur\", \"members\": []}\n\nb1[\"name\"] = \"Blur\" # OK\nb1[\"members\"] = [\"Damon Albarn\"] # E\nb1[\"members\"].append(\"Damon Albarn\") # OK\n\n\n# > The :pep:`alternative functional syntax <589#alternative-syntax>` for\n# > TypedDict also supports the new type qualifier.\n\nBand2 = TypedDict(\"Band2\", {\"name\": str, \"members\": ReadOnly[list[str]]})\n\nb2: Band2 = {\"name\": \"blur\", \"members\": []}\n\nb2[\"name\"] = \"Blur\" # OK\nb2[\"members\"] = [\"Damon Albarn\"] # E\nb2[\"members\"].append(\"Damon Albarn\") # OK\n\n\n# > ``ReadOnly[]`` can be used with ``Required[]``, ``NotRequired[]`` and\n# > ``Annotated[]``, in any nesting order.\n\n\nclass Movie1(TypedDict):\n title: ReadOnly[Required[str]] # OK\n year: ReadOnly[NotRequired[Annotated[int, \"\"]]] # OK\n\n\nm1: Movie1 = {\"title\": \"\", \"year\": 1991}\nm1[\"title\"] = \"\" # E\nm1[\"year\"] = 1992 # E\n\n\nclass Movie2(TypedDict):\n title: Required[ReadOnly[str]] # OK\n year: Annotated[NotRequired[ReadOnly[int]], \"\"] # OK\n\n\nm2: Movie2 = {\"title\": \"\", \"year\": 1991}\nm2[\"title\"] = \"\" # E\nm2[\"year\"] = 1992 # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_02.py","code":"\"\"\"\nTests type consistency rules for TypedDict with ReadOnly items.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Any, Collection, NotRequired, Required, TypedDict\nfrom typing_extensions import ReadOnly\n\n# > A TypedDict type ``A`` is consistent with TypedDict ``B`` if ``A`` is\n# > structurally compatible with ``B``. This is true if and only if all of\n# > the following are satisfied:\n\n# > For each item in ``B``, ``A`` has the corresponding key, unless the item\n# > in ``B`` is read-only, not required, and of top value type\n# > (``ReadOnly[NotRequired[object]]``).\n\n\nclass A1(TypedDict):\n x: Required[int]\n\n\nclass B1(TypedDict):\n x: Required[int]\n y: NotRequired[str]\n\n\nclass C1(TypedDict):\n x: Required[int]\n y: ReadOnly[NotRequired[str]]\n\n\ndef func1(a: A1, b: B1, c: C1):\n v1: A1 = b # OK\n v2: A1 = c # OK\n\n v3: B1 = a # E\n v4: B1 = c # E\n\n v5: C1 = a # E\n v6: C1 = b # OK\n\n\n# > For each item in ``B``, if ``A`` has the corresponding key, the\n# > corresponding value type in ``A`` is consistent with the value type in ``B``.\n\n# (This is the same rule that applies to TypedDicts without read-only items,\n# so we will skip this redundant test.)\n\n# > For each non-read-only item in ``B``, its value type is consistent with\n# > the corresponding value type in ``A``.\n\n# (This is the same rule that applies to TypedDicts without read-only items,\n# so we will skip this redundant test.)\n\n# > For each required key in ``B``, the corresponding key is required in ``A``.\n\n# (This is the same rule that applies to TypedDicts without read-only items,\n# so we will skip this redundant test.)\n\n# > For each non-required key in ``B``, if the item is not read-only in ``B``,\n# > the corresponding key is not required in ``A``.\n\n\nclass A2(TypedDict):\n x: NotRequired[ReadOnly[str]]\n\n\nclass B2(TypedDict):\n x: NotRequired[str]\n\n\nclass C2(TypedDict):\n x: Required[str]\n\n\ndef func2(a: A2, b: B2, c: C2):\n v1: A2 = b # OK\n v2: A2 = c # OK\n\n v3: B2 = a # E\n v4: B2 = c # E\n\n v5: C2 = a # E\n v6: C2 = b # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_03.py","code":"\"\"\"\nTests inheritance rules involving typing.ReadOnly.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Collection, NotRequired, Required, TypedDict\nfrom typing_extensions import ReadOnly\n\n# > Subclasses can redeclare read-only items as non-read-only, allowing them\n# > to be mutated.\n\n\nclass NamedDict(TypedDict):\n name: ReadOnly[str]\n\n\nclass Album1(NamedDict):\n name: str\n year: int\n\n\na1: Album1 = {\"name\": \"Flood\", \"year\": 1990}\na1[\"year\"] = 1973 # OK\na1[\"name\"] = \"Dark Side Of The Moon\" # OK\n\n\n# > If a read-only item is not redeclared, it remains read-only.\n\n\nclass Album2(NamedDict):\n year: int\n\n\na2: Album2 = {\"name\": \"Flood\", \"year\": 1990}\na2[\"name\"] = \"Dark Side Of The Moon\" # E\n\n\n# > Subclasses can narrow value types of read-only items.\n\n\nclass AlbumCollection(TypedDict):\n albums: ReadOnly[Collection[Album1]]\n alt: ReadOnly[list[str | int]]\n\n\nclass RecordShop(AlbumCollection):\n name: str\n albums: ReadOnly[list[Album1]] # OK\n alt: ReadOnly[list[str]] # E\n\n\n# > Subclasses can require items that are read-only but not required in the\n# > superclass.\n\n\nclass OptionalName(TypedDict):\n name: ReadOnly[NotRequired[str]]\n\n\nclass RequiredName(OptionalName):\n name: ReadOnly[Required[str]] # OK\n\n\nd: RequiredName = {} # E\n\n\n# > Subclasses can combine these rules.\n\n\nclass OptionalIdent(TypedDict):\n ident: ReadOnly[NotRequired[str | int]]\n\n\nclass User(OptionalIdent):\n ident: str # Required, mutable, and not an int\n\n\nu: User\nu = {\"ident\": \"\"} # OK\nu[\"ident\"] = \"\" # OK\nu[\"ident\"] = 3 # E\nu = {\"ident\": 3} # E\nu = {} # E\n\n\nclass F1(TypedDict):\n a: Required[int]\n b: ReadOnly[NotRequired[int]]\n c: ReadOnly[Required[int]]\n\n\nclass F3(F1):\n a: ReadOnly[int] # E\n\n\nclass F4(F1):\n a: NotRequired[int] # E\n\n\nclass F5(F1):\n b: ReadOnly[Required[int]] # OK\n\n\nclass F6(F1):\n c: ReadOnly[NotRequired[int]] # E\n\n\nclass TD_A1(TypedDict):\n x: int\n y: ReadOnly[int]\n\n\nclass TD_A2(TypedDict):\n x: float\n y: ReadOnly[float]\n\n\nclass TD_A(TD_A1, TD_A2): ... # E: x is incompatible\n\n\nclass TD_B1(TypedDict):\n x: ReadOnly[NotRequired[int]]\n y: ReadOnly[Required[int]]\n\n\nclass TD_B2(TypedDict):\n x: ReadOnly[Required[int]]\n y: ReadOnly[NotRequired[int]]\n\n\nclass TD_B(TD_B1, TD_B2): ... # E: x is incompatible\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_04.py","code":"\"\"\"\nTests the use of unpacked TypedDicts with read-only items when used to annotate\na **kwargs parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Protocol, TypedDict, Unpack\nfrom typing_extensions import ReadOnly\n\n# > :pep:`692` introduced ``Unpack`` to annotate ``**kwargs`` with a\n# > ``TypedDict``. Marking one or more of the items of a ``TypedDict`` used\n# > in this way as read-only will have no effect on the type signature of\n# > the method. However, it *will* prevent the item from being modified in\n# > the body of the function.\n\n\nclass Args(TypedDict):\n key1: int\n key2: str\n\n\nclass ReadOnlyArgs(TypedDict):\n key1: ReadOnly[int]\n key2: ReadOnly[str]\n\n\nclass Function(Protocol):\n def __call__(self, **kwargs: Unpack[Args]) -> None: ...\n\n\ndef impl(**kwargs: Unpack[ReadOnlyArgs]) -> None:\n kwargs[\"key1\"] = 3 # E\n\n\nfn: Function = impl # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_05.py","code":"\"\"\"\nTests inheritance rules involving the update method for TypedDicts\nthat contain read-only items.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Never, NotRequired, TypedDict\nfrom typing_extensions import ReadOnly\n\n# > In addition to existing type checking rules, type checkers should error if\n# > a TypedDict with a read-only item is updated with another TypedDict that\n# > declares that key.\n\n\nclass A(TypedDict):\n x: ReadOnly[int]\n y: int\n\n\na1: A = {\"x\": 1, \"y\": 2}\na2: A = {\"x\": 3, \"y\": 4}\na1.update(a2) # E\n\n# > Unless the declared value is of bottom type (:data:`~typing.Never`).\n\n\nclass B(TypedDict):\n x: NotRequired[Never]\n y: ReadOnly[int]\n\n\ndef update_a(a: A, b: B) -> None:\n a.update(b) # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_update.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"required-notrequired","pep":"655","introduced_in":"3.11","form":"modern","file":"required-notrequired/modern_01.py","code":"\"\"\"\nTests the Required and NotRequired special forms.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#required-and-notrequired\n\nfrom typing import Annotated, NotRequired, Required, TypedDict\n\n\n# Required and NotRequired are valid only within a TypedDict.\nclass NotTypedDict:\n x: Required[int] # E: Required not allowed in this context\n\n\ndef func1(\n x: NotRequired[int], # E: NotRequired not allowed in this context\n) -> None:\n pass\n\n\nclass TD1(TypedDict, total=False):\n a: int\n\n\nclass TD2(TD1, total=True):\n b: int\n\n\nclass TD3(TypedDict):\n a: NotRequired[int]\n b: Required[int]\n\n\nclass TD4(TypedDict, total=False):\n a: int\n b: Required[int]\n\n\nclass TD5(TypedDict, total=True):\n a: NotRequired[int]\n b: int\n\n\ntd3: TD3 = {\"b\": 0}\ntd4: TD4 = {\"b\": 0}\ntd5: TD5 = {\"b\": 0}\n\n# These are all equivalent types, so they should be\n# bidirectionally type compatible.\ntd3 = td4\ntd3 = td5\ntd4 = td3\ntd4 = td5\ntd5 = td3\ntd5 = td4\n\n\nclass TD6(TypedDict):\n a: Required[Required[int]] # E: Nesting not allowed\n b: Required[NotRequired[int]] # E: Nesting not allowed\n\n\nclass TD7(TypedDict):\n # > Required[] and NotRequired[] can be used with Annotated[], in any nesting order.\n x: Annotated[Required[int], \"\"]\n y: Required[Annotated[int, \"\"]]\n z: Annotated[Required[Annotated[int, \"\"]], \"\"]\n\n\nRecursiveMovie = TypedDict(\n \"RecursiveMovie\", {\"title\": Required[str], \"predecessor\": NotRequired[\"RecursiveMovie\"]}\n)\n\nmovie: RecursiveMovie = {\"title\": \"Beethoven 3\", \"predecessor\": {\"title\": \"Beethoven 2\"}}\n","source":"typing_tests","origin":"conformance/tests/typeddicts_required.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_01.py","code":"\"\"\"\nTests for advanced or special-case usage of the typing.Self type.\n\"\"\"\n\nfrom typing import assert_type, Self\n\n\nclass ParentA:\n # Test for property that returns Self.\n @property\n def prop1(self) -> Self:\n raise NotImplementedError\n\nclass ChildA(ParentA):\n ...\n\n\nassert_type(ParentA().prop1, ParentA)\nassert_type(ChildA().prop1, ChildA)\n\n\n# Test for a child that accesses an attribute within a parent\n# whose type is annotated using Self.\nclass ParentB:\n a: list[Self]\n\n @classmethod\n def method1(cls) -> Self:\n raise NotImplementedError\n\nclass ChildB(ParentB):\n b: int = 0\n\n def method2(self) -> None:\n assert_type(self, Self)\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = self.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(self.method1(), Self)\n\n @classmethod\n def method3(cls) -> None:\n assert_type(cls, type[Self])\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = cls.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(cls.method1(), Self)\n","source":"typing_tests","origin":"conformance/tests/generics_self_advanced.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_02.py","code":"\"\"\"\nTests for usage of the typing.Self type with attributes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-attribute-annotations\n\nfrom typing import TypeVar, Generic, Self\nfrom dataclasses import dataclass\n\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass LinkedList(Generic[T]):\n value: T\n next: Self | None = None\n\n\n@dataclass\nclass OrdinalLinkedList(LinkedList[int]):\n def ordinal_value(self) -> str:\n return str(self.value)\n\n\n# This should result in a type error.\nxs = OrdinalLinkedList(value=1, next=LinkedList[int](value=2)) # E\n\nif xs.next is not None:\n xs.next = OrdinalLinkedList(value=3, next=None) # OK\n\n # This should result in a type error.\n xs.next = LinkedList[int](value=3, next=None) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_attributes.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_03.py","code":"\"\"\"\nTests for basic usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#self.\n\nfrom typing import Callable, Generic, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n\nclass Shape:\n def set_scale(self, scale: float) -> Self:\n assert_type(self, Self)\n self.scale = scale\n return self\n\n def method2(self) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n def method3(self) -> \"Shape\":\n return self\n\n @classmethod\n def from_config(cls, config: dict[str, float]) -> Self:\n assert_type(cls, type[Self])\n return cls()\n\n @classmethod\n def cls_method2(cls) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n @classmethod\n def cls_method3(cls) -> \"Shape\":\n return cls()\n\n def difference(self, other: Self) -> float:\n assert_type(other, Self)\n return 0.0\n\n def apply(self, f: Callable[[Self], None]) -> None:\n return f(self)\n\n\nclass Circle(Shape):\n pass\n\n\nassert_type(Shape().set_scale(1.0), Shape)\nassert_type(Circle().set_scale(1.0), Circle)\n\nassert_type(Shape.from_config({}), Shape)\nassert_type(Circle.from_config({}), Circle)\n\n\nclass Container(Generic[T]):\n value: T\n\n def __init__(self, value: T) -> None:\n self.value = value\n\n def set_value(self, value: T) -> Self:\n raise NotImplementedError\n\n # This should generate an error because Self isn't subscriptable.\n def foo(self, other: Self[int]) -> None: # E\n pass\n\n\ndef object_with_concrete_type(\n int_container: Container[int], str_container: Container[str]\n) -> None:\n assert_type(int_container.set_value(42), Container[int])\n assert_type(str_container.set_value(\"hello\"), Container[str])\n\n\ndef object_with_generic_type(\n container: Container[T],\n value: T,\n) -> Container[T]:\n val = container.set_value(value)\n assert_type(val, Container[T])\n return val\n","source":"typing_tests","origin":"conformance/tests/generics_self_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_04.py","code":"\"\"\"\nTests for usage of the typing.Self type with protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n\nfrom typing import Protocol, Self, assert_type\n\n\nclass ShapeProtocol(Protocol):\n def set_scale(self, scale: float) -> Self:\n ...\n\n\nclass ReturnSelf:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> Self:\n self.scale = scale\n return self\n\n\nclass ReturnConcreteShape:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> \"ReturnConcreteShape\":\n self.scale = scale\n return self\n\n\nclass BadReturnType:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> int:\n self.scale = scale\n return 42\n\n\nclass ReturnDifferentClass:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> ReturnConcreteShape:\n return ReturnConcreteShape()\n\n\ndef accepts_shape(shape: ShapeProtocol) -> None:\n y = shape.set_scale(0.5)\n assert_type(y, ShapeProtocol)\n\n\ndef main(\n return_self_shape: ReturnSelf,\n return_concrete_shape: ReturnConcreteShape,\n bad_return_type: BadReturnType,\n return_different_class: ReturnDifferentClass,\n) -> None:\n accepts_shape(return_self_shape) # OK\n accepts_shape(return_concrete_shape) # OK\n\n # This should generate a type error.\n accepts_shape(bad_return_type) # E\n\n # Not OK because it returns a non-subclass.\n accepts_shape(return_different_class) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_protocols.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_05.py","code":"\"\"\"\nTests for valid and invalid usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#valid-locations-for-self\n\nfrom typing import Any, Callable, Generic, Self, TypeAlias, TypeVar\n\nclass ReturnsSelf:\n def foo(self) -> Self: # Accepted\n return self\n\n @classmethod\n def bar(cls) -> Self: # Accepted\n return cls(1)\n\n def __new__(cls, value: int) -> Self: # Accepted\n return cls(1)\n\n def explicitly_use_self(self: Self) -> Self: # Accepted\n return self\n\n # Accepted (Self can be nested within other types)\n def returns_list(self) -> list[Self]:\n return []\n\n # Accepted (Self can be nested within other types)\n @classmethod\n def return_cls(cls) -> type[Self]:\n return cls\n\nclass Child(ReturnsSelf):\n # Accepted (we can override a method that uses Self annotations)\n def foo(self) -> Self:\n return self\n\nclass TakesSelf:\n def foo(self, other: Self) -> bool: # Accepted\n return True\n\nclass Recursive:\n # Accepted (treated as an @property returning ``Self | None``)\n next: Self | None\n\nclass CallableAttribute:\n def foo(self) -> int:\n return 0\n\n # Accepted (treated as an @property returning the Callable type)\n bar: Callable[[Self], int] = foo\n\nclass HasNestedFunction:\n x: int = 42\n\n def foo(self) -> None:\n\n # Accepted (Self is bound to HasNestedFunction).\n def nested(z: int, inner_self: Self) -> Self:\n print(z)\n print(inner_self.x)\n return inner_self\n\n nested(42, self) # OK\n\n\nclass Outer:\n class Inner:\n def foo(self) -> Self: # Accepted (Self is bound to Inner)\n return self\n\n\n# This should generate an error.\ndef foo(bar: Self) -> Self: ... # E: not within a class\n\n# This should generate an error.\nbar: Self # E: not within a class\n\nTFoo2 = TypeVar(\"TFoo2\", bound=\"Foo2\")\n\nclass Foo2:\n # Rejected (Self is treated as unknown).\n def has_existing_self_annotation(self: TFoo2) -> Self: # E\n raise NotImplementedError\n\nclass Foo3:\n def return_concrete_type(self) -> Self:\n return Foo3() # E (see FooChild below for rationale)\n\nclass Foo3Child(Foo3):\n child_value: int = 42\n\n def child_method(self) -> None:\n y = self.return_concrete_type()\n y.child_value\n\nT = TypeVar(\"T\")\n\nclass Bar(Generic[T]):\n def bar(self) -> T:\n raise NotImplementedError\n\n# This should generate an error.\nclass Baz(Bar[Self]): ... # E\n\nclass Baz2(Self): ... # E\n\n# This should generate an error.\nTupleSelf: TypeAlias = tuple[Self] # E\n\nclass Base:\n @staticmethod\n # This should generate an error.\n def make() -> Self: # E\n raise NotImplementedError\n\n @staticmethod\n # This should generate an error.\n def return_parameter(foo: Self) -> Self: # E\n raise NotImplementedError\n\nclass MyMetaclass(type):\n # This should generate an error.\n def __new__(cls, *args: Any) -> Self: # E\n raise NotImplementedError\n\n # This should generate an error.\n def __mul__(cls, count: int) -> list[Self]: # E\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_self_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_01.py","code":"\"\"\"\nTests explicit type aliases defined with `TypeAlias`.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#typealias\n\nfrom typing import Any, Callable, Concatenate, Literal, ParamSpec, TypeVar, Union, assert_type\nfrom typing import TypeAlias as TA\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1: TA = Union[int, str]\nGoodTypeAlias2: TA = int | None\nGoodTypeAlias3: TA = list[GoodTypeAlias2]\nGoodTypeAlias4: TA = list[T]\nGoodTypeAlias5: TA = tuple[T, ...] | list[T]\nGoodTypeAlias6: TA = tuple[int, int, S, T]\nGoodTypeAlias7: TA = Callable[..., int]\nGoodTypeAlias8: TA = Callable[[int, T], T]\nGoodTypeAlias9: TA = Callable[Concatenate[int, P], R]\nGoodTypeAlias10: TA = Any\nGoodTypeAlias11: TA = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12: TA = Callable[P, None]\nGoodTypeAlias13: TA = \"int | str\"\nGoodTypeAlias14: TA = list[\"int | str\"]\nGoodTypeAlias15: TA = Literal[3, 4, 5, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12,\n p13: GoodTypeAlias13,\n p14: GoodTypeAlias14,\n p15: GoodTypeAlias15,\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, Callable[..., None])\n assert_type(p13, int | str)\n assert_type(p14, list[int | str])\n assert_type(p15, Literal[3, 4, 5, None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be allowed as type aliases.\nBadTypeAlias1: TA = eval(\"\".join(map(chr, [105, 110, 116]))) # E\nBadTypeAlias2: TA = [int, str] # E\nBadTypeAlias3: TA = ((int, str),) # E\nBadTypeAlias4: TA = [int for i in range(1)] # E\nBadTypeAlias5: TA = {\"a\": \"b\"} # E\nBadTypeAlias6: TA = (lambda: int)() # E\nBadTypeAlias7: TA = [int][0] # E\nBadTypeAlias8: TA = int if 1 < 3 else str # E\nBadTypeAlias9: TA = var1 # E\nBadTypeAlias10: TA = True # E\nBadTypeAlias11: TA = 1 # E\nBadTypeAlias12: TA = list or set # E\nBadTypeAlias13: TA = f\"{'int'}\" # E\n\n\nListAlias: TA = list\nListOrSetAlias: TA = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2: ListAlias[int] # E: already specialized\nx3 = ListOrSetAlias() # E: cannot instantiate union\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_02.py","code":"\"\"\"\nTests recursive (self-referential) type aliases.\n\"\"\"\n\n# The typing specification doesn't mandate support for recursive\n# (self-referential) type aliases prior to PEP 695, but it also\n# doesn't indicates that they shouldn't work.\n# Most type checkers now support them, and many libraries and code\n# bases have started to rely on them.\n# PEP 695 formally mandates that recursive type aliases work.\n\nfrom typing import Mapping, TypeAlias, TypeVar, Union\n\nJson = Union[None, int, str, float, list[\"Json\"], dict[str, \"Json\"]]\n\nj1: Json = [1, {\"a\": 1}] # OK\nj2: Json = 3.4 # OK\nj3: Json = [1.2, None, [1.2, [\"\"]]] # OK\nj4: Json = {\"a\": 1, \"b\": 3j} # E: incompatible type\nj5: Json = [2, 3j] # E: incompatible type\n\n\n# This type alias should be equivalent to Json.\nJson2 = Union[None, int, str, float, list[\"Json2\"], dict[str, \"Json2\"]]\n\ndef func1(j1: Json) -> Json2:\n return j1\n\n\nRecursiveTuple = str | int | tuple[\"RecursiveTuple\", ...]\n\n\nt1: RecursiveTuple = (1, 1) # OK\nt2: RecursiveTuple = (1, \"1\") # OK\nt3: RecursiveTuple = (1, \"1\", 1, \"2\") # OK\nt4: RecursiveTuple = (1, (\"1\", 1), \"2\") # OK\nt5: RecursiveTuple = (1, (\"1\", 1), (1, (1, 2))) # OK\nt6: RecursiveTuple = (1, (\"1\", 1), (1, (1, [2]))) # E\nt7: RecursiveTuple = (1, [1]) # E\n\n\nRecursiveMapping = str | int | Mapping[str, \"RecursiveMapping\"]\n\nm1: RecursiveMapping = 1 # OK\nm2: RecursiveMapping = \"1\" # OK\nm3: RecursiveMapping = {\"1\": \"1\"} # OK\nm4: RecursiveMapping = {\"1\": \"1\", \"2\": 1} # OK\nm5: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {}} # OK\nm6: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": \"2\", \"2\": {}}} # OK\nm7: RecursiveMapping = {\"1\": [1]} # E\nm8: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": [1, 2]} # E\nm9: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": 1, \"2\": [1, 2, 3]}} # E\n\n\nT1 = TypeVar(\"T1\", str, int)\nT2 = TypeVar(\"T2\")\n\nGenericTypeAlias1 = list[\"GenericTypeAlias1[T1]\" | T1]\nSpecializedTypeAlias1 = GenericTypeAlias1[str]\n\ng1: SpecializedTypeAlias1 = [\"hi\", [\"hi\", \"hi\"]] # OK\ng2: GenericTypeAlias1[str] = [\"hi\", \"bye\", [\"\"], [[\"hi\"]]] # OK\ng3: GenericTypeAlias1[str] = [\"hi\", [2.4]] # E\n\nGenericTypeAlias2 = list[\"GenericTypeAlias2[T1, T2]\" | T1 | T2]\n\ng4: GenericTypeAlias2[str, int] = [[3, [\"hi\"]], \"hi\"] # OK\ng5: GenericTypeAlias2[str, float] = [[3, [\"hi\", 3.4, [3.4]]], \"hi\"] # OK\ng6: GenericTypeAlias2[str, int] = [[3, [\"hi\", 3, [3.4]]], \"hi\"] # E\n\n\nRecursiveUnion: TypeAlias = Union[\"RecursiveUnion\", int] # E: cyclical reference\n\n# On one line because different type checkers report the error on different lines\nMutualReference1: TypeAlias = Union[\"MutualReference2\", int]; MutualReference2: TypeAlias = Union[\"MutualReference1\", str] # E: cyclical reference\n","source":"typing_tests","origin":"conformance/tests/aliases_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-guard","pep":"647","introduced_in":"3.10","form":"modern","file":"type-guard/modern_01.py","code":"\"\"\"\nTests TypeGuard functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeguard\n\nfrom typing import Any, Callable, Protocol, Self, TypeGuard, TypeVar, assert_type\n\n\nT = TypeVar(\"T\")\n\ndef is_two_element_tuple(val: tuple[T, ...]) -> TypeGuard[tuple[T, T]]:\n return len(val) == 2\n\ndef func1(names: tuple[str, ...]):\n if is_two_element_tuple(names):\n assert_type(names, tuple[str, str])\n else:\n assert_type(names, tuple[str, ...])\n\n\ndef is_str_list(val: list[object], allow_empty: bool) -> TypeGuard[list[str]]:\n if len(val) == 0:\n return allow_empty\n return all(isinstance(x, str) for x in val)\n\ndef is_set_of(val: set[Any], type: type[T]) -> TypeGuard[set[T]]:\n return all(isinstance(x, type) for x in val)\n\ndef func2(val: set[object]):\n if is_set_of(val, int):\n assert_type(val, set[int])\n else:\n assert_type(val, set[object])\n\n\nT_A = TypeVar(\"T_A\", bound=\"A\")\n\nclass A:\n def tg_1(self, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @classmethod\n def tg_2(cls, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @staticmethod\n def tg_3(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n def tg4(self, val: object) -> TypeGuard[Self]:\n return isinstance(val, type(self))\n\n def tg5(self: T_A, val: object) -> TypeGuard[T_A]:\n return isinstance(val, type(self))\n\nclass B(A):\n pass\n\n# > Type checkers should assume that type narrowing should be applied to\n# > the expression that is passed as the first positional argument to a\n# > user-defined type guard. If the type guard function accepts more than\n# > one argument, no type narrowing is applied to those additional argument\n# > expressions.\n\ndef func3() -> None:\n val1 = object()\n if A().tg_1(val1):\n assert_type(val1, int)\n\n val2 = object()\n if A().tg_2(val2):\n assert_type(val2, int)\n\n val3 = object()\n if A.tg_2(val3):\n assert_type(val3, int)\n\n val4 = object()\n if A().tg_3(val4):\n assert_type(val4, int)\n\n val5 = object()\n if A.tg_3(val5):\n assert_type(val5, int)\n\n val6 = object()\n if B().tg4(val6):\n assert_type(val6, B)\n\n val7 = object()\n if B().tg4(val7):\n assert_type(val7, B)\n\n\n# > If a type guard function is implemented as an instance method or class\n# > method, the first positional argument maps to the second parameter\n# > (after “self” or “cls”).\n\nclass C:\n # Type checker should emit error here.\n def tg_1(self) -> TypeGuard[int]: # E\n return False\n\n @classmethod\n # Type checker should emit error here.\n def tg_2(cls) -> TypeGuard[int]: # E\n return False\n\n# > ``TypeGuard`` is also valid as the return type of a ``Callable`` type. In that\n# > context, it is treated as a subtype of bool. For example, ``Callable[..., TypeGuard[int]]``\n# > is assignable to ``Callable[..., bool]``.\n\n\ndef takes_callable_bool(f: Callable[[object], bool]) -> None:\n pass\n\n\ndef takes_callable_str(f: Callable[[object], str]) -> None:\n pass\n\n\ndef simple_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ntakes_callable_bool(simple_typeguard) # OK\ntakes_callable_str(simple_typeguard) # E\n\n\nclass CallableBoolProto(Protocol):\n def __call__(self, val: object) -> bool: ...\n\n\nclass CallableStrProto(Protocol):\n def __call__(self, val: object) -> str: ...\n\n\ndef takes_callable_bool_proto(f: CallableBoolProto) -> None:\n pass\n\n\ndef takes_callable_str_proto(f: CallableStrProto) -> None:\n pass\n\n\ntakes_callable_bool_proto(simple_typeguard) # OK\ntakes_callable_str_proto(simple_typeguard) # E\n\n# > Unlike ``TypeGuard``, ``TypeIs`` is invariant in its argument type:\n# > ``TypeIs[B]`` is not a subtype of ``TypeIs[A]``,\n# > even if ``B`` is a subtype of ``A``.\n\ndef takes_int_typeguard(f: Callable[[object], TypeGuard[int]]) -> None:\n pass\n\n\ndef int_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ndef bool_typeguard(val: object) -> TypeGuard[bool]:\n return isinstance(val, bool)\n\n\ntakes_int_typeguard(int_typeguard) # OK\ntakes_int_typeguard(bool_typeguard) # OK\n","source":"typing_tests","origin":"conformance/tests/narrowing_typeguard.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests Callable annotation and parameter annotations for \"def\" statements.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#callable\n\nfrom typing import (\n Any,\n Callable,\n Concatenate,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n assert_type,\n)\n\nT_contra = TypeVar(\"T_contra\", contravariant=True)\nP = ParamSpec(\"P\")\n\n\ndef func1(cb: Callable[[int, str], list[str]]) -> None:\n assert_type(cb(1, \"\"), list[str])\n\n cb(1) # E\n cb(1, 2) # E\n cb(1, \"\", 1) # E\n # Mypy reports two errors, one for each kwarg.\n cb(a=1, b=\"\") # E: bad kwarg 'a'\n\n\ndef func2(cb: Callable[[], dict[str, str]]) -> None:\n assert_type(cb(), dict[str, str])\n\n cb(1) # E\n\n\n# https://typing.readthedocs.io/en/latest/spec/callables.html#meaning-of-in-callable\n\n\n# > The Callable special form supports the use of ... in place of the list of\n# > parameter types. This indicates that the type is consistent with any input\n# > signature.\ndef func3(cb: Callable[..., list[str]]):\n assert_type(cb(), list[str])\n assert_type(cb(\"\"), list[str])\n assert_type(cb(1, \"\"), list[str])\n\n\ndef func4(*args: int, **kwargs: int) -> None:\n assert_type(args, tuple[int, ...])\n assert_type(kwargs, dict[str, int])\n\n\nv1: Callable[int] # E\nv2: Callable[int, int] # E\nv3: Callable[[], [int]] # E\nv4: Callable[int, int, int] # E\nv5: Callable[[...], int] # E\n\n\ndef test_cb1(x: int) -> str:\n return \"\"\n\n\ndef test_cb2() -> str:\n return \"\"\n\n\ncb1: Callable[..., str]\ncb1 = test_cb1 # OK\ncb1 = test_cb2 # OK\n\ncb2: Callable[[], str] = cb1 # OK\n\n# > A ... can also be used with Concatenate. In this case, the parameters prior\n# > to the ... are required to be present in the input signature and be\n# > compatible in kind and type, but any additional parameters are permitted.\n\n\ndef test_cb3(a: int, b: int, c: int) -> str:\n return \"\"\n\n\ndef test_cb4(*, a: int) -> str:\n return \"\"\n\n\ncb3: Callable[Concatenate[int, ...], str]\ncb3 = test_cb1 # OK\ncb3 = test_cb2 # E\ncb3 = test_cb3 # OK\ncb3 = test_cb4 # E\n\n# > If the input signature in a function definition includes both a *args and\n# > **kwargs parameter and both are typed as Any (explicitly or implicitly\n# > because it has no annotation), a type checker should treat this as the\n# > equivalent of `...`. Any other parameters in the signature are unaffected\n# > and are retained as part of the signature.\n\n\nclass Proto1(Protocol):\n def __call__(self, *args: Any, **kwargs: Any) -> None: ...\n\n\nclass Proto2(Protocol):\n def __call__(self, a: int, /, *args, **kwargs) -> None: ...\n\n\nclass Proto3(Protocol):\n def __call__(self, a: int, *args: Any, **kwargs: Any) -> None: ...\n\n\nclass Proto4[**P](Protocol):\n def __call__(self, a: int, *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n\nclass Proto5(Protocol[T_contra]):\n def __call__(self, *args: T_contra, **kwargs: T_contra) -> None: ...\n\n\nclass Proto6(Protocol):\n def __call__(self, a: int, /, *args: Any, k: str, **kwargs: Any) -> None:\n pass\n\n\nclass Proto7(Protocol):\n def __call__(self, a: float, /, b: int, *, k: str, m: str) -> None:\n pass\n\n\nclass Proto8(Protocol):\n def __call__(self) -> None: ...\n\n\ndef func5(\n p1: Proto1,\n p2: Proto2,\n p3: Proto3,\n p4: Proto4[...],\n p5: Proto5[Any],\n p7: Proto7,\n p8: Proto8,\n c1: Callable[..., None],\n c2: Callable[Concatenate[int, ...], None],\n):\n ok1: Callable[..., None] = p1 # OK\n ok2: Proto1 = c1 # OK\n ok3: Callable[..., None] = p5 # OK\n ok4: Proto5[Any] = c1 # OK\n ok5: Callable[Concatenate[int, ...], None] = p2 # OK\n ok6: Proto2 = c2 # OK\n ok7: Callable[..., None] = p3 # OK\n ok8: Proto3 = c1 # OK\n ok9: Proto4[...] = p3 # OK\n ok10: Proto3 = p4 # OK\n ok11: Proto6 = p7 # OK\n\n err1: Proto5[Any] = p8 # E\n\n\n# > The ... syntax can also be used to provide a specialized value for a\n# > ParamSpec in a generic class or type alias.\n\n\nCallback1: TypeAlias = Callable[P, str]\nCallback2: TypeAlias = Callable[Concatenate[int, P], str]\n\n\ndef func6(cb1: Callable[[], str], cb2: Callable[[int], str]) -> None:\n f1: Callback1[...] = cb1 # OK\n f2: Callback2[...] = cb1 # E\n\n f3: Callback1[...] = cb2 # OK\n f4: Callback2[...] = cb2 # OK\n\n\n# > If ... is used with signature concatenation, the ... portion continues\n# > to mean “any conceivable set of parameters that could be compatible”.\n\nCallbackWithInt: TypeAlias = Callable[Concatenate[int, P], str]\nCallbackWithStr: TypeAlias = Callable[Concatenate[str, P], str]\n\n\ndef func7(cb: Callable[[int, str], str]) -> None:\n f1: Callable[Concatenate[int, ...], str] = cb # OK\n f2: Callable[Concatenate[str, ...], str] = cb # E\n f3: CallbackWithInt[...] = cb # OK\n f4: CallbackWithStr[...] = cb # E\n","source":"typing_tests","origin":"conformance/tests/callables_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests subtyping rules for callables.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#subtyping-rules-for-callables\n\nfrom typing import Callable, ParamSpec, Protocol, TypeAlias, overload\n\nP = ParamSpec(\"P\")\n\n# > Callable types are covariant with respect to their return types but\n# > contravariant with respect to their parameter types.\n\n\ndef func1(\n cb1: Callable[[float], int],\n cb2: Callable[[float], float],\n cb3: Callable[[int], int],\n) -> None:\n f1: Callable[[int], float] = cb1 # OK\n f2: Callable[[int], float] = cb2 # OK\n f3: Callable[[int], float] = cb3 # OK\n\n f4: Callable[[float], float] = cb1 # OK\n f5: Callable[[float], float] = cb2 # OK\n f6: Callable[[float], float] = cb3 # E\n\n f7: Callable[[int], int] = cb1 # OK\n f8: Callable[[int], int] = cb2 # E\n f9: Callable[[int], int] = cb3 # OK\n\n\n# > Callable A is a subtype of callable B if all keyword-only parameters in B\n# > are present in A as either keyword-only parameters or standard (positional\n# > or keyword) parameters.\n\n\nclass PosOnly2(Protocol):\n def __call__(self, b: int, a: int, /) -> None: ...\n\n\nclass KwOnly2(Protocol):\n def __call__(self, *, b: int, a: int) -> None: ...\n\n\nclass Standard2(Protocol):\n def __call__(self, a: int, b: int) -> None: ...\n\n\ndef func2(standard: Standard2, pos_only: PosOnly2, kw_only: KwOnly2):\n f1: Standard2 = pos_only # E\n f2: Standard2 = kw_only # E\n\n f3: PosOnly2 = standard # OK\n f4: PosOnly2 = kw_only # E\n\n f5: KwOnly2 = standard # OK\n f6: KwOnly2 = pos_only # E\n\n\n# > If a callable B has a signature with a *args parameter, callable A\n# > must also have a *args parameter to be a subtype of B, and the type of\n# > B’s *args parameter must be a subtype of A’s *args parameter.\n\n\nclass NoArgs3(Protocol):\n def __call__(self) -> None: ...\n\n\nclass IntArgs3(Protocol):\n def __call__(self, *args: int) -> None: ...\n\n\nclass FloatArgs3(Protocol):\n def __call__(self, *args: float) -> None: ...\n\n\ndef func3(no_args: NoArgs3, int_args: IntArgs3, float_args: FloatArgs3):\n f1: NoArgs3 = int_args # OK\n f2: NoArgs3 = float_args # OK\n\n f3: IntArgs3 = no_args # E: missing *args parameter\n f4: IntArgs3 = float_args # OK\n\n f5: FloatArgs3 = no_args # E: missing *args parameter\n f6: FloatArgs3 = int_args # E: float is not subtype of int\n\n\n# > If a callable B has a signature with one or more positional-only parameters,\n# > a callable A is a subtype of B if A has an *args parameter whose type is a\n# > supertype of the types of any otherwise-unmatched positional-only parameters\n# > in B.\n\n\nclass PosOnly4(Protocol):\n def __call__(self, a: int, b: str, /) -> None: ...\n\n\nclass IntArgs4(Protocol):\n def __call__(self, *args: int) -> None: ...\n\n\nclass IntStrArgs4(Protocol):\n def __call__(self, *args: int | str) -> None: ...\n\n\nclass StrArgs4(Protocol):\n def __call__(self, a: int, /, *args: str) -> None: ...\n\n\nclass Standard4(Protocol):\n def __call__(self, a: int, b: str) -> None: ...\n\n\ndef func4(int_args: IntArgs4, int_str_args: IntStrArgs4, str_args: StrArgs4):\n f1: PosOnly4 = int_args # E: str is not subtype of int\n f2: PosOnly4 = int_str_args # OK\n f3: PosOnly4 = str_args # OK\n f4: IntStrArgs4 = str_args # E: int | str is not subtype of str\n f5: IntStrArgs4 = int_args # E: int | str is not subtype of int\n f6: StrArgs4 = int_str_args # OK\n f7: StrArgs4 = int_args # E: str is not subtype of int\n f8: IntArgs4 = int_str_args # OK\n f9: IntArgs4 = str_args # E: int is not subtype of str\n f10: Standard4 = int_str_args # E: keyword parameters a and b missing\n f11: Standard4 = str_args # E: keyword parameter b missing\n\n\n# > If a callable B has a signature with a **kwargs parameter (without an\n# > unpacked TypedDict type annotation), callable A must also have a **kwargs\n# > parameter to be a subtype of B, and the type of B’s **kwargs parameter\n# > must be a subtype of A’s **kwargs parameter.\n\n\nclass NoKwargs5(Protocol):\n def __call__(self) -> None: ...\n\n\nclass IntKwargs5(Protocol):\n def __call__(self, **kwargs: int) -> None: ...\n\n\nclass FloatKwargs5(Protocol):\n def __call__(self, **kwargs: float) -> None: ...\n\n\ndef func5(no_kwargs: NoKwargs5, int_kwargs: IntKwargs5, float_kwargs: FloatKwargs5):\n f1: NoKwargs5 = int_kwargs # OK\n f2: NoKwargs5 = float_kwargs # OK\n\n f3: IntKwargs5 = no_kwargs # E: missing **kwargs parameter\n f4: IntKwargs5 = float_kwargs # OK\n\n f5: FloatKwargs5 = no_kwargs # E: missing **kwargs parameter\n f6: FloatKwargs5 = int_kwargs # E: float is not subtype of int\n\n\n# > If a callable B has a signature with one or more keyword-only parameters,\n# > a callable A is a subtype of B if A has a **kwargs parameter whose type\n# > is a supertype of the types of any otherwise-unmatched keyword-only\n# > parameters in B.\n\n\nclass KwOnly6(Protocol):\n def __call__(self, *, a: int, b: str) -> None: ...\n\n\nclass IntKwargs6(Protocol):\n def __call__(self, **kwargs: int) -> None: ...\n\n\nclass IntStrKwargs6(Protocol):\n def __call__(self, **kwargs: int | str) -> None: ...\n\n\nclass StrKwargs6(Protocol):\n def __call__(self, *, a: int, **kwargs: str) -> None: ...\n\n\nclass Standard6(Protocol):\n def __call__(self, a: int, b: str) -> None: ...\n\n\ndef func6(\n int_kwargs: IntKwargs6, int_str_kwargs: IntStrKwargs6, str_kwargs: StrKwargs6\n):\n f1: KwOnly6 = int_kwargs # E: str is not subtype of int\n f2: KwOnly6 = int_str_kwargs # OK\n f3: KwOnly6 = str_kwargs # OK\n f4: IntStrKwargs6 = str_kwargs # E: int | str is not subtype of str\n f5: IntStrKwargs6 = int_kwargs # E: int | str is not subtype of int\n f6: StrKwargs6 = int_str_kwargs # OK\n f7: StrKwargs6 = int_kwargs # E: str is not subtype of int\n f8: IntKwargs6 = int_str_kwargs # OK\n f9: IntKwargs6 = str_kwargs # E: int is not subtype of str\n f10: Standard6 = int_str_kwargs # E: Does not accept positional arguments\n f11: Standard6 = str_kwargs # E: Does not accept positional arguments\n\n\n# > A signature that includes *args: P.args, **kwargs: P.kwargs is equivalent\n# > to a Callable parameterized by P.\n\n\nclass ProtocolWithP[**P](Protocol):\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n\nTypeAliasWithP: TypeAlias = Callable[P, None]\n\n\ndef func7(proto: ProtocolWithP[P], ta: TypeAliasWithP[P]):\n # These two types are equivalent\n f1: TypeAliasWithP[P] = proto # OK\n f2: ProtocolWithP[P] = ta # OK\n\n\n# > If a callable A has a parameter x with a default argument value and B is\n# > the same as A except that x has no default argument, then A is a subtype\n# > of B. A is also a subtype of C if C is the same as A with parameter x\n# > removed.\n\n\nclass DefaultArg8(Protocol):\n def __call__(self, x: int = 0) -> None: ...\n\n\nclass NoDefaultArg8(Protocol):\n def __call__(self, x: int) -> None: ...\n\n\nclass NoX8(Protocol):\n def __call__(self) -> None: ...\n\n\ndef func8(default_arg: DefaultArg8, no_default_arg: NoDefaultArg8, no_x: NoX8):\n f1: DefaultArg8 = no_default_arg # E\n f2: DefaultArg8 = no_x # E\n\n f3: NoDefaultArg8 = default_arg # OK\n f4: NoDefaultArg8 = no_x # E\n\n f5: NoX8 = default_arg # OK\n f6: NoX8 = no_default_arg # E\n\n\n# > If a callable A is overloaded with two or more signatures, it is a subtype\n# > of callable B if at least one of the overloaded signatures in A is a\n# > subtype of B.\n\n\nclass Overloaded9(Protocol):\n @overload\n def __call__(self, x: int) -> int: ...\n @overload\n def __call__(self, x: str) -> str: ...\n\n\nclass IntArg9(Protocol):\n def __call__(self, x: int) -> int: ...\n\n\nclass StrArg9(Protocol):\n def __call__(self, x: str) -> str: ...\n\n\nclass FloatArg9(Protocol):\n def __call__(self, x: float) -> float: ...\n\n\ndef func9(overloaded: Overloaded9):\n f1: IntArg9 = overloaded # OK\n f2: StrArg9 = overloaded # OK\n f3: FloatArg9 = overloaded # E\n\n\n# > If a callable B is overloaded with two or more signatures, callable A is\n# > a subtype of B if A is a subtype of all of the signatures in B.\n\n\nclass Overloaded10(Protocol):\n @overload\n def __call__(self, x: int, y: str) -> float: ...\n @overload\n def __call__(self, x: str) -> complex: ...\n\n\nclass StrArg10(Protocol):\n def __call__(self, x: str) -> complex: ...\n\n\nclass IntStrArg10(Protocol):\n def __call__(self, x: int | str, y: str = \"\") -> int: ...\n\n\ndef func10(int_str_arg: IntStrArg10, str_arg: StrArg10):\n f1: Overloaded10 = int_str_arg # OK\n f2: Overloaded10 = str_arg # E\n","source":"typing_tests","origin":"conformance/tests/callables_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_24.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_25.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-is","pep":"742","introduced_in":"3.13","form":"modern","file":"type-is/modern_01.py","code":"\"\"\"\nTests TypeIs functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeis\n\nfrom collections.abc import Awaitable\nfrom typing import Any, Callable, Protocol, Self, TypeGuard, TypeVar, assert_type\nfrom typing_extensions import TypeIs\n\n\nT = TypeVar(\"T\")\n\ndef is_two_element_tuple(val: tuple[T, ...]) -> TypeIs[tuple[T, T]]:\n return len(val) == 2\n\ndef func1(names: tuple[str, str] | tuple[str, str, str]):\n if is_two_element_tuple(names):\n assert_type(names, tuple[str, str])\n else:\n assert_type(names, tuple[str, str, str])\n\n\n# > The final narrowed type may be narrower than **R**, due to the constraints of the\n# > argument's previously-known type\n\ndef is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:\n return isinstance(val, Awaitable)\n\nasync def func2(val: int | Awaitable[int]):\n if is_awaitable(val):\n # Not `assert_type(val, Awaitable[int])` because a conformant\n # implementation could allow the possibility that instead it is\n # `int & Awaitable[Any]`, an awaitable subclass of int.\n x: int = await val\n return x\n else:\n # We can't say much here. The strictly correct answer is\n # (int | Awaitable[int]) & ~Awaitable[Any], but conformant implementations\n # may simplify this.\n # But it should definitely remain assignable to `int | Awaitable[int]`.\n y: int | Awaitable[int] = val\n return y\n\n\nT_A = TypeVar(\"T_A\", bound=\"A\")\n\nclass A:\n def tg_1(self, val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n @classmethod\n def tg_2(cls, val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n @staticmethod\n def tg_3(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n def tg4(self, val: object) -> TypeIs[Self]:\n return isinstance(val, type(self))\n\n def tg5(self: T_A, val: object) -> TypeIs[T_A]:\n return isinstance(val, type(self))\n\nclass B(A):\n pass\n\n# > The type narrowing behavior is applied to the first positional argument\n# > passed to the function. The function may accept additional arguments,\n# > but they are not affected by type narrowing.\n\n\ndef func3() -> None:\n val1 = object()\n if A().tg_1(val1):\n assert_type(val1, int)\n\n val2 = object()\n if A().tg_2(val2):\n assert_type(val2, int)\n\n val3 = object()\n if A.tg_2(val3):\n assert_type(val3, int)\n\n val4 = object()\n if A().tg_3(val4):\n assert_type(val4, int)\n\n val5 = object()\n if A.tg_3(val5):\n assert_type(val5, int)\n\n val6 = object()\n if B().tg4(val6):\n assert_type(val6, B)\n\n val7 = object()\n if B().tg4(val7):\n assert_type(val7, B)\n\n\n# > If a type narrowing function\n# > is implemented as an instance method or class method, the first positional\n# > argument maps to the second parameter (after self or cls).\n\nclass C:\n # Type checker should emit error here.\n def tg_1(self) -> TypeIs[int]: # E\n return False\n\n @classmethod\n # Type checker should emit error here.\n def tg_2(cls) -> TypeIs[int]: # E\n return False\n\n# > ``TypeIs`` is also valid as the return type of a callable, for example\n# > in callback protocols and in the ``Callable`` special form. In these\n# > contexts, it is treated as a subtype of bool. For example, ``Callable[..., TypeIs[int]]``\n# > is assignable to ``Callable[..., bool]``.\n\n\ndef takes_callable_bool(f: Callable[[object], bool]) -> None:\n pass\n\n\ndef takes_callable_str(f: Callable[[object], str]) -> None:\n pass\n\n\ndef simple_typeguard(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n\ntakes_callable_bool(simple_typeguard) # OK\ntakes_callable_str(simple_typeguard) # E\n\n\nclass CallableBoolProto(Protocol):\n def __call__(self, val: object) -> bool: ...\n\n\nclass CallableStrProto(Protocol):\n def __call__(self, val: object) -> str: ...\n\n\ndef takes_callable_bool_proto(f: CallableBoolProto) -> None:\n pass\n\n\ndef takes_callable_str_proto(f: CallableStrProto) -> None:\n pass\n\n\ntakes_callable_bool_proto(simple_typeguard) # OK\ntakes_callable_str_proto(simple_typeguard) # E\n\n# TypeIs and TypeGuard are not compatible with each other.\n\ndef takes_typeguard(f: Callable[[object], TypeGuard[int]]) -> None:\n pass\n\ndef takes_typeis(f: Callable[[object], TypeIs[int]]) -> None:\n pass\n\ndef is_int_typeis(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\ndef is_int_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\ntakes_typeguard(is_int_typeguard) # OK\ntakes_typeguard(is_int_typeis) # E\ntakes_typeis(is_int_typeguard) # E\ntakes_typeis(is_int_typeis) # OK\n\n\n# > Unlike ``TypeGuard``, ``TypeIs`` is invariant in its argument type:\n# > ``TypeIs[B]`` is not a subtype of ``TypeIs[A]``,\n# > even if ``B`` is a subtype of ``A``.\n\ndef takes_int_typeis(f: Callable[[object], TypeIs[int]]) -> None:\n pass\n\n\ndef int_typeis(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n\ndef bool_typeis(val: object) -> TypeIs[bool]:\n return isinstance(val, bool)\n\n\ntakes_int_typeis(int_typeis) # OK\ntakes_int_typeis(bool_typeis) # E\n\n# > It is an error to narrow to a type that is not consistent with the input type\n\ndef bad_typeis(x: int) -> TypeIs[str]: # E\n return isinstance(x, str)\n\n\ndef bad_typeis_variance(x: list[object]) -> TypeIs[list[int]]: # E\n return all(isinstance(x, int) for x in x)\n","source":"typing_tests","origin":"conformance/tests/narrowing_typeis.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_15.py","code":"\"\"\"\nTests for basic usage of default values for TypeVar-like's.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#defaults-for-type-parameters.\n\nfrom typing import Any, Callable, Generic, Self, Unpack, assert_type\nfrom typing_extensions import TypeVar, ParamSpec, TypeVarTuple\n\n\nDefaultStrT = TypeVar(\"DefaultStrT\", default=str)\nDefaultIntT = TypeVar(\"DefaultIntT\", default=int)\nDefaultBoolT = TypeVar(\"DefaultBoolT\", default=bool)\nT = TypeVar(\"T\")\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\n\n# > The order for defaults should follow the standard function parameter\n# > rules, so a type parameter with no ``default`` cannot follow one with\n# > a ``default`` value. Doing so may raise a ``TypeError`` at runtime,\n# > and a type checker should flag this as an error.\n\n\nclass NonDefaultFollowsDefault(Generic[DefaultStrT, T]): ... # E: non-default TypeVars cannot follow ones with defaults\n\n\nclass NoNonDefaults(Generic[DefaultStrT, DefaultIntT]):\n x: DefaultStrT\n y: DefaultIntT\n\n\ndef test_no_non_defaults(a: NoNonDefaults, b: NoNonDefaults[str], c: NoNonDefaults[str, int]):\n assert_type(a.x, str)\n assert_type(a.y, int)\n\n assert_type(b.x, str)\n assert_type(b.y, int)\n\n assert_type(c.x, str)\n assert_type(c.y, int)\n\n\nclass OneDefault(Generic[T, DefaultBoolT]):\n x: T\n y: DefaultBoolT\n\n\ndef test_one_default(a: OneDefault[float], b: OneDefault[float, bool]):\n assert_type(a.x, float)\n assert_type(a.y, bool)\n\n assert_type(b.x, float)\n assert_type(b.y, bool)\n\n\nclass AllTheDefaults(Generic[T1, T2, DefaultStrT, DefaultIntT, DefaultBoolT]):\n x1: T1\n x2: T2\n x3: DefaultStrT\n x4: DefaultIntT\n x5: DefaultBoolT\n\n\ndef test_all_the_defaults(\n a: AllTheDefaults,\n b: AllTheDefaults[int], # E: expected 2 arguments to AllTheDefaults\n c: AllTheDefaults[int, complex],\n d: AllTheDefaults[int, complex, str, int, bool],\n e: AllTheDefaults[int, complex, str],\n f: AllTheDefaults[int, complex, str, int],\n g: AllTheDefaults[int, complex, str, int, bool],\n):\n assert_type(a.x1, Any)\n assert_type(a.x2, Any)\n assert_type(a.x3, str)\n assert_type(a.x4, int)\n assert_type(a.x5, bool)\n\n assert_type(c.x1, int)\n assert_type(c.x2, complex)\n assert_type(c.x3, str)\n assert_type(c.x4, int)\n assert_type(c.x5, bool)\n\n assert_type(d.x1, int)\n assert_type(d.x2, complex)\n assert_type(d.x3, str)\n assert_type(d.x4, int)\n assert_type(d.x5, bool)\n\n assert_type(e.x1, int)\n assert_type(e.x2, complex)\n assert_type(e.x3, str)\n assert_type(e.x4, int)\n assert_type(e.x5, bool)\n\n assert_type(f.x1, int)\n assert_type(f.x2, complex)\n assert_type(f.x3, str)\n assert_type(f.x4, int)\n assert_type(f.x5, bool)\n\n assert_type(g.x1, int)\n assert_type(g.x2, complex)\n assert_type(g.x3, str)\n assert_type(g.x4, int)\n assert_type(g.x5, bool)\n\n\n# > ``ParamSpec`` defaults are defined using the same syntax as\n# > ``TypeVar`` \\ s but use a ``list`` of types or an ellipsis\n# > literal \"``...``\" or another in-scope ``ParamSpec``.\n\nDefaultP = ParamSpec(\"DefaultP\", default=[str, int])\n\n\nclass Class_ParamSpec(Generic[DefaultP]):\n x: Callable[DefaultP, None]\n\n\ndef test_param_spec_defaults(a: Class_ParamSpec):\n assert_type(a.x, Callable[[str, int], None])\n assert_type(Class_ParamSpec(), Class_ParamSpec[str, int])\n assert_type(Class_ParamSpec[[bool, bool]](), Class_ParamSpec[bool, bool])\n\n\n# > ``TypeVarTuple`` defaults are defined using the same syntax as\n# > ``TypeVar`` \\ s, but instead of a single type, they use an unpacked tuple\n# > of types or an unpacked, in-scope ``TypeVarTuple`` (see `Scoping Rules`_).\n\nDefaultTs = TypeVarTuple(\"DefaultTs\", default=Unpack[tuple[str, int]])\n\n\nclass Class_TypeVarTuple(Generic[*DefaultTs]):\n x: tuple[*DefaultTs]\n\n\ndef test_type_var_tuple_defaults(a: Class_TypeVarTuple):\n assert_type(a.x, tuple[str, int])\n assert_type(Class_TypeVarTuple(), Class_TypeVarTuple[str, int])\n assert_type(Class_TypeVarTuple[int, bool](), Class_TypeVarTuple[int, bool])\n\n\nAnotherDefaultTs = TypeVarTuple(\"AnotherDefaultTs\", default=Unpack[DefaultTs])\n\n\n# > If both ``bound`` and ``default`` are passed, ``default`` must be a\n# > subtype of ``bound``. If not, the type checker should generate an\n# > error.\n\nOk1 = TypeVar(\"Ok1\", bound=float, default=int) # OK\nInvalid1 = TypeVar(\"Invalid1\", bound=str, default=int) # E: the bound and default are incompatible\n\n# > For constrained ``TypeVar``\\ s, the default needs to be one of the\n# > constraints. A type checker should generate an error even if it is a\n# > subtype of one of the constraints.\n\nOk2 = TypeVar(\"Ok2\", float, str, default=float) # OK\nInvalid2 = TypeVar(\"Invalid2\", float, str, default=int) # E: expected one of float or str got int\n\n\n# > In generic functions, type checkers may use a type parameter's default when the\n# > type parameter cannot be solved to anything. We leave the semantics of this\n# > usage unspecified, as ensuring the ``default`` is returned in every code path\n# > where the type parameter can go unsolved may be too hard to implement. Type\n# > checkers are free to either disallow this case or experiment with implementing\n# > support.\n\nT4 = TypeVar(\"T4\", default=int)\n\n\ndef func1(x: int | set[T4]) -> T4:\n raise NotImplementedError\n\n\nassert_type(func1(0), int) # E[optional-default-use]\nassert_type(func1(0), Any) # E[optional-default-use]\n\n\n# > A ``TypeVar`` that immediately follows a ``TypeVarTuple`` is not allowed\n# > to have a default, because it would be ambiguous whether a type argument\n# > should be bound to the ``TypeVarTuple`` or the defaulted ``TypeVar``.\n\nTs = TypeVarTuple(\"Ts\")\nT5 = TypeVar(\"T5\", default=bool)\n\n\nclass Foo5(Generic[*Ts, T5]): ... # E\n\n\n# > It is allowed to have a ``ParamSpec`` with a default following a\n# > ``TypeVarTuple`` with a default, as there can be no ambiguity between a\n# > type argument for the ``ParamSpec`` and one for the ``TypeVarTuple``.\n\nP = ParamSpec(\"P\", default=[float, bool])\n\n\nclass Foo6(Generic[*Ts, P]):\n x: tuple[*Ts]\n y: Callable[P, None]\n\n\ndef test_foo6(a: Foo6[int, str], b: Foo6[int, str, [bytes]]):\n assert_type(a.x, tuple[int, str])\n assert_type(a.y, Callable[[float, bool], None])\n\n assert_type(b.x, tuple[int, str])\n assert_type(b.y, Callable[[bytes], None])\n\n\n# > Type parameter defaults should be bound by attribute access\n# > (including call and subscript).\n\n\nclass Foo7(Generic[DefaultIntT]):\n def meth(self, /) -> Self:\n return self\n\n attr: DefaultIntT\n\n\nfoo7 = Foo7()\nassert_type(Foo7.meth(foo7), Foo7[int])\nassert_type(Foo7().attr, int)\n","source":"typing_tests","origin":"conformance/tests/generics_defaults.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_16.py","code":"\"\"\"\nTests for type parameter default values that reference other type parameters.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#defaults-for-type-parameters.\n\n# > To use another type parameter as a default the ``default`` and the\n# > type parameter must be the same type (a ``TypeVar``'s default must be\n# > a ``TypeVar``, etc.).\n\nfrom typing import Any, Generic, assert_type\nfrom typing_extensions import TypeVar\n\nDefaultStrT = TypeVar(\"DefaultStrT\", default=str)\nStartT = TypeVar(\"StartT\", default=int)\nStopT = TypeVar(\"StopT\", default=StartT)\nStepT = TypeVar(\"StepT\", default=int | None)\n\n\nclass slice(Generic[StartT, StopT, StepT]): ...\n\n\nassert_type(slice(), slice[int, int, int | None])\nassert_type(slice[str](), slice[str, str, int | None])\nassert_type(slice[str, bool, complex](), slice[str, bool, complex])\n\nT2 = TypeVar(\"T2\", default=DefaultStrT)\n\n\nclass Foo(Generic[DefaultStrT, T2]):\n def __init__(self, a: DefaultStrT, b: T2) -> None: ...\n\n\ndef func1(i: int, s: str) -> None:\n assert_type(Foo(i, s), Foo[int, str])\n Foo[int](i, s) # E: Foo[int, str] cannot be assigned to self: Foo[int, int] in Foo.__init__\n Foo[int](s, i) # E: Foo[str, int] cannot be assigned to self: Foo[int, int] in Foo.__init__\n\n\n# > ``T1`` must be used before ``T2`` in the parameter list of the generic.\n\nS1 = TypeVar(\"S1\")\nS2 = TypeVar(\"S2\", default=S1)\n\n\nclass Foo2(Generic[S1, S2]): ... # OK\n\n\nStart2T = TypeVar(\"Start2T\", default=\"StopT\")\nStop2T = TypeVar(\"Stop2T\", default=int)\n\n\nclass slice2(Generic[Start2T, Stop2T, StepT]): ... # E: bad ordering\n\n\n# > Using a type parameter from an outer scope as a default is not supported.\n\n\nclass Foo3(Generic[S1]):\n class Bar2(Generic[S2]): ... # E\n\n\n# > ``T1``'s bound must be a subtype of ``T2``'s bound.\n\nX1 = TypeVar(\"X1\", bound=int)\nOk1 = TypeVar(\"Ok1\", default=X1, bound=float) # OK\nAlsoOk1 = TypeVar(\"AlsoOk1\", default=X1, bound=int) # OK\nInvalid1 = TypeVar(\"Invalid1\", default=X1, bound=str) # E: int is not a subtype of str\n\n\n# > The constraints of ``T2`` must be a superset of the constraints of ``T1``.\n\nY1 = TypeVar(\"Y1\", bound=int)\nInvalid2 = TypeVar(\"Invalid2\", float, str, default=Y1) # E: upper bound int is incompatible with constraints float or str\n\nY2 = TypeVar(\"Y2\", int, str)\nAlsoOk2 = TypeVar(\"AlsoOk2\", int, str, bool, default=Y2) # OK\nAlsoInvalid2 = TypeVar(\"AlsoInvalid2\", bool, complex, default=Y2) # E: {bool, complex} is not a superset of {int, str}\n\n\n# > Type parameters are valid as parameters to generics inside of a\n# > ``default`` when the first parameter is in scope as determined by the\n# > `previous section `_.\n\n\nZ1 = TypeVar(\"Z1\")\nListDefaultT = TypeVar(\"ListDefaultT\", default=list[Z1]) # OK\n\n\nclass Bar(Generic[Z1, ListDefaultT]): # OK\n x: Z1\n y: ListDefaultT\n def __init__(self, x: Z1, y: ListDefaultT): ...\n\n\ndef f(b1: Bar, b2: Bar[int]):\n assert_type(b1.x, Any)\n assert_type(b1.y, list[Any])\n assert_type(b2.x, int)\n assert_type(b2.y, list[int])\n\n\nassert_type(Bar[int](0, []), Bar[int, list[int]])\nassert_type(Bar[int, list[str]](0, []), Bar[int, list[str]])\nassert_type(Bar[int, str](0, \"\"), Bar[int, str])\n","source":"typing_tests","origin":"conformance/tests/generics_defaults_referential.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_17.py","code":"\"\"\"\nTests for specialization rules associated with type parameters with\ndefault values.\n\"\"\"\n\n# > A generic type alias can be further subscripted following normal subscription\n# > rules. If a type parameter has a default that hasn't been overridden, it should\n# > be treated like it was substituted into the type alias.\n\nfrom typing import Generic, TypeAlias, assert_type\nfrom typing_extensions import TypeVar\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nDefaultIntT = TypeVar(\"DefaultIntT\", default=int)\nDefaultStrT = TypeVar(\"DefaultStrT\", default=str)\n\n\nclass SomethingWithNoDefaults(Generic[T1, T2]): ...\n\n\nMyAlias: TypeAlias = SomethingWithNoDefaults[int, DefaultStrT] # OK\n\n\ndef func1(p1: MyAlias, p2: MyAlias[bool]):\n assert_type(p1, SomethingWithNoDefaults[int, str])\n assert_type(p2, SomethingWithNoDefaults[int, bool])\n\n\nMyAlias[bool, int] # E: too many arguments passed to MyAlias\n\n\n# > Generic classes with type parameters that have defaults behave similarly\n# > generic type aliases. That is, subclasses can be further subscripted following\n# > normal subscription rules, non-overridden defaults should be substituted.\n\n\nclass SubclassMe(Generic[T1, DefaultStrT]):\n x: DefaultStrT\n\n\nclass Bar(SubclassMe[int, DefaultStrT]): ...\n\n\nx1: type[Bar[str]] = Bar # ok\n# Type checkers may take type context into account when deciding how to\n# specialize a bare runtime reference to a generic class.\nx2: type[Bar[int]] = Bar # E?\nassert_type(Bar(), Bar[str])\nassert_type(Bar[bool](), Bar[bool])\n\n\nclass Foo(SubclassMe[float]): ...\n\n\nassert_type(Foo().x, str)\n\nFoo[str] # E: Foo cannot be further subscripted\n\n\nclass Baz(Generic[DefaultIntT, DefaultStrT]): ...\n\n\nclass Spam(Baz): ...\n\n\n# Spam is \nv1: Baz[int, str] = Spam()\n","source":"typing_tests","origin":"conformance/tests/generics_defaults_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_15.py","code":"\"\"\"\nTests the \"type\" statement introduced in Python 3.12.\n\"\"\"\n\nfrom typing import Callable, TypeVar\n\n\ntype GoodAlias1 = int\ntype GoodAlias2[S1, *S2, **S3] = Callable[S3, S1] | tuple[*S2]\ntype GoodAlias3 = GoodAlias2[int, tuple[int, str], ...]\n\n\nclass ClassA:\n type GoodAlias4 = int | None\n\n\nGoodAlias1.bit_count # E: cannot access attribute\n\nGoodAlias1() # E: cannot call alias\n\nprint(GoodAlias1.__value__) # OK\nprint(GoodAlias1.__type_params__) # OK\nprint(GoodAlias1.other_attrib) # E: unknown attribute\n\n\nclass DerivedInt(GoodAlias1): # E: cannot use alias as base class\n pass\n\n\ndef func2(x: object):\n if isinstance(x, GoodAlias1): # E: cannot use alias in isinstance\n pass\n\nvar1 = 1\n\n# The following should not be allowed as type aliases.\ntype BadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116]))) # E\ntype BadTypeAlias2 = [int, str] # E\ntype BadTypeAlias3 = ((int, str),) # E\ntype BadTypeAlias4 = [int for i in range(1)] # E\ntype BadTypeAlias5 = {\"a\": \"b\"} # E\ntype BadTypeAlias6 = (lambda: int)() # E\ntype BadTypeAlias7 = [int][0] # E\ntype BadTypeAlias8 = int if 1 < 3 else str # E\ntype BadTypeAlias9 = var1 # E\ntype BadTypeAlias10 = True # E\ntype BadTypeAlias11 = 1 # E\ntype BadTypeAlias12 = list or set # E\ntype BadTypeAlias13 = f\"{'int'}\" # E\n\nV = TypeVar(\"V\")\n\ntype TA1[K] = dict[K, V] # E: combines old and new TypeVars\n\n\nT1 = TypeVar(\"T1\")\n\ntype TA2 = list[T1] # E: uses old TypeVar\n\n\ntype RecursiveTypeAlias1[T] = T | list[RecursiveTypeAlias1[T]]\n\nr1_1: RecursiveTypeAlias1[int] = 1\nr1_2: RecursiveTypeAlias1[int] = [1, [1, 2, 3]]\n\ntype RecursiveTypeAlias2[S: int, T: str, **P] = Callable[P, T] | list[S] | list[RecursiveTypeAlias2[S, T, P]]\n\nr2_1: RecursiveTypeAlias2[str, str, ...] # E: not compatible with S bound\nr2_2: RecursiveTypeAlias2[int, str, ...]\nr2_3: RecursiveTypeAlias2[int, int, ...] # E: not compatible with T bound\nr2_4: RecursiveTypeAlias2[int, str, [int, str]]\n\ntype RecursiveTypeAlias3 = RecursiveTypeAlias3 # E: circular definition\n\ntype RecursiveTypeAlias4[T] = T | RecursiveTypeAlias4[str] # E: circular definition\n\ntype RecursiveTypeAlias5[T] = T | list[RecursiveTypeAlias5[T]]\n\ntype RecursiveTypeAlias6 = RecursiveTypeAlias7 # E[RTA6+]: circular definition\ntype RecursiveTypeAlias7 = RecursiveTypeAlias6 # E[RTA6+]: circular definition\n","source":"typing_tests","origin":"conformance/tests/aliases_type_statement.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_16.py","code":"\"\"\"\nTests the TypeAliasType call introduced in Python 3.12.\n\"\"\"\n\nfrom typing import Callable, Generic, ParamSpec, TypeAliasType, TypeVar, TypeVarTuple\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nTStr = TypeVar(\"TStr\", bound=str)\nP = ParamSpec(\"P\")\nTs = TypeVarTuple(\"Ts\")\n\nmy_tuple = (S, T)\nvar1 = 3\n\nGoodAlias1 = TypeAliasType(\"GoodAlias1\", int)\nGoodAlias2 = TypeAliasType(\"GoodAlias2\", list[T], type_params=(T,))\nGoodAlias3 = TypeAliasType(\"GoodAlias3\", list[T] | list[S], type_params=(S, T))\nGoodAlias4 = TypeAliasType(\"GoodAlias4\", T | \"list[GoodAlias4[T]]\", type_params=(T,))\nGoodAlias5 = TypeAliasType(\n \"GoodAlias5\",\n Callable[P, TStr] | list[S] | list[\"GoodAlias5[S, TStr, P]\"] | tuple[*Ts],\n type_params=(S, TStr, P, Ts),\n)\n\nclass ClassA(Generic[T]):\n GoodAlias6 = TypeAliasType(\"GoodAlias6\", list[T])\n\n\nprint(GoodAlias1.__value__) # OK\nprint(GoodAlias1.__type_params__) # OK\nprint(GoodAlias1.other_attrib) # E: unknown attribute\n\n\nx1: GoodAlias4[int] = 1 # OK\nx2: GoodAlias4[int] = [1] # OK\nx3: GoodAlias5[str, str, ..., int, str] # OK\nx4: GoodAlias5[int, str, ..., int, str] # OK\nx5: GoodAlias5[int, str, [int, str], *tuple[int, str, int]] # OK\nx6: GoodAlias5[int, int, ...] # E: incorrect type arguments\n\n\nBadAlias1 = TypeAliasType(\"BadAlias1\", list[S], type_params=(T,)) # E: S not in scope\nBadAlias2 = TypeAliasType(\"BadAlias2\", list[S]) # E: S not in scope\nBadAlias3 = TypeAliasType(\"BadAlias3\", int, type_params=my_tuple) # E: not literal tuple\nBadAlias4 = TypeAliasType(\"BadAlias4\", \"BadAlias4\") # E: circular dependency\nBadAlias5 = TypeAliasType(\"BadAlias5\", T | \"BadAlias5[str]\", type_params=(T,)) # E: circular dependency\nBadAlias6 = TypeAliasType(\"BadAlias6\", \"BadAlias7\") # E: circular dependency\nBadAlias7 = TypeAliasType(\"BadAlias7\", BadAlias6) # E?: circular dependency\n\n# The following are invalid type expressions for a type alias.\nBadAlias8 = TypeAliasType(\"BadAlias8\", eval(\"\".join(map(chr, [105, 110, 116])))) # E\nBadAlias9 = TypeAliasType(\"BadAlias9\", [int, str]) # E\nBadAlias10 = TypeAliasType(\"BadAlias10\", ((int, str),)) # E\nBadAlias11 = TypeAliasType(\"BadAlias11\", [int for i in range(1)]) # E\nBadAlias12 = TypeAliasType(\"BadAlias12\", {\"a\": \"b\"}) # E\nBadAlias13 = TypeAliasType(\"BadAlias13\", (lambda: int)()) # E\nBadAlias14 = TypeAliasType(\"BadAlias14\", [int][0]) # E\nBadAlias15 = TypeAliasType(\"BadAlias15\", int if 1 < 3 else str) # E\nBadAlias16 = TypeAliasType(\"BadAlias16\", var1) # E\nBadAlias17 = TypeAliasType(\"BadAlias17\", True) # E\nBadAlias18 = TypeAliasType(\"BadAlias18\", 1) # E\nBadAlias19 = TypeAliasType(\"BadAlias19\", list or set) # E\nBadAlias20 = TypeAliasType(\"BadAlias20\", f\"{'int'}\") # E\n\nBadAlias21 = TypeAliasType(\"BadAlias21\", list[BadAlias21]) # E\n","source":"typing_tests","origin":"conformance/tests/aliases_typealiastype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_17.py","code":"\"\"\"\nTests the compatibility rules between type parameter syntax (introduced in PEP 695)\nand traditional TypeVars.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#compatibility-with-traditional-typevars\n\nfrom typing import TypeVar\n\n\nK = TypeVar(\"K\")\n\n\nclass ClassA[V](dict[K, V]): # E: traditional TypeVar not allowed here\n ...\n\n\nclass ClassB[K, V](dict[K, V]): # OK\n ...\n\n\nclass ClassC[V]:\n def method1(self, a: V, b: K) -> V | K: # OK\n raise NotImplementedError\n\n def method2[M](self, a: M, b: K) -> M | K: # E\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_compatibility.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_18.py","code":"\"\"\"\nValidates the type parameter syntax introduced in PEP 695.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#type-parameter-declarations\n\n\n# This generic class is parameterized by a TypeVar T, a\n# TypeVarTuple Ts, and a ParamSpec P.\nfrom typing import Generic, Protocol\n\n\nclass ChildClass[T, *Ts, **P]:\n pass\n\n\nclass ClassA[T](Generic[T]): # E: Runtime error\n ...\n\n\nclass ClassB[S, T](Protocol): # OK\n ...\n\n\nclass ClassC[S, T](Protocol[S, T]): # E\n ...\n\n\nclass ClassD[T: str]:\n def method1(self, x: T):\n x.capitalize() # OK\n x.is_integer() # E\n\n\nclass ClassE[T: dict[str, int]]: # OK\n pass\n\n\nclass ClassF[S: ForwardReference[int], T: \"ForwardReference[str]\"]: # OK\n ...\n\n\nclass ClassG[V]:\n class ClassD[T: dict[str, V]]: # E: generic type not allowed\n ...\n\n\nclass ClassH[T: [str, int]]: # E: illegal expression form\n ...\n\n\nclass ClassI[AnyStr: (str, bytes)]: # OK\n ...\n\n\nclass ClassJ[T: (ForwardReference[int], \"ForwardReference[str]\", bytes)]: # OK\n ...\n\n\nclass ClassK[T: ()]: # E: two or more types required\n ...\n\n\nclass ClassL[T: (str,)]: # E: two or more types required\n ...\n\n\nt1 = (bytes, str)\n\n\nclass ClassM[T: t1]: # E: literal tuple expression required\n ...\n\n\nclass ClassN[T: (3, bytes)]: # E: invalid expression form\n ...\n\n\nclass ClassO[T: (list[S], str)]: # E: generic type\n ...\n\n\nclass ForwardReference[T]: ...\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_declarations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_19.py","code":"\"\"\"\nTests the handling of \"infer_variance\" parameter for TypeVar.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#auto-variance-for-typevar\n\nfrom typing import Final, Generic, Iterator, overload, Sequence, TypeVar\nfrom dataclasses import dataclass\n\n\nT = TypeVar(\"T\", infer_variance=True)\nK = TypeVar(\"K\", infer_variance=True)\nV = TypeVar(\"V\", infer_variance=True)\n\nS1 = TypeVar(\"S1\", covariant=True, infer_variance=True) # E: cannot use covariant with infer_variance\n\nS2 = TypeVar(\"S2\", contravariant=True, infer_variance=True) # E: cannot use contravariant with infer_variance\n\n\nclass ShouldBeCovariant1(Generic[T]):\n def __getitem__(self, index: int) -> T:\n raise NotImplementedError\n\n def __iter__(self) -> Iterator[T]:\n raise NotImplementedError\n\n\nvco1_1: ShouldBeCovariant1[float] = ShouldBeCovariant1[int]() # OK\nvco1_2: ShouldBeCovariant1[int] = ShouldBeCovariant1[float]() # E\n\n\nclass ShouldBeCovariant2(Sequence[T]):\n @overload\n def __getitem__(self, index: int) -> T:\n ...\n @overload\n def __getitem__(self, index: slice) -> Sequence[T]:\n ...\n def __getitem__(self, index: int | slice) -> T | Sequence[T]:\n raise NotImplementedError\n\n def __len__(self) -> int:\n raise NotImplementedError\n\n\nvco2_1: ShouldBeCovariant2[float] = ShouldBeCovariant2[int]() # OK\nvco2_2: ShouldBeCovariant2[int] = ShouldBeCovariant2[float]() # E\n\n\nclass ShouldBeCovariant3(Generic[T]):\n def method1(self) -> \"ShouldBeCovariant2[T]\":\n raise NotImplementedError\n\n\nvco3_1: ShouldBeCovariant3[float] = ShouldBeCovariant3[int]() # OK\nvco3_2: ShouldBeCovariant3[int] = ShouldBeCovariant3[float]() # E\n\n\n@dataclass(frozen=True)\nclass ShouldBeCovariant4(Generic[T]):\n x: T\n\n\n# This test is problematic as of Python 3.13 because of the\n# newly synthesized \"__replace__\" method, which causes the type\n# variable to be inferred as invariant rather than covariant.\n# See https://github.com/python/mypy/issues/17623#issuecomment-2266312738\n# for details. Until we sort this out, we'll leave this test commented\n# out.\n\n# vo4_1: ShouldBeCovariant4[float] = ShouldBeCovariant4[int](1) # OK\n# vo4_4: ShouldBeCovariant4[int] = ShouldBeCovariant4[float](1.0) # E\n\n\nclass ShouldBeCovariant5(Generic[T]):\n def __init__(self, x: T) -> None:\n self._x = x\n\n @property\n def x(self) -> T:\n return self._x\n\n\nvo5_1: ShouldBeCovariant5[float] = ShouldBeCovariant5[int](1) # OK\nvo5_2: ShouldBeCovariant5[int] = ShouldBeCovariant5[float](1.0) # E\n\n\nclass ShouldBeCovariant6(Generic[T]):\n x: Final[T]\n\n def __init__(self, value: T):\n self.x = value\n\n\nvo6_1: ShouldBeCovariant6[float] = ShouldBeCovariant6[int](1) # OK\nvo6_2: ShouldBeCovariant6[int] = ShouldBeCovariant6[float](1.0) # E\n\n\nclass ShouldBeInvariant1(Generic[T]):\n def __init__(self, value: T) -> None:\n self._value = value\n\n @property\n def value(self) -> T:\n return self._value\n\n @value.setter\n def value(self, value: T):\n self._value = value\n\n\nvinv1_1: ShouldBeInvariant1[float] = ShouldBeInvariant1[int](1) # E\nvinv1_2: ShouldBeInvariant1[int] = ShouldBeInvariant1[float](1.1) # E\n\n\nclass ShouldBeInvariant2(Generic[T]):\n def __init__(self, value: T) -> None:\n self._value = value\n\n def get_value(self) -> T:\n return self._value\n\n def set_value(self, value: T):\n self._value = value\n\n\nvinv2_1: ShouldBeInvariant2[float] = ShouldBeInvariant2[int](1) # E\nvinv2_2: ShouldBeInvariant2[int] = ShouldBeInvariant2[float](1.1) # E\n\n\nclass ShouldBeInvariant3(dict[K, V]):\n pass\n\n\nvinv3_1: ShouldBeInvariant3[float, str] = ShouldBeInvariant3[int, str]() # E\nvinv3_2: ShouldBeInvariant3[int, str] = ShouldBeInvariant3[float, str]() # E\nvinv3_3: ShouldBeInvariant3[str, float] = ShouldBeInvariant3[str, int]() # E\nvinv3_4: ShouldBeInvariant3[str, int] = ShouldBeInvariant3[str, float]() # E\n\n\n@dataclass\nclass ShouldBeInvariant4[T]:\n x: T\n\n\nvinv4_1: ShouldBeInvariant4[float] = ShouldBeInvariant4[int](1) # E\n\n\nclass ShouldBeInvariant5[T]:\n def __init__(self, x: T) -> None:\n self.x = x\n\n\nvinv5_1: ShouldBeInvariant5[float] = ShouldBeInvariant5[int](1) # E\n\n\nclass ShouldBeContravariant1(Generic[T]):\n def __init__(self, value: T) -> None:\n pass\n\n def set_value(self, value: T):\n pass\n\n\nvcontra1_1: ShouldBeContravariant1[float] = ShouldBeContravariant1[int](1) # E\nvcontra1_2: ShouldBeContravariant1[int] = ShouldBeContravariant1[float](1.2) # OK\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_infer_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_20.py","code":"\"\"\"\nTests the scoping rules for type parameter syntax introduced in PEP 695.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#type-parameter-scopes\n\nfrom typing import Callable, Mapping, Sequence, TypeVar, assert_type\n\n# > A compiler error or runtime exception is generated if the definition\n# > of an earlier type parameter references a later type parameter even\n# > if the name is defined in an outer scope.\n\n\nclass ClassA[S, T: Sequence[S]]: # E\n ...\n\n\nclass ClassB[S: Sequence[T], T]: # E\n ...\n\n\nclass Foo[T]:\n ...\n\n\nprint(T) # E: Runtime error: 'T' is not defined\n\n\ndef decorator1[\n T, **P, R\n](x: type[Foo[T]]) -> Callable[[Callable[P, R]], Callable[P, R]]:\n raise NotImplementedError\n\n\n@decorator1(Foo[T]) # E: Runtime error: 'T' is not defined\nclass ClassD[T]:\n ...\n\n\ntype Alias1[K, V] = Mapping[K, V] | Sequence[K]\n\n\nS: int = int(0)\n\n\ndef outer1[S](x: str):\n S: str = x\n T: int = 1\n\n def outer2[T]():\n def inner1():\n nonlocal S # OK\n assert_type(S, str)\n # nonlocal T # Syntax error\n\n def inner2():\n global S # OK\n assert_type(S, int)\n\n\nclass Outer1:\n class Private:\n pass\n\n class Inner[T](Private, Sequence[T]): # OK\n pass\n\n def method1[T](self, a: Inner[T]) -> Inner[T]: # OK\n return a\n\n\ndef decorator2[**P, R](x: int) -> Callable[[Callable[P, R]], Callable[P, R]]:\n raise NotImplementedError\n\n\nT = int(0)\n\n\n@decorator2(T) # OK\nclass ClassE[T](Sequence[T]):\n T = int(1)\n\n def method1[T](self): # E\n ...\n\n def method2[T](self, x=T): # E\n ...\n\n def method3[T](self, x: T): # E\n ...\n\n\nT = int(0)\n\n\ndef f(a: int, b: str, c: complex):\n class Outer2[T]:\n T = a\n\n assert_type(T, int)\n\n class Inner1:\n T = b\n\n assert_type(T, str)\n\n def inner_method(self):\n assert_type(T, TypeVar)\n\n def outer_method(self):\n T = c\n\n assert_type(T, complex)\n\n def inner_func():\n assert_type(T, complex)\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_13.py","code":"\"\"\"\nTests the \"alternative\" (non-class) syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#alternative-syntax\n\nfrom typing import TypedDict\n\n\nMovie = TypedDict(\"Movie\", {\"name\": str, \"year\": int, \"illegal key name\": bool})\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982, \"illegal key name\": True}\n\nMovieOptional = TypedDict(\"MovieOptional\", {\"name\": str, \"year\": int}, total=False)\n\nmovie_opt1: MovieOptional = {}\nmovie_opt2: MovieOptional = {\"year\": 1982}\n\n# > A type checker is only expected to accept a dictionary display expression as\n# > the second argument to TypedDict. In particular, a variable that refers to a\n# > dictionary object does not need to be supported, to simplify implementation.\nmy_dict = {\"name\": str}\nBadTypedDict1 = TypedDict(\"BadTypedDict1\", my_dict) # E\n\n\n# This should generate an error because it uses a non-str key.\nBadTypedDict2 = TypedDict(\"BadTypedDict2\", {1: str}) # E\n\n\n# This should generate an error because it uses a non-matching name.\nBadTypedDict3 = TypedDict(\"WrongName\", {\"name\": str}) # E\n\n\n# This should generate an error because of the additional parameter.\nBadTypedDict4 = TypedDict(\"BadTypedDict4\", {\"name\": str}, total=False, other=False) # E\n\n\n# > The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13.\n# > It may also be unsupported by static type checkers.\n\nMovie2 = TypedDict(\"Movie2\", name=str, year=int) # E?\n\nmovie2: Movie2\nmovie2 = {\"name\": \"Blade Runner\", \"year\": 1982} # E?: May generate errors if keyword-argument syntax is unsupported\nmovie2 = {\"name\": \"Blade Runner\", \"year\": \"\"} # E?: Incorrect type for year\n","source":"typing_tests","origin":"conformance/tests/typeddicts_alt_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_14.py","code":"\"\"\"\nTests the class syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import Generic, TypeVar, TypedDict\nimport sys\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n # > String literal forward references are valid in the value types.\n director: \"Person\"\n\n\nclass Person(TypedDict):\n name: str\n age: int\n\n\n# > Methods are not allowed, since the runtime type of a TypedDict object\n# > will always be just dict (it is never a subclass of dict).\nclass BadTypedDict1(TypedDict):\n name: str\n\n # Methods are not allowed, so this should generate an error.\n def method1(self): # E\n pass\n\n # Methods are not allowed, so this should generate an error.\n @classmethod # E[method2]\n def method2(cls): # E[method2]\n pass\n\n # Methods are not allowed, so this should generate an error.\n @staticmethod # E[method3]\n def method3(): # E[method3]\n pass\n\n\nclass CustomMeta(type):\n pass\n\n\n# > Specifying a custom metaclass is not allowed.\nclass BadTypedDict2(TypedDict, metaclass=CustomMeta): # E\n name: str\n\n\n# This should generate an error because \"other\" is not an allowed keyword argument.\nclass BadTypedDict3(TypedDict, other=True): # E\n name: str\n\n# > `if` conditions that the type checker is able to\n# > statically evaluate are also permitted (e.g. `if sys.version_info > (3, 14)`),\n# > in order to specify items that exist only under the given conditions.\nclass ConditionalField(TypedDict):\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nConditionalField(x=1, y=2)\nConditionalField(x=1, y=2, z=3) # E\n\n\n# > TypedDicts may be made generic by adding Generic[T] among the bases.\nT = TypeVar(\"T\")\n\n\nclass GenericTypedDict(TypedDict, Generic[T]):\n name: str\n value: T\n\n\n# > An empty TypedDict can be created by only including pass in the\n# > body (if there is a docstring, pass can be omitted):\nclass EmptyDict1(TypedDict):\n pass\n\n\nclass EmptyDict2(TypedDict):\n \"\"\"Docstring\"\"\"\n\n\nclass MovieTotal(TypedDict, total=True):\n name: str\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n","source":"typing_tests","origin":"conformance/tests/typeddicts_class_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_15.py","code":"\"\"\"\nTests inheritance rules for TypedDict classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclass BookBasedMovie(Movie):\n based_on: str\n\nclass BookBasedMovieAlso(TypedDict):\n name: str\n year: int\n based_on: str\n\nb1: BookBasedMovie = {\"name\": \"Little Women\", \"year\": 2019, \"based_on\": \"Little Women\"}\n\nb2: BookBasedMovieAlso = b1\n\n\nclass X(TypedDict):\n x: int\n\nclass Y(TypedDict):\n y: str\n\nclass XYZ(X, Y):\n z: bool\n\nx1 = XYZ(x=1, y=\"\", z=True)\n\n# > A TypedDict cannot inherit from both a TypedDict type and a\n# > non-TypedDict base class other than Generic.\n\nclass NonTypedDict:\n pass\n\nclass BadTypedDict(TypedDict, NonTypedDict): # E\n pass\n\n\n# > Changing a field type of a parent TypedDict class in a subclass is\n# > not allowed.\n\nclass X1(TypedDict):\n x: str\n\nclass Y1(X1): # E[Y1]\n x: int # E[Y1]: cannot overwrite TypedDict field \"x\"\n\n\n# > Multiple inheritance does not allow conflict types for the same name field:\nclass X2(TypedDict):\n x: int\n\nclass Y2(TypedDict):\n x: str\n\nclass XYZ2(X2, Y2): # E: cannot overwrite TypedDict field \"x\" while merging\n xyz: bool\n","source":"typing_tests","origin":"conformance/tests/typeddicts_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_16.py","code":"\"\"\"\nTests operations provided by a TypedDict object.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#supported-and-unsupported-operations\n\n\nfrom typing import TypedDict, assert_type\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie\n\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982}\nmovie[\"name\"] = \"Other\"\nmovie[\"year\"] = 1981\n\nmovie[\"name\"] = 1982 # E: wrong type\nmovie[\"year\"] = \"\" # E: wrong type\nmovie[\"other\"] = \"\" # E: unknown key added\n\nprint(movie[\"other\"]) # E: unknown key referenced\n\nmovie = {\"name\": \"Blade Runner\"} # E: year is missing\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982.1} # E: year is wrong type\n\n# > The use of a key that is not known to exist should be reported as an error.\nmovie = {\"name\": \"\", \"year\": 1900, \"other\": 2} # E: extra key\n\n\ndef func1(variable_key: str):\n # > A key that is not a literal should generally be rejected.\n movie: Movie = {variable_key: \"\", \"year\": 1900} # E: variable key\n\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"name\")\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"other\") # E?\n\n\nmovie.clear() # E: clear not allowed\n\ndel movie[\"name\"] # E: del not allowed for required key\n\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n year: int\n\n\nmovie_optional: MovieOptional = {}\n\nassert_type(movie_optional.get(\"name\"), str | None)\n\nmovie_optional.clear() # E: clear not allowed\n\ndel movie_optional[\"name\"]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_operations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_17.py","code":"\"\"\"\nTests the type consistency rules for TypedDict objects.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#type-consistency\n\nfrom typing import Any, Literal, Mapping, TypedDict\n\n\nclass A1(TypedDict):\n x: int | None\n\n\nclass B1(TypedDict):\n x: int\n\n\nb1: B1 = {\"x\": 0}\n\n# > Value types behave invariantly.\na1: A1 = b1 # E: 'B1' not compatible with 'A1'\n\n# > any TypedDict type is consistent with Mapping[str, object]\nv1: Mapping[str, object] = b1\n\n# > A TypedDict type with a required key is not consistent with a TypedDict\n# > type where the same key is a non-required key.\n\nclass A2(TypedDict, total=False):\n x: int\n\n\nclass B2(TypedDict):\n x: int\n\n\nb2: B2 = {\"x\": 0}\na2: A2 = b2 # E: 'B2' not compatible with 'A2'\n\n\n# > A TypedDict type A is consistent with TypedDict B if A is structurally\n# > compatible with B. This is true if and only if both of these conditions\n# > are satisfied:\n# > 1. For each key in B, A has the corresponding key and the corresponding\n# > value type in A is consistent with the value type in B. For each key in B,\n# > the value type in B is also consistent with the corresponding value type\n# > in A.\n# > 2. For each required key in B, the corresponding key is required in A. For\n# > each non-required key in B, the corresponding key is not required in A.\n\n\nclass A3(TypedDict):\n x: int\n\n\nclass B3(TypedDict):\n x: int\n y: int\n\n\nb3: B3 = {\"x\": 0, \"y\": 0}\na3: A3 = b3\n\na3 = {\"x\": 0}\nb3 = a3 # E\n\n\n# This should generate an error because it's a literal assignment.\na3_1: A3 = {\"x\": 0, \"y\": 0} # E\n\n# This should not generate an error.\na3_2 = b3\n\n# > A TypedDict isn’t consistent with any Dict[...] type.\n\nd1: dict[str, int] = b3 # E\nd2: dict[str, object] = b3 # E\nd3: dict[Any, Any] = b3 # E\n\n# > A TypedDict with all int values is not consistent with Mapping[str, int].\n\nm1: Mapping[str, int] = b3 # E\nm2: Mapping[str, object] = b3 # OK\nm3: Mapping[str, Any] = b3 # OK\n\n\n# Test \"get\" method.\nUserType1 = TypedDict(\"UserType1\", {\"name\": str, \"age\": int}, total=False)\nuser1: UserType1 = {\"name\": \"Bob\", \"age\": 40}\n\nname1: str = user1.get(\"name\", \"n/a\")\nage1: int = user1.get(\"age\", 42)\n\nUserType2 = TypedDict(\"UserType2\", {\"name\": str, \"age\": int})\nuser2: UserType2 = {\"name\": \"Bob\", \"age\": 40}\n\nname2: str | None = user2.get(\"name\")\n\n# The spec does not say whether type checkers should adjust the return type of `.get()`\n# to exclude `None` if it is known that the key exists. Either option is acceptable.\nname3: str = user2.get(\"name\") # E?\n\nage2: int = user2.get(\"age\", 42)\n\nage3: int | str = user2.get(\"age\", \"42\")\n\nage4: int = user2.get(\"age\", \"42\") # E?\n\n# Test nested TypedDicts.\nclass Inner1(TypedDict):\n inner_key: str\n\n\nclass Inner2(TypedDict):\n inner_key: Inner1\n\n\nclass Outer1(TypedDict):\n outer_key: Inner2\n\n\no1: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": \"hi\"}}}\n\n# This should generate an error because the inner-most value\n# should be a string.\no2: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": 1}}} # E\n\n\nclass Inner3(TypedDict):\n x: int\n\n\nclass Inner4(TypedDict):\n x: int\n\n\nclass Outer2(TypedDict):\n y: str\n z: Literal[\"\"] | Inner3\n\n\nclass Outer3(TypedDict):\n y: str\n z: Literal[\"\"] | Inner4\n\n\ndef func1(td: Outer3):\n ...\n\n\no3: Outer2 = {\"y\": \"\", \"z\": {\"x\": 0}}\no4: Outer3 = o3\n","source":"typing_tests","origin":"conformance/tests/typeddicts_type_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_18.py","code":"\"\"\"\nTests for basic usage of TypedDict.\n\"\"\"\n\nfrom typing import TypeVar, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982}\n\n\ndef record_movie(movie: Movie) -> None:\n ...\n\n\nrecord_movie({\"name\": \"Blade Runner\", \"year\": 1982})\n\n\nmovie[\"director\"] = \"Ridley Scott\" # E: invalid key 'director'\nmovie[\"year\"] = \"1982\" # E: invalid value type (\"int\" expected)\n\n# The code below should be rejected, since 'title' is not a valid key,\n# and the 'name' key is missing:\nmovie2: Movie = {\"title\": \"Blade Runner\", \"year\": 1982} # E\n\nm = Movie(name='Blade Runner', year=1982)\n\n\n# > TypedDict type objects cannot be used in isinstance() tests such as\n# > isinstance(d, Movie).\nif isinstance(movie, Movie): # E\n pass\n\n\n# TypedDict should not be allowed as a bound for a TypeVar.\nT = TypeVar(\"T\", bound=TypedDict) # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"typed-kwargs","pep":"692","introduced_in":"3.12","form":"modern","file":"typed-kwargs/modern_01.py","code":"\"\"\"\nTests the use of an unpacked TypedDict for annotating **kwargs.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#unpack-for-keyword-arguments\n\n# This sample tests the handling of Unpack[TypedDict] when used with\n# a **kwargs parameter in a function signature.\n\nfrom typing import Protocol, TypeVar, TypedDict, NotRequired, Required, Unpack, assert_type\n\n\nclass TD1(TypedDict):\n v1: Required[int]\n v2: NotRequired[str]\n\n\nclass TD2(TD1):\n v3: Required[str]\n\n\ndef func1(**kwargs: Unpack[TD2]) -> None:\n v1 = kwargs[\"v1\"]\n assert_type(v1, int)\n\n # > Type checkers may allow reading an item using ``d['x']`` even if\n # > the key ``'x'`` is not required\n kwargs[\"v2\"] # E?: v2 may not be present\n\n if \"v2\" in kwargs:\n v2 = kwargs[\"v2\"]\n assert_type(v2, str)\n\n v3 = kwargs[\"v3\"]\n assert_type(v3, str)\n\n\ndef func2(v3: str, **kwargs: Unpack[TD1]) -> None:\n # > When Unpack is used, type checkers treat kwargs inside the function\n # > body as a TypedDict.\n assert_type(kwargs, TD1)\n\n\ndef func3() -> None:\n # Mypy reports multiple errors here.\n func1() # E: missing required keyword args\n func1(v1=1, v2=\"\", v3=\"5\") # OK\n\n td2 = TD2(v1=2, v3=\"4\")\n func1(**td2) # OK\n func1(v1=1, v2=\"\", v3=\"5\", v4=5) # E?: v4 is not in TD2, but could be in a subtype\n func1(1, \"\", \"5\") # E: args not passed by position\n\n # > Passing a dictionary of type dict[str, object] as a **kwargs argument\n # > to a function that has **kwargs annotated with Unpack must generate a\n # > type checker error.\n my_dict: dict[str, str] = {}\n func1(**my_dict) # E: untyped dict\n\n d1 = {\"v1\": 2, \"v3\": \"4\", \"v4\": 4}\n func1(**d1) # E?: OK or Type error (spec allows either)\n func2(**td2) # OK\n func1(v1=2, **td2) # E: v1 is already specified\n func2(1, **td2) # E: v1 is already specified\n func2(v1=1, **td2) # E: v1 is already specified\n\n\nclass TDProtocol1(Protocol):\n def __call__(self, *, v1: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol2(Protocol):\n def __call__(self, *, v1: int, v3: str, v2: str = \"\") -> None:\n ...\n\n\nclass TDProtocol3(Protocol):\n def __call__(self, *, v1: int, v2: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol4(Protocol):\n def __call__(self, *, v1: int) -> None:\n ...\n\n\nclass TDProtocol5(Protocol):\n def __call__(self, v1: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol6(Protocol):\n def __call__(self, **kwargs: Unpack[TD2]) -> None:\n ...\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#assignment\n\nv1: TDProtocol1 = func1 # OK\nv2: TDProtocol2 = func1 # OK\nv3: TDProtocol3 = func1 # E: v2 is wrong type\nv4: TDProtocol4 = func1 # E: v3 is missing\nv5: TDProtocol5 = func1 # E: params are positional\nv6: TDProtocol6 = func1 # OK\n\n\ndef func4(v1: int, /, **kwargs: Unpack[TD2]) -> None:\n ...\n\n\ndef func5(v1: int, **kwargs: Unpack[TD2]) -> None: # E: parameter v1 overlaps with the TypedDict.\n ...\n\n\nT = TypeVar(\"T\", bound=TD2)\n\n# > TypedDict is the only permitted heterogeneous type for typing **kwargs.\n# > Therefore, in the context of typing **kwargs, using Unpack with types other\n# > than TypedDict should not be allowed and type checkers should generate\n# > errors in such cases.\n\ndef func6(**kwargs: Unpack[T]) -> None: # E: unpacked value must be a TypedDict, not a TypeVar bound to TypedDict.\n ...\n\n# > The situation where the destination callable contains **kwargs: Unpack[TypedDict] and\n# > the source callable doesn’t contain **kwargs should be disallowed. This is because,\n# > we cannot be sure that additional keyword arguments are not being passed in when an instance of a subclass\n# > had been assigned to a variable with a base class type and then unpacked in the destination callable invocation\n\ndef func7(*, v1: int, v3: str, v2: str = \"\") -> None:\n ...\n\n\nv7: TDProtocol6 = func7 # E: source does not have kwargs\n","source":"typing_tests","origin":"conformance/tests/callables_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"typed-kwargs","pep":"692","introduced_in":"3.12","form":"modern","file":"typed-kwargs/modern_02.py","code":"\"\"\"\nTests the use of unpacked TypedDicts with read-only items when used to annotate\na **kwargs parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Protocol, TypedDict, Unpack\nfrom typing_extensions import ReadOnly\n\n# > :pep:`692` introduced ``Unpack`` to annotate ``**kwargs`` with a\n# > ``TypedDict``. Marking one or more of the items of a ``TypedDict`` used\n# > in this way as read-only will have no effect on the type signature of\n# > the method. However, it *will* prevent the item from being modified in\n# > the body of the function.\n\n\nclass Args(TypedDict):\n key1: int\n key2: str\n\n\nclass ReadOnlyArgs(TypedDict):\n key1: ReadOnly[int]\n key2: ReadOnly[str]\n\n\nclass Function(Protocol):\n def __call__(self, **kwargs: Unpack[Args]) -> None: ...\n\n\ndef impl(**kwargs: Unpack[ReadOnlyArgs]) -> None:\n kwargs[\"key1\"] = 3 # E\n\n\nfn: Function = impl # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_13.py","code":"\"\"\"\nTests for the use of TypeVarTuple with \"*args\" parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#args-as-a-type-variable-tuple\n\n# > If *args is annotated as a type variable tuple, the types of the individual\n# > arguments become the types in the type variable tuple.\n\nfrom typing import TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef args_to_tuple(*args: *Ts) -> tuple[*Ts]:\n raise NotImplementedError\n\n\nclass Env:\n ...\n\n\ndef exec_le(path: str, *args: *tuple[*Ts, Env], env: Env | None = None) -> tuple[*Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(x: int, y: str):\n assert_type(args_to_tuple(x, y), tuple[int, str])\n\n assert_type(exec_le(\"\", Env()), tuple[()]) # OK\n assert_type(exec_le(y, x, y, Env()), tuple[int, str]) # OK\n exec_le(\"\", 0, \"\") # E\n exec_le(\"\", 0, \"\", env=Env()) # E\n\n\n# > Using an unpacked unbounded tuple is equivalent to the\n# > PEP 484#arbitrary-argument-lists-and-default-argument-values behavior of\n# > *args: int, which accepts zero or more values of type int.\n\n\ndef func1(*args: *tuple[int, ...]) -> None:\n ...\n\n\nfunc1() # OK\nfunc1(1, 2, 3, 4, 5) # OK\nfunc1(1, \"2\", 3) # E\n\n\ndef func2(*args: *tuple[int, *tuple[str, ...], str]) -> None:\n ...\n\n\nfunc2(1, \"\") # OK\nfunc2(1, \"\", \"\", \"\", \"\") # OK\nfunc2(1, 1, \"\") # E\nfunc2(1) # E\nfunc2(\"\") # E\n\n\ndef func3(*args: *tuple[int, str]) -> None:\n ...\n\n\nfunc3(1, \"hello\") # OK\nfunc3(1) # E\n\n\ndef func4(*args: tuple[*Ts]):\n ...\n\n\nfunc4((0,), (1,)) # OK\nfunc4((0,), (1, 2)) # E (length mismatch)\nfunc4((0,), (\"1\",)) # OK\n\n\n# This is a syntax error, so leave it commented out.\n# def func5(**kwargs: *Ts): # E\n# ...\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_14.py","code":"\"\"\"\nTests basic usage of TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#typevartuple\n\nfrom typing import Generic, NewType, TypeVarTuple, assert_type\n\nTs = TypeVarTuple(\"Ts\")\nTs1 = TypeVarTuple(\"Ts1\")\n\n\nclass Array1(Generic[*Ts]):\n ...\n\n\ndef func1(*args: *Ts) -> tuple[*Ts]:\n raise NotImplementedError\n\n\nShape = TypeVarTuple(\"Shape\")\n\n\nclass Array(Generic[*Shape]):\n def __init__(self, shape: tuple[*Shape]):\n self._shape: tuple[*Shape] = shape\n\n def get_shape(self) -> tuple[*Shape]:\n return self._shape\n\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nTime = NewType(\"Time\", int)\nBatch = NewType(\"Batch\", int)\n\nv1: Array[Height, Width] = Array((Height(1), Width(2))) # OK\nv2: Array[Batch, Height, Width] = Array((Batch(1), Height(1), Width(1))) # OK\nv3: Array[Time, Batch, Height, Width] = Array(\n (Time(1), Batch(1), Height(1), Width(1))\n) # OK\n\nv4: Array[Height, Width] = Array(Height(1)) # E\nv5: Array[Batch, Height, Width] = Array((Batch(1), Width(1))) # E\nv6: Array[Time, Batch, Height, Width] = Array( # E[v6]\n (Time(1), Batch(1), Width(1), Height(1)) # E[v6]\n)\n\n\n# > Type Variable Tuples Must Always be Unpacked\n\n\nclass ClassA(Generic[Shape]): # E: not unpacked\n def __init__(self, shape: tuple[Shape]): # E: not unpacked\n self._shape: tuple[*Shape] = shape\n\n def get_shape(self) -> tuple[Shape]: # E: not unpacked\n raise NotImplementedError\n\n def method1(*args: Shape) -> None: # E: not unpacked\n ...\n\n\n# > TypeVarTuple does not support type constraints.\n\nTs2 = TypeVarTuple(\"Ts2\", int, float) # E\nTs3 = TypeVarTuple(\"Ts3\", bound=int) # E: bound is unavailable in Python 3.12\n\n\n# > If the same TypeVarTuple instance is used in multiple places in a signature\n# > or class, a valid type inference might be to bind the TypeVarTuple to a\n# > tuple of a union of types.\n\n\ndef func2(arg1: tuple[*Ts], arg2: tuple[*Ts]) -> tuple[*Ts]:\n raise NotImplementedError\n\n\n# > We do not allow this; type unions may not appear within the tuple.\n# > If a type variable tuple appears in multiple places in a signature,\n# > the types must match exactly (the list of type parameters must be the\n# > same length, and the type parameters themselves must be identical)\n\ndef check_func2(x: int):\n assert_type(func2((x,), (1,)), tuple[int]) # OK\nfunc2((0,), (0.0,)) # OK\nfunc2((0.0,), (0,)) # OK\nfunc2((0,), (1,)) # OK\n\nfunc2((0,), (\"0\",)) # OK\nfunc2((0, 0), (0,)) # E\n\n\ndef multiply(x: Array[*Shape], y: Array[*Shape]) -> Array[*Shape]:\n raise NotImplementedError\n\n\ndef func3(x: Array[Height], y: Array[Width], z: Array[Height, Width]):\n multiply(x, x) # OK\n multiply(x, y) # E\n multiply(x, z) # E\n\n\n# > Only a single type variable tuple may appear in a type parameter list.\n\n\nclass Array3(Generic[*Ts, *Ts1]): # E\n ...\n\n\nclass Array4[*Ts1, *Ts2]: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_15.py","code":"\"\"\"\nTests the use of TypeVarTuple within a Callable.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variable-tuples-with-callable\n\n# > Type variable tuples can also be used in the arguments section of a Callable.\n\n\nfrom typing import Callable, TypeVar, TypeVarTuple, assert_type\n\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Process:\n def __init__(self, target: Callable[[*Ts], None], args: tuple[*Ts]) -> None:\n ...\n\n\ndef func1(arg1: int, arg2: str) -> None:\n ...\n\n\nProcess(target=func1, args=(0, \"\")) # OK\nProcess(target=func1, args=(\"\", 0)) # E\n\n\ndef func2(f: Callable[[int, *Ts, T], tuple[T, *Ts]]) -> tuple[*Ts, T]:\n raise NotImplementedError\n\n\ndef callback1(a: int, b: str, c: int, d: complex) -> tuple[complex, str, int]:\n raise NotImplementedError\n\n\ndef callback2(a: int, d: str) -> tuple[str]:\n raise NotImplementedError\n\n\nassert_type(func2(callback1), tuple[str, int, complex])\nassert_type(func2(callback2), tuple[str])\n\n\ndef func3(*args: *tuple[int, *Ts, T]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(a: int, b: str, c: float, d: complex):\n assert_type(func3(a, b, c, d), tuple[complex, str, float])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_callable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_16.py","code":"\"\"\"\nTests type concatenation using TypeVarTuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-concatenation\n\n# > Type variable tuples don’t have to be alone; normal types can be prefixed and/or suffixed.\n\nfrom typing import Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nShape = TypeVarTuple(\"Shape\")\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef add_batch_axis(x: Array[*Shape]) -> Array[Batch, *Shape]:\n raise NotImplementedError\n\n\ndef del_batch_axis(x: Array[Batch, *Shape]) -> Array[*Shape]:\n raise NotImplementedError\n\n\ndef add_batch_channels(x: Array[*Shape]) -> Array[Batch, *Shape, Channels]:\n raise NotImplementedError\n\n\ndef func1(a: Array[Height, Width]):\n b = add_batch_axis(a) # OK\n assert_type(b, Array[Batch, Height, Width])\n c = del_batch_axis(b) # OK\n assert_type(c, Array[Height, Width])\n d = add_batch_channels(a) # OK\n assert_type(d, Array[Batch, Height, Width, Channels])\n\n\ndef prefix_tuple(x: T, y: tuple[*Ts]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef call_prefix_tuple(x: int, y: bool, z: str):\n result = prefix_tuple(x=x, y=(y, z))\n assert_type(result, tuple[int, bool, str])\n\n\ndef move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n return (*tup[1:], tup[0])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_concat.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_17.py","code":"\"\"\"\nTests the use of TypeVarTuple in function overloads.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#overloads-for-accessing-individual-types\n\nfrom typing import Any, Generic, TypeVar, TypeVarTuple, assert_type, overload\n\n\nShape = TypeVarTuple(\"Shape\")\nAxis1 = TypeVar(\"Axis1\")\nAxis2 = TypeVar(\"Axis2\")\nAxis3 = TypeVar(\"Axis3\")\n\n\nclass Array(Generic[*Shape]):\n @overload\n def transpose(self: \"Array[Axis1, Axis2]\") -> \"Array[Axis2, Axis1]\":\n ...\n\n @overload\n def transpose(self: \"Array[Axis1, Axis2, Axis3]\") -> \"Array[Axis3, Axis2, Axis1]\":\n ...\n\n def transpose(self) -> Any:\n raise NotImplementedError\n\n\ndef func1(a: Array[Axis1, Axis2], b: Array[Axis1, Axis2, Axis3]):\n assert_type(a.transpose(), Array[Axis2, Axis1])\n assert_type(b.transpose(), Array[Axis3, Axis2, Axis1])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_overloads.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_18.py","code":"\"\"\"\nTests the handling of a TypeVarTuple specialization.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#behaviour-when-type-parameters-are-not-specified\n\nfrom typing import Any, Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nTime = NewType(\"Time\", int)\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef takes_any_array1(arr: Array):\n ...\n\n\ndef takes_any_array2(arr: Array[*tuple[Any, ...]]):\n ...\n\n\ndef func1(x: Array[Height, Width]):\n takes_any_array1(x) # OK\n takes_any_array2(x) # OK\n\n\ndef func2(y: Array[Time, Height, Width]):\n takes_any_array1(y) # OK\n takes_any_array2(y) # OK\n\n\n# > Generic aliases can be created using a type variable tuple in a similar\n# > way to regular type variables.\n\nIntTuple = tuple[int, *Ts]\nNamedArray = tuple[str, Array[*Ts]]\n\n\ndef func3(a: IntTuple[float, bool], b: NamedArray[Height]):\n assert_type(a, tuple[int, float, bool])\n assert_type(b, tuple[str, Array[Height]])\n\n\ndef func4(a: IntTuple[()], b: NamedArray[()]):\n assert_type(a, tuple[int])\n assert_type(b, tuple[str, Array[()]])\n\n\nShape = TypeVarTuple(\"Shape\")\nDType = TypeVar(\"DType\")\n\n\nclass Array2(Generic[DType, *Shape]):\n ...\n\n\nFloatArray = Array2[float, *Shape]\nArray1D = Array2[DType, Any]\n\n\ndef func5_0(a: Array1D, b: Array1D[int]):\n assert_type(a, Array2[Any, Any])\n assert_type(b, Array2[int, Any])\n\n\ndef takes_float_array_of_any_shape(x: FloatArray):\n ...\n\n\ndef func5_1(x: FloatArray[Height, Width]):\n takes_float_array_of_any_shape(x) # OK\n\n\ndef takes_float_array_with_specific_shape(y: FloatArray[Height, Width]):\n ...\n\n\ndef func5_2(x: FloatArray):\n takes_float_array_with_specific_shape(x) # OK\n\n\nT = TypeVar(\"T\")\nVariadicTuple = tuple[T, *Ts]\n\n\ndef func6(a: VariadicTuple[str, int], b: VariadicTuple[float], c: VariadicTuple):\n assert_type(a, tuple[str, int])\n assert_type(b, tuple[float])\n assert_type(c, tuple[Any, *tuple[Any, ...]])\n\n\nTs1 = TypeVarTuple(\"Ts1\")\nTs2 = TypeVarTuple(\"Ts2\")\n\nIntTupleVar = tuple[int, *Ts1] # OK\nIntFloatTupleVar = IntTupleVar[float, *Ts2] # OK\nIntFloatsTupleVar = IntTupleVar[*tuple[float, ...]] # OK\n\n\nIntTupleGeneric = tuple[int, T]\n\nIntTupleGeneric[str] # OK\nIntTupleGeneric[*Ts] # E\nIntTupleGeneric[*tuple[float, ...]] # E\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nTA1 = tuple[*Ts, T1, T2] # OK\nTA2 = tuple[T1, T2, *Ts] # OK\nTA3 = tuple[T1, *Ts, T2, T3] # OK\nTA4 = tuple[T1, T2, *tuple[int, ...]] # OK\nTA5 = tuple[T1, *Ts, T2, *Ts] # E\nTA6 = tuple[T1, *Ts, T2, *tuple[int, ...]] # E\n\n\nTA7 = tuple[*Ts, T1, T2]\n\nv1: TA7[int] # E: requires at least two type arguments\n\n\ndef func7(a: TA7[*Ts, T1, T2]) -> tuple[tuple[*Ts], T1, T2]:\n raise NotImplementedError\n\n\ndef func8(a: TA7[str, bool], b: TA7[str, bool, float], c: TA7[str, bool, float, int]):\n assert_type(func7(a), tuple[tuple[()], str, bool])\n assert_type(func7(b), tuple[tuple[str], bool, float])\n assert_type(func7(c), tuple[tuple[str, bool], float, int])\n\n\nTA8 = tuple[T1, *Ts, T2, T3]\n\n\ndef func9(a: TA8[T1, *Ts, T2, T3]) -> tuple[tuple[*Ts], T1, T2, T3]:\n raise NotImplementedError\n\n\ndef func10(a: TA8[str, bool, float], b: TA8[str, bool, float, int]):\n assert_type(func9(a), tuple[tuple[()], str, bool, float])\n assert_type(func9(b), tuple[tuple[bool], str, float, int])\n\n\nTA9 = tuple[*Ts, T1]\nTA10 = TA9[*tuple[int, ...]] # OK\n\n\ndef func11(a: TA10, b: TA9[*tuple[int, ...], str], c: TA9[*tuple[int, ...], str]):\n assert_type(a, tuple[*tuple[int, ...], int])\n assert_type(b, tuple[*tuple[int, ...], str])\n assert_type(c, tuple[*tuple[int, ...], str])\n\n\nTA11 = tuple[T, *Ts1]\nTA12 = TA11[*Ts2] # E\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_19.py","code":"\"\"\"\nTests unpack operations for TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#unpacking-tuple-types\n\nfrom typing import Any, Generic, NewType, TypeVarTuple\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nTs = TypeVarTuple(\"Ts\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef process_batch_channels(x: Array[Batch, *tuple[Any, ...], Channels]) -> None:\n ...\n\n\ndef func3(\n x: Array[Batch, Height, Width, Channels], y: Array[Batch, Channels], z: Array[Batch]\n):\n process_batch_channels(x) # OK\n process_batch_channels(y) # OK\n process_batch_channels(z) # E\n\n\nShape = TypeVarTuple(\"Shape\")\n\n\ndef expect_variadic_array(x: Array[Batch, *Shape]) -> None:\n ...\n\n\ndef expect_precise_array(x: Array[Batch, Height, Width, Channels]) -> None:\n ...\n\n\ndef func4(y: Array[*tuple[Any, ...]]):\n expect_variadic_array(y) # OK\n expect_precise_array(y) # OK\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_unpack.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_20.py","code":"\"\"\"\nTests variance of TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance-inference\n\n\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple\n\nclass InvariantTypeVarTuple[*InOutTs]:\n a: tuple[*InOutTs]\n\nin_out_obj: InvariantTypeVarTuple[object] = InvariantTypeVarTuple[int]() # E\nin_out_int: InvariantTypeVarTuple[int] = InvariantTypeVarTuple[object]() # E\nin_out_int = InvariantTypeVarTuple[int]()\nin_out_variadic_int: InvariantTypeVarTuple[*tuple[int, ...]] = InvariantTypeVarTuple[*tuple[object, ...]]() # E\nin_out_variadic_object: InvariantTypeVarTuple[*tuple[object, ...]] = InvariantTypeVarTuple[*tuple[int, ...]]() # E\nin_out_empty: InvariantTypeVarTuple[()] = InvariantTypeVarTuple[()]() # OK\nin_out_fixed_from_variadic: InvariantTypeVarTuple[int] = InvariantTypeVarTuple[*tuple[int, ...]]() # E\nin_out_variadic_from_fixed: InvariantTypeVarTuple[*tuple[int, ...]] = InvariantTypeVarTuple[int]() # E\n\n\nclass ContravariantTypeVarTuple[*InTs]:\n def f(self, t: tuple[*InTs]):\n raise NotImplementedError\n\nin_obj: ContravariantTypeVarTuple[object, object] = ContravariantTypeVarTuple[object, int]() # E\nin_int: ContravariantTypeVarTuple[int] = ContravariantTypeVarTuple[object]() # OK\nin_variadic_int: ContravariantTypeVarTuple[*tuple[int, ...]] = ContravariantTypeVarTuple[*tuple[object, ...]]() # OK\nin_variadic_object: ContravariantTypeVarTuple[*tuple[object, ...]] = ContravariantTypeVarTuple[*tuple[int, ...]]() # E\nin_empty: ContravariantTypeVarTuple[()] = ContravariantTypeVarTuple[()]() # OK\nin_fixed_from_variadic: ContravariantTypeVarTuple[int] = ContravariantTypeVarTuple[*tuple[int, ...]]() # OK\nin_variadic_from_fixed: ContravariantTypeVarTuple[*tuple[int, ...]] = ContravariantTypeVarTuple[int]() # E\n\n\nclass CovariantTypeVarTuple[*OutTs]:\n def f(self) -> tuple[*OutTs]:\n raise NotImplementedError\n\n\nout_int: CovariantTypeVarTuple[int] = CovariantTypeVarTuple[object]() # E\nout_obj: CovariantTypeVarTuple[object] = CovariantTypeVarTuple[int]() # OK\nout_multiple1: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[bool, bool]() # OK\nout_multiple2: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[bool, object]() # E\nout_multiple3: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[object, bool]() # E\nout_multiple4: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[object, object]() # E\nout_variadic_int: CovariantTypeVarTuple[*tuple[int, ...]] = CovariantTypeVarTuple[*tuple[object, ...]]() # E\nout_variadic_object: CovariantTypeVarTuple[*tuple[object, ...]] = CovariantTypeVarTuple[*tuple[int, ...]]() # OK\nout_empty: CovariantTypeVarTuple[()] = CovariantTypeVarTuple[()]() # OK\nout_fixed_from_variadic: CovariantTypeVarTuple[int] = CovariantTypeVarTuple[*tuple[int, ...]]() # E\nout_variadic_from_fixed: CovariantTypeVarTuple[*tuple[int, ...]] = CovariantTypeVarTuple[int]() # OK\n\nTs = TypeVarTuple(\"Ts\") # OK\nInferTs = TypeVarTuple(\"InferTs\", infer_variance=True) # OK\nInvTs1 = TypeVarTuple(\"InvTs1\", covariant=True, contravariant=True) # E\nInvTs2 = TypeVarTuple(\"InvTs2\", covariant=True, infer_variance=True) # E\nInvTs3 = TypeVarTuple(\"InvTs3\", contravariant=True, infer_variance=True) # E\n\nclass InvariantTypeVarTupleOld(Generic[*Ts]):\n def in_f(self, *args: *Ts) -> None: # OK\n raise NotImplementedError\n\n def out_f(self) -> tuple[*Ts]: # OK\n raise NotImplementedError\n\n\nobj_old: InvariantTypeVarTupleOld[object] = InvariantTypeVarTupleOld[int]() # E\nint_old: InvariantTypeVarTupleOld[int] = InvariantTypeVarTupleOld[object]() # E\nint_old = InvariantTypeVarTupleOld[int]()\n\n\nInTs = TypeVarTuple(\"InTs\", contravariant=True)\n\nclass ContravariantTypeVarTupleOld(Generic[*InTs]):\n def in_f(self, *args: *InTs) -> None: # OK\n raise NotImplementedError\n\n def out_f(self) -> tuple[*InTs]: # E\n raise NotImplementedError\n\n\nin_obj_old: ContravariantTypeVarTupleOld[object] = ContravariantTypeVarTupleOld[int]() # E\nin_int_old: ContravariantTypeVarTupleOld[int] = ContravariantTypeVarTupleOld[object]() # OK\n\n\nOutTs = TypeVarTuple(\"OutTs\", covariant=True)\n\nclass CovariantTypeVarTupleOld(Generic[*OutTs]):\n def in_f(self, *args: *OutTs) -> None: # E\n raise NotImplementedError\n\n def out_f(self) -> tuple[*OutTs]: # OK\n raise NotImplementedError\n\n\nout_int_old: CovariantTypeVarTupleOld[int] = CovariantTypeVarTupleOld[object]() # E\nout_obj_old: CovariantTypeVarTupleOld[object] = CovariantTypeVarTupleOld[int]() # OK\n\n\n# `infer_variance=True` on a traditional `TypeVarTuple`\nclass InferredContravariantTypeVarTupleOld(Generic[*InferTs]):\n def in_f(self, *args: *InferTs) -> None: # OK\n raise NotImplementedError\n\n\ninfer_in_obj_old: InferredContravariantTypeVarTupleOld[object] = InferredContravariantTypeVarTupleOld[int]() # E\ninfer_in_int_old: InferredContravariantTypeVarTupleOld[int] = InferredContravariantTypeVarTupleOld[object]() # OK\n\n\nclass InferredCovariantTypeVarTupleOld(Generic[*InferTs]):\n def out_f(self) -> tuple[*InferTs]: # OK\n raise NotImplementedError\n\n\ninfer_out_int_old: InferredCovariantTypeVarTupleOld[int] = InferredCovariantTypeVarTupleOld[object]() # E\ninfer_out_obj_old: InferredCovariantTypeVarTupleOld[object] = InferredCovariantTypeVarTupleOld[int]() # OK\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_21.py","code":"\"\"\"\nTests the handling of unpacked tuples embedded within other tuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#unpacked-tuple-form\n\n# > An unpacked form of ``tuple`` (using an unpack operator ``*``)\n# > can be used within a tuple type argument list\n\n# > Unpacking a concrete tuple type is analogous to unpacking a tuple of values at runtime.\n\n\nfrom typing import TypeVarTuple, Unpack, assert_type\n\n\ndef func1(x: tuple[int, *tuple[bool, bool], str]):\n assert_type(x, tuple[int, bool, bool, str])\n assert_type(x, tuple[*tuple[int, bool], bool, str])\n assert_type(x, tuple[int, bool, *tuple[bool, str]])\n\n\n# > Unpacking an unbounded tuple preserves the unbounded tuple as it is.\n\n\ndef func2(x: tuple[int, *tuple[bool, ...], str]):\n assert_type(x, tuple[int, *tuple[bool, ...], str])\n\n\n# > For example, tuple[int, *tuple[str]] is equivalent to tuple[int, str].\n\nu1: tuple[*tuple[int], *tuple[int]] = (int(1), int(1)) # OK\nassert_type(u1, tuple[int, int])\nu2: tuple[*tuple[int, ...], *tuple[int]] # OK\n\n\n# > Only one unbounded tuple can be used within another tuple:\n\nt1: tuple[*tuple[str], *tuple[str]] # OK\nt2: tuple[*tuple[str, *tuple[str, ...]]] # OK\nt3: tuple[*tuple[str, ...], *tuple[int, ...]] # E\nt4: tuple[*tuple[str, *tuple[str, ...]], *tuple[int, ...]] # E\n\n\n# > An unpacked TypeVarTuple counts as an unbounded tuple in the context of this rule\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef func3(t: tuple[*Ts]):\n t5: tuple[*tuple[str], *Ts] # OK\n t6: tuple[*tuple[str, ...], *Ts] # E\n\n\n# > The ``*`` syntax requires Python 3.11 or newer. For older versions of Python,\n# > the ``typing.Unpack`` special form can be used:\n\nt11: tuple[Unpack[tuple[str]], Unpack[tuple[str]]] # OK\nt12: tuple[Unpack[tuple[str, Unpack[tuple[str, ...]]]]] # OK\nt13: tuple[Unpack[tuple[str, ...]], Unpack[tuple[int, ...]]] # E\nt14: tuple[ # E[t14]\n Unpack[tuple[str, Unpack[tuple[str, ...]]]], Unpack[tuple[int, ...]] # E[t14]\n]\n","source":"typing_tests","origin":"conformance/tests/tuples_unpacked.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n an = g.__anext__()\n try:\n while True:\n try:\n an.__next__()\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n break\n else:\n res.append('EMPTY StopIteration')\n break\n except StopAsyncIteration:\n raise\n except Exception as ex:\n res.append(str(type(ex)))\n break\n except StopAsyncIteration:\n res.append('STOP')\n break\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_exception_11(self):\n def sync_gen():\n yield 10\n yield 20\n\n def sync_gen_wrapper():\n yield 1\n sg = sync_gen()\n sg.send(None)\n try:\n sg.throw(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n async def async_gen():\n yield 10\n yield 20\n\n async def async_gen_wrapper():\n yield 1\n asg = async_gen()\n await asg.asend(None)\n try:\n await asg.athrow(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())\n\n def test_async_gen_exception_12(self):\n async def gen():\n with self.assertWarnsRegex(RuntimeWarning,\n f\"coroutine method 'asend' of '{gen.__qualname__}' \"\n f\"was never awaited\"):\n await anext(me)\n yield 123\n\n me = gen()\n ai = me.__aiter__()\n an = ai.__anext__()\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n an.__next__()\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"):\n an.send(None)\n\n def test_async_gen_asend_throw_concurrent_with_send(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n return\n yield\n\n\n agen = agenfn()\n gen = agen.asend(None)\n gen.send(None)\n gen2 = agen.asend(None)\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_athrow_throw_concurrent_with_send(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n return\n yield\n\n\n agen = agenfn()\n gen = agen.asend(None)\n gen.send(None)\n gen2 = agen.athrow(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r'athrow\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_asend_throw_concurrent_with_throw(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n try:\n yield\n except MyExc:\n pass\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n\n\n agen = agenfn()\n with self.assertRaises(StopIteration):\n agen.asend(None).send(None)\n\n gen = agen.athrow(MyExc)\n gen.throw(MyExc)\n gen2 = agen.asend(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_athrow_throw_concurrent_with_throw(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n try:\n yield\n except MyExc:\n pass\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n\n agen = agenfn()\n with self.assertRaises(StopIteration):\n agen.asend(None).send(None)\n\n gen = agen.athrow(MyExc)\n gen.throw(MyExc)\n gen2 = agen.athrow(None)\n\n with self.assertRaisesRegex(RuntimeError,\n r'athrow\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_3_arg_deprecation_warning(self):\n async def gen():\n yield 123\n\n with self.assertWarns(DeprecationWarning):\n x = gen().athrow(GeneratorExit, GeneratorExit(), None)\n with self.assertRaises(GeneratorExit):\n x.send(None)\n del x\n gc_collect()\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n aclose = g.aclose()\n self.assertTrue(inspect.isawaitable(aclose))\n aclose.close()\n\n def test_async_gen_asend_close_runtime_error(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n async def agenfn():\n try:\n await _async_yield(None)\n except GeneratorExit:\n await _async_yield(None)\n return\n yield\n\n agen = agenfn()\n gen = agen.asend(None)\n gen.send(None)\n with self.assertRaisesRegex(RuntimeError, \"coroutine ignored GeneratorExit\"):\n gen.close()\n\n def test_async_gen_athrow_close_runtime_error(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n try:\n yield\n except MyExc:\n try:\n await _async_yield(None)\n except GeneratorExit:\n await _async_yield(None)\n\n agen = agenfn()\n with self.assertRaises(StopIteration):\n agen.asend(None).send(None)\n gen = agen.athrow(MyExc)\n gen.send(None)\n with self.assertRaisesRegex(RuntimeError, \"coroutine ignored GeneratorExit\"):\n gen.close()\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n asyncio.events._set_event_loop_policy(None)\n\n def check_async_iterator_anext(self, ait_class):\n with self.subTest(anext=\"pure-Python\"):\n self._check_async_iterator_anext(ait_class, py_anext)\n with self.subTest(anext=\"builtin\"):\n self._check_async_iterator_anext(ait_class, anext)\n\n def _check_async_iterator_anext(self, ait_class, anext):\n g = ait_class()\n async def consume():\n results = []\n results.append(await anext(g))\n results.append(await anext(g))\n results.append(await anext(g, 'buckle my shoe'))\n return results\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2, 'buckle my shoe'])\n with self.assertRaises(StopAsyncIteration):\n self.loop.run_until_complete(consume())\n\n async def test_2():\n g1 = ait_class()\n self.assertEqual(await anext(g1), 1)\n self.assertEqual(await anext(g1), 2)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n\n g2 = ait_class()\n self.assertEqual(await anext(g2, \"default\"), 1)\n self.assertEqual(await anext(g2, \"default\"), 2)\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n\n return \"completed\"\n\n result = self.loop.run_until_complete(test_2())\n self.assertEqual(result, \"completed\")\n\n def test_send():\n p = ait_class()\n obj = anext(p, \"completed\")\n with self.assertRaises(StopIteration):\n with contextlib.closing(obj.__await__()) as g:\n g.send(None)\n\n test_send()\n\n async def test_throw():\n p = ait_class()\n obj = anext(p, \"completed\")\n self.assertRaises(SyntaxError, obj.throw, SyntaxError)\n return \"completed\"\n\n result = self.loop.run_until_complete(test_throw())\n self.assertEqual(result, \"completed\")\n\n def test_async_generator_anext(self):\n async def agen():\n yield 1\n yield 2\n self.check_async_iterator_anext(agen)\n\n def test_python_async_iterator_anext(self):\n class MyAsyncIter:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n async def __anext__(self):\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIter)\n\n def test_python_async_iterator_types_coroutine_anext(self):\n import types\n class MyAsyncIterWithTypesCoro:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n @types.coroutine\n def __anext__(self):\n if False:\n yield \"this is a generator-based coroutine\"\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIterWithTypesCoro)\n\n def test_async_gen_aiter(self):\n async def gen():\n yield 1\n yield 2\n g = gen()\n async def consume():\n return [i async for i in aiter(g)]\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_aiter_class(self):\n results = []\n class Gen:\n async def __aiter__(self):\n yield 1\n yield 2\n g = Gen()\n async def consume():\n ait = aiter(g)\n while True:\n try:\n results.append(await anext(ait))\n except StopAsyncIteration:\n break\n self.loop.run_until_complete(consume())\n self.assertEqual(results, [1, 2])\n\n def test_aiter_idempotent(self):\n async def gen():\n yield 1\n applied_once = aiter(gen())\n applied_twice = aiter(applied_once)\n self.assertIs(applied_once, applied_twice)\n\n def test_anext_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await anext()\n async def call_with_too_many_args():\n await anext(gen(), 1, 3)\n async def call_with_wrong_type_args():\n await anext(1, gen())\n async def call_with_kwarg():\n await anext(aiterator=gen())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_kwarg())\n\n def test_anext_bad_await(self):\n async def bad_awaitable():\n class BadAwaitable:\n def __await__(self):\n return 42\n class MyAsyncIter:\n def __aiter__(self):\n return self\n def __anext__(self):\n return BadAwaitable()\n regex = r\"__await__.*iterator\"\n awaitable = anext(MyAsyncIter(), \"default\")\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n awaitable = anext(MyAsyncIter())\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(bad_awaitable())\n self.assertEqual(result, \"completed\")\n\n async def check_anext_returning_iterator(self, aiter_class):\n awaitable = anext(aiter_class(), \"default\")\n with self.assertRaises(TypeError):\n await awaitable\n awaitable = anext(aiter_class())\n with self.assertRaises(TypeError):\n await awaitable\n return \"completed\"\n\n def test_anext_return_iterator(self):\n class WithIterAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return iter(\"abc\")\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithIterAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_return_generator(self):\n class WithGenAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n yield\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithGenAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_await_raises(self):\n class RaisingAwaitable:\n def __await__(self):\n raise ZeroDivisionError()\n yield\n class WithRaisingAwaitableAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return RaisingAwaitable()\n async def do_test():\n awaitable = anext(WithRaisingAwaitableAnext())\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n awaitable = anext(WithRaisingAwaitableAnext(), \"default\")\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(do_test())\n self.assertEqual(result, \"completed\")\n\n def test_anext_iter(self):\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyError(Exception):\n pass\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n def test1(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError()), 2)\n try:\n g.send(None)\n except StopIteration as e:\n err = e\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(err.value, \"default\")\n\n def test2(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError()), 2)\n with self.assertRaises(MyError):\n g.throw(MyError())\n\n def test3(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n g.close()\n with self.assertRaisesRegex(RuntimeError, 'cannot reuse'):\n self.assertEqual(g.send(None), 1)\n\n def test4(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n self.assertEqual(g.throw(MyError()), 20)\n with self.assertRaisesRegex(MyError, 'val'):\n g.throw(MyError('val'))\n\n def test5(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n return\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n with self.assertRaisesRegex(StopIteration, 'default'):\n g.throw(MyError())\n\n def test6(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n await _async_yield(1)\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n with self.assertRaises(MyError):\n g.throw(MyError())\n\n def run_test(test):\n with self.subTest('pure-Python anext()'):\n test(py_anext)\n with self.subTest('builtin anext()'):\n test(anext)\n\n run_test(test1)\n run_test(test2)\n run_test(test3)\n run_test(test4)\n run_test(test5)\n run_test(test6)\n\n def test_aiter_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await aiter()\n async def call_with_too_many_args():\n await aiter(gen(), 1)\n async def call_with_wrong_type_arg():\n await aiter(1)\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_arg())\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n await asyncio.sleep(0.01)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_tuple_no_exceptions(self):\n # StopAsyncIteration exceptions should be cleared.\n # See: https://github.com/python/cpython/issues/128078.\n\n async def foo():\n if False:\n yield (1, 2)\n\n async def run():\n it = foo().__aiter__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n res = await anext(it, ('a', 'b'))\n self.assertTupleEqual(res, ('a', 'b'))\n\n self.loop.run_until_complete(run())\n\n def test_sync_anext_raises_exception(self):\n # See: https://github.com/python/cpython/issues/131670\n msg = 'custom'\n for exc_type in [\n StopAsyncIteration,\n StopIteration,\n ValueError,\n Exception,\n ]:\n exc = exc_type(msg)\n with self.subTest(exc=exc):\n class A:\n def __anext__(self):\n raise exc\n\n with self.assertRaisesRegex(exc_type, msg):\n anext(A())\n with self.assertRaisesRegex(exc_type, msg):\n anext(A(), 1)\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n gc_collect() # For PyPy or other GCs.\n\n # Starts running the aclose task\n await asyncio.sleep(0)\n # For asyncio.sleep(0) in finally block\n await asyncio.sleep(0)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_aclose_12(self):\n DONE = 0\n\n async def target():\n await asyncio.sleep(0.01)\n 1 / 0\n\n async def foo():\n nonlocal DONE\n task = asyncio.create_task(target())\n try:\n yield 1\n finally:\n try:\n await task\n except ZeroDivisionError:\n DONE = 1\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout)\n yield 1\n finally:\n await asyncio.sleep(0)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1))\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t1)\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t2)\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(finalized, 2)\n\n def test_async_gen_asyncio_shutdown_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n self.assertEqual(messages, [])\n\n def test_async_gen_asyncio_shutdown_exception_01(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n message, = messages\n self.assertEqual(message['asyncgen'], it)\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('an error occurred during closing of asynchronous generator',\n message['message'])\n\n def test_async_gen_asyncio_shutdown_exception_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n gc_collect()\n\n asyncio.run(main())\n\n message, = messages\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('unhandled exception during asyncio.run() shutdown',\n message['message'])\n del message, messages\n gc_collect()\n\n def test_async_gen_expression_01(self):\n async def arange(n):\n for i in range(n):\n await asyncio.sleep(0.01)\n yield i\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 async for i in arange(n))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(10)])\n\n def test_async_gen_expression_02(self):\n async def wrap(n):\n await asyncio.sleep(0.01)\n return n\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 for i in range(n) if await wrap(i))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(1, 10)])\n\n def test_async_gen_expression_incorrect(self):\n async def ag():\n yield 42\n\n async def run(arg):\n (x async for x in arg)\n\n err_msg_async = \"'async for' requires an object with \" \\\n \"__aiter__ method, got .*\"\n\n self.loop.run_until_complete(run(ag()))\n with self.assertRaisesRegex(TypeError, err_msg_async):\n self.loop.run_until_complete(run(None))\n\n def test_asyncgen_nonstarted_hooks_are_cancellable(self):\n # See https://bugs.python.org/issue38013\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n\n asyncio.run(main())\n\n self.assertEqual([], messages)\n gc_collect()\n\n def test_async_gen_await_same_anext_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.__anext__()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"\n ):\n await nxt\n\n await it.aclose() # prevent unfinished iterator warning\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_await_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.aclose()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n await nxt\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_throw_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n nxt = it.aclose()\n with self.assertRaises(StopIteration):\n nxt.throw(GeneratorExit)\n\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n nxt.throw(GeneratorExit)\n\n def test_async_gen_throw_custom_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n\n class MyException(Exception):\n pass\n\n nxt = it.aclose()\n with self.assertRaises(MyException):\n nxt.throw(MyException)\n\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n nxt.throw(MyException)\n\n def test_async_gen_throw_custom_same_athrow_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n\n class MyException(Exception):\n pass\n\n nxt = it.athrow(MyException)\n with self.assertRaises(MyException):\n nxt.throw(MyException)\n\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n nxt.throw(MyException)\n\n def test_async_gen_aclose_twice_with_different_coros(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n await it.aclose()\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_after_exhaustion(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n async for _ in it:\n pass\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_compatible_with_get_stack(self):\n async def async_generator():\n yield object()\n\n async def run():\n ag = async_generator()\n asyncio.create_task(ag.aclose())\n tasks = asyncio.all_tasks()\n for task in tasks:\n # No AttributeError raised\n task.get_stack()\n\n self.loop.run_until_complete(run())\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"breakpoint","pep":"553","introduced_in":"3.7","form":"modern","file":"breakpoint/modern_01.py","code":"import ast\nimport builtins\nimport collections\nimport contextlib\nimport decimal\nimport fractions\nimport gc\nimport io\nimport locale\nimport math\nimport os\nimport pickle\nimport platform\nimport random\nimport re\nimport sys\nimport traceback\nimport types\nimport typing\nimport unittest\nimport warnings\nfrom contextlib import ExitStack\nfrom functools import partial\nfrom inspect import CO_COROUTINE\nfrom itertools import product\nfrom textwrap import dedent\nfrom types import AsyncGeneratorType, FunctionType, CellType\nfrom operator import neg\nfrom test import support\nfrom test.support import cpython_only, swap_attr\nfrom test.support import async_yield, run_yielding_async_fn\nfrom test.support.import_helper import import_module\nfrom test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink)\nfrom test.support.script_helper import assert_python_ok\nfrom test.support.testcase import ComplexesAreIdenticalMixin\nfrom test.support.warnings_helper import check_warnings\nfrom test.support import requires_IEEE_754\nfrom unittest.mock import MagicMock, patch\n\n\nclass TestBreakpoint(unittest.TestCase):\n def setUp(self):\n # These tests require a clean slate environment. For example, if the\n # test suite is run with $PYTHONBREAKPOINT set to something else, it\n # will mess up these tests. Similarly for sys.breakpointhook.\n # Cleaning the slate here means you can't use breakpoint() to debug\n # these tests, but I think that's okay. Just use pdb.set_trace() if\n # you must.\n self.resources = ExitStack()\n self.addCleanup(self.resources.close)\n self.env = self.resources.enter_context(EnvironmentVarGuard())\n del self.env['PYTHONBREAKPOINT']\n self.resources.enter_context(\n swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))\n\n def test_breakpoint(self):\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once()\n\n def test_breakpoint_with_breakpointhook_set(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_breakpointhook_reset(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n # Reset the hook and it will not be called again.\n sys.breakpointhook = sys.__breakpointhook__\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_args_and_keywords(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint(1, 2, 3, four=4, five=5)\n my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)\n\n def test_breakpoint_with_passthru_error(self):\n def my_breakpointhook():\n pass\n sys.breakpointhook = my_breakpointhook\n self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_builtin(self):\n self.env['PYTHONBREAKPOINT'] = 'int'\n with patch('builtins.int') as mock:\n breakpoint('7')\n mock.assert_called_once_with('7')\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_other(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_noop_0(self):\n self.env['PYTHONBREAKPOINT'] = '0'\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_not_called()\n\n def test_envar_good_path_empty_string(self):\n # PYTHONBREAKPOINT='' is the same as it not being set.\n self.env['PYTHONBREAKPOINT'] = ''\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_unimportable(self):\n for envar in (\n '.', '..', '.foo', 'foo.', '.int', 'int.',\n '.foo.bar', '..foo.bar', '/./',\n 'nosuchbuiltin',\n 'nosuchmodule.nosuchcallable',\n ):\n with self.subTest(envar=envar):\n self.env['PYTHONBREAKPOINT'] = envar\n mock = self.resources.enter_context(patch('pdb.set_trace'))\n w = self.resources.enter_context(check_warnings(quiet=True))\n breakpoint()\n self.assertEqual(\n str(w.message),\n f'Ignoring unimportable $PYTHONBREAKPOINT: \"{envar}\"')\n self.assertEqual(w.category, RuntimeWarning)\n mock.assert_not_called()\n\n def test_envar_ignored_when_hook_is_set(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n sys.breakpointhook = int\n breakpoint()\n mock.assert_not_called()\n\n def test_runtime_error_when_hook_is_lost(self):\n del sys.breakpointhook\n with self.assertRaises(RuntimeError):\n breakpoint()\n","source":"cpython_tests","origin":"Lib/test/test_builtin.py::TestBreakpoint","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(ZeroDivisionError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n notes = cm.exception.__notes__\n self.assertRegex(str(notes), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(notes), r'\\battr\\b')\n self.assertRegex(str(notes), r'\\bDescriptor\\b')\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(TypeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n notes = cm.exception.__notes__\n self.assertRegex(str(notes), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(notes), r'\\battr\\b')\n self.assertRegex(str(notes), r'\\bDescriptor\\b')\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass2(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass3(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass3.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass2(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass2.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_03.py","code":"import sys\nimport collections.abc\nimport concurrent.futures\nimport contextvars\nimport functools\nimport gc\nimport random\nimport time\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import threading_helper\n\n\nclass ContextTest(unittest.TestCase):\n def test_context_var_new_1(self):\n with self.assertRaisesRegex(TypeError, 'takes exactly 1'):\n contextvars.ContextVar()\n\n with self.assertRaisesRegex(TypeError, 'must be a str'):\n contextvars.ContextVar(1)\n\n c = contextvars.ContextVar('aaa')\n self.assertEqual(c.name, 'aaa')\n\n with self.assertRaises(AttributeError):\n c.name = 'bbb'\n\n self.assertNotEqual(hash(c), hash('aaa'))\n\n @isolated_context\n def test_context_var_repr_1(self):\n c = contextvars.ContextVar('a')\n self.assertIn('a', repr(c))\n\n c = contextvars.ContextVar('a', default=123)\n self.assertIn('123', repr(c))\n\n lst = []\n c = contextvars.ContextVar('a', default=lst)\n lst.append(c)\n self.assertIn('...', repr(c))\n self.assertIn('...', repr(lst))\n\n t = c.set(1)\n self.assertIn(repr(c), repr(t))\n self.assertNotIn(' used ', repr(t))\n c.reset(t)\n self.assertIn(' used ', repr(t))\n\n @isolated_context\n def test_token_repr_1(self):\n c = contextvars.ContextVar('a')\n tok = c.set(1)\n self.assertRegex(repr(tok),\n r\"^ at 0x[0-9a-fA-F]+>$\")\n\n def test_context_subclassing_1(self):\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContextVar(contextvars.ContextVar):\n # Potentially we might want ContextVars to be subclassable.\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContext(contextvars.Context):\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyToken(contextvars.Token):\n pass\n\n def test_context_new_1(self):\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1, a=1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(a=1)\n contextvars.Context(**{})\n\n def test_context_new_unhashable_str_subclass(self):\n # gh-132002: it used to crash on unhashable str subtypes.\n class weird_str(str):\n def __eq__(self, other):\n pass\n\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n contextvars.ContextVar(weird_str())\n\n def test_context_typerrors_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx[1]\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n 1 in ctx\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx.get(1)\n\n def test_context_get_context_1(self):\n ctx = contextvars.copy_context()\n self.assertIsInstance(ctx, contextvars.Context)\n\n def test_context_run_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required'):\n ctx.run()\n\n def test_context_run_2(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n kwargs['spam'] = 'foo'\n args += ('bar',)\n return args, kwargs\n\n for f in (func, functools.partial(func)):\n # partial doesn't support FASTCALL\n\n self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))\n self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, a=2),\n (('bar',), {'a': 2, 'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, 11, a=2),\n ((11, 'bar'), {'a': 2, 'spam': 'foo'}))\n\n a = {}\n self.assertEqual(\n ctx.run(f, 11, **a),\n ((11, 'bar'), {'spam': 'foo'}))\n self.assertEqual(a, {})\n\n def test_context_run_3(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2, a=123)\n\n @isolated_context\n def test_context_run_4(self):\n ctx1 = contextvars.Context()\n ctx2 = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func2():\n self.assertIsNone(var.get(None))\n\n def func1():\n self.assertIsNone(var.get(None))\n var.set('spam')\n ctx2.run(func2)\n self.assertEqual(var.get(None), 'spam')\n\n cur = contextvars.copy_context()\n self.assertEqual(len(cur), 1)\n self.assertEqual(cur[var], 'spam')\n return cur\n\n returned_ctx = ctx1.run(func1)\n self.assertEqual(ctx1, returned_ctx)\n self.assertEqual(returned_ctx[var], 'spam')\n self.assertIn(var, returned_ctx)\n\n def test_context_run_5(self):\n ctx = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func():\n self.assertIsNone(var.get(None))\n var.set('spam')\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n\n self.assertIsNone(var.get(None))\n\n def test_context_run_6(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('a', default=0)\n\n def fun():\n self.assertEqual(c.get(), 0)\n self.assertIsNone(ctx.get(c))\n\n c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(ctx.get(c), 42)\n\n ctx.run(fun)\n\n def test_context_run_7(self):\n ctx = contextvars.Context()\n\n def fun():\n with self.assertRaisesRegex(RuntimeError, 'is already entered'):\n ctx.run(fun)\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_1(self):\n c = contextvars.ContextVar('c')\n with self.assertRaises(LookupError):\n c.get()\n\n self.assertIsNone(c.get(None))\n\n t0 = c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n self.assertIs(t0.old_value, t0.MISSING)\n self.assertIs(t0.old_value, contextvars.Token.MISSING)\n self.assertIs(t0.var, c)\n\n t = c.set('spam')\n self.assertEqual(c.get(), 'spam')\n self.assertEqual(c.get(None), 'spam')\n self.assertEqual(t.old_value, 42)\n c.reset(t)\n\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n\n c.set('spam2')\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t)\n self.assertEqual(c.get(), 'spam2')\n\n ctx1 = contextvars.copy_context()\n self.assertIn(c, ctx1)\n\n c.reset(t0)\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t0)\n self.assertIsNone(c.get(None))\n\n self.assertIn(c, ctx1)\n self.assertEqual(ctx1[c], 'spam2')\n self.assertEqual(ctx1.get(c, 'aa'), 'spam2')\n self.assertEqual(len(ctx1), 1)\n self.assertEqual(list(ctx1.items()), [(c, 'spam2')])\n self.assertEqual(list(ctx1.values()), ['spam2'])\n self.assertEqual(list(ctx1.keys()), [c])\n self.assertEqual(list(ctx1), [c])\n\n ctx2 = contextvars.copy_context()\n self.assertNotIn(c, ctx2)\n with self.assertRaises(KeyError):\n ctx2[c]\n self.assertEqual(ctx2.get(c, 'aa'), 'aa')\n self.assertEqual(len(ctx2), 0)\n self.assertEqual(list(ctx2), [])\n\n @isolated_context\n def test_context_getset_2(self):\n v1 = contextvars.ContextVar('v1')\n v2 = contextvars.ContextVar('v2')\n\n t1 = v1.set(42)\n with self.assertRaisesRegex(ValueError, 'by a different'):\n v2.reset(t1)\n\n @isolated_context\n def test_context_getset_3(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n def fun():\n self.assertEqual(c.get(), 42)\n with self.assertRaises(KeyError):\n ctx[c]\n self.assertIsNone(ctx.get(c))\n self.assertEqual(ctx.get(c, 'spam'), 'spam')\n self.assertNotIn(c, ctx)\n self.assertEqual(list(ctx.keys()), [])\n\n t = c.set(1)\n self.assertEqual(list(ctx.keys()), [c])\n self.assertEqual(ctx[c], 1)\n\n c.reset(t)\n self.assertEqual(list(ctx.keys()), [])\n with self.assertRaises(KeyError):\n ctx[c]\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_4(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n tok = ctx.run(c.set, 1)\n\n with self.assertRaisesRegex(ValueError, 'different Context'):\n c.reset(tok)\n\n @isolated_context\n def test_context_getset_5(self):\n c = contextvars.ContextVar('c', default=42)\n c.set([])\n\n def fun():\n c.set([])\n c.get().append(42)\n self.assertEqual(c.get(), [42])\n\n contextvars.copy_context().run(fun)\n self.assertEqual(c.get(), [])\n\n def test_context_copy_1(self):\n ctx1 = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def ctx1_fun():\n c.set(10)\n\n ctx2 = ctx1.copy()\n self.assertEqual(ctx2[c], 10)\n\n c.set(20)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 10)\n\n ctx2.run(ctx2_fun)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 30)\n\n def ctx2_fun():\n self.assertEqual(c.get(), 10)\n c.set(30)\n self.assertEqual(c.get(), 30)\n\n ctx1.run(ctx1_fun)\n\n def test_context_isinstance(self):\n ctx = contextvars.Context()\n self.assertIsInstance(ctx, collections.abc.Mapping)\n self.assertTrue(issubclass(contextvars.Context, collections.abc.Mapping))\n\n mapping_methods = (\n '__contains__', '__eq__', '__getitem__', '__iter__', '__len__',\n '__ne__', 'get', 'items', 'keys', 'values',\n )\n for name in mapping_methods:\n with self.subTest(name=name):\n self.assertTrue(callable(getattr(ctx, name)))\n\n @isolated_context\n @threading_helper.requires_working_threading()\n def test_context_threads_1(self):\n cvar = contextvars.ContextVar('cvar')\n\n def sub(num):\n for i in range(10):\n cvar.set(num + i)\n time.sleep(random.uniform(0.001, 0.05))\n self.assertEqual(cvar.get(), num + i)\n return num\n\n tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)\n try:\n results = list(tp.map(sub, range(10)))\n finally:\n tp.shutdown()\n self.assertEqual(results, list(range(10)))\n\n @isolated_context\n @threading_helper.requires_working_threading()\n def test_context_thread_inherit(self):\n import threading\n\n cvar = contextvars.ContextVar('cvar')\n\n def run_context_none():\n if sys.flags.thread_inherit_context:\n expected = 1\n else:\n expected = None\n self.assertEqual(cvar.get(None), expected)\n\n # By default, context is inherited based on the\n # sys.flags.thread_inherit_context option.\n cvar.set(1)\n thread = threading.Thread(target=run_context_none)\n thread.start()\n thread.join()\n\n # Passing 'None' explicitly should have same behaviour as not\n # passing parameter.\n thread = threading.Thread(target=run_context_none, context=None)\n thread.start()\n thread.join()\n\n # An explicit Context value can also be passed\n custom_ctx = contextvars.Context()\n custom_var = None\n\n def setup_context():\n nonlocal custom_var\n custom_var = contextvars.ContextVar('custom')\n custom_var.set(2)\n\n custom_ctx.run(setup_context)\n\n def run_custom():\n self.assertEqual(custom_var.get(), 2)\n\n thread = threading.Thread(target=run_custom, context=custom_ctx)\n thread.start()\n thread.join()\n\n # You can also pass a new Context() object to start with an empty context\n def run_empty():\n with self.assertRaises(LookupError):\n cvar.get()\n\n thread = threading.Thread(target=run_empty, context=contextvars.Context())\n thread.start()\n thread.join()\n\n def test_token_contextmanager_with_default(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def fun():\n with c.set(36):\n self.assertEqual(c.get(), 36)\n\n self.assertEqual(c.get(), 42)\n\n ctx.run(fun)\n\n def test_token_contextmanager_without_default(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('c')\n\n def fun():\n with c.set(36):\n self.assertEqual(c.get(), 36)\n\n with self.assertRaisesRegex(LookupError, \")\")\n\n def test_docstring_deque_field(self):\n @dataclass\n class C:\n x: deque\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque)\")\n\n def test_docstring_deque_field_with_default_factory(self):\n @dataclass\n class C:\n x: deque = field(default_factory=deque)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque=)\")\n\n def test_docstring_undefined_name(self):\n @dataclass\n class C:\n x: undef\n\n self.assertDocStrEqual(C.__doc__, \"C(x:undef)\")\n\n def test_docstring_with_unsolvable_forward_ref_in_init(self):\n # See: https://github.com/python/cpython/issues/128184\n ns = {}\n exec(\n textwrap.dedent(\n \"\"\"\n from dataclasses import dataclass\n\n @dataclass\n class C:\n def __init__(self, x: X, num: int) -> None: ...\n \"\"\",\n ),\n ns,\n )\n\n self.assertDocStrEqual(ns['C'].__doc__, \"C(x:X,num:int)\")\n\n def test_docstring_with_no_signature(self):\n # See https://github.com/python/cpython/issues/103449\n class Meta(type):\n __call__ = dict\n class Base(metaclass=Meta):\n pass\n\n @dataclass\n class C(Base):\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestDocString","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_19.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestInit(unittest.TestCase):\n def test_base_has_init(self):\n class B:\n def __init__(self):\n self.z = 100\n\n # Make sure that declaring this class doesn't raise an error.\n # The issue is that we can't override __init__ in our class,\n # but it should be okay to add __init__ to us if our base has\n # an __init__.\n @dataclass\n class C(B):\n x: int = 0\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertNotIn('z', vars(c))\n\n # Make sure that if we don't add an init, the base __init__\n # gets called.\n @dataclass(init=False)\n class C(B):\n x: int = 10\n c = C()\n self.assertEqual(c.x, 10)\n self.assertEqual(c.z, 100)\n\n def test_no_init(self):\n @dataclass(init=False)\n class C:\n i: int = 0\n self.assertEqual(C().i, 0)\n\n @dataclass(init=False)\n class C:\n i: int = 2\n def __init__(self):\n self.i = 3\n self.assertEqual(C().i, 3)\n\n def test_overwriting_init(self):\n # If the class has __init__, use it no matter the value of\n # init=.\n\n @dataclass\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(3).x, 6)\n\n @dataclass(init=True)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(4).x, 8)\n\n @dataclass(init=False)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(5).x, 10)\n\n def test_inherit_from_protocol(self):\n # Dataclasses inheriting from protocol should preserve their own `__init__`.\n # See bpo-45081.\n\n class P(Protocol):\n a: int\n\n @dataclass\n class C(P):\n a: int\n\n self.assertEqual(C(5).a, 5)\n\n @dataclass\n class D(P):\n def __init__(self, a):\n self.a = a * 2\n\n self.assertEqual(D(5).a, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestInit","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_20.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestRepr(unittest.TestCase):\n def test_repr(self):\n @dataclass\n class B:\n x: int\n\n @dataclass\n class C(B):\n y: int = 10\n\n o = C(4)\n self.assertEqual(repr(o), 'TestRepr.test_repr..C(x=4, y=10)')\n\n @dataclass\n class D(C):\n x: int = 20\n self.assertEqual(repr(D()), 'TestRepr.test_repr..D(x=20, y=10)')\n\n @dataclass\n class C:\n @dataclass\n class D:\n i: int\n @dataclass\n class E:\n pass\n self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr..C.D(i=0)')\n self.assertEqual(repr(C.E()), 'TestRepr.test_repr..C.E()')\n\n def test_no_repr(self):\n # Test a class with no __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n self.assertIn(f'{__name__}.TestRepr.test_no_repr..C object at',\n repr(C(3)))\n\n # Test a class with a __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'C-class'\n self.assertEqual(repr(C(3)), 'C-class')\n\n def test_overwriting_repr(self):\n # If the class has __repr__, use it no matter the value of\n # repr=.\n\n @dataclass\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=True)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestRepr","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_21.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestEq(unittest.TestCase):\n def test_recursive_eq(self):\n # Test a class with recursive child\n @dataclass\n class C:\n recursive: object = ...\n c = C()\n c.recursive = c\n self.assertEqual(c, c)\n\n def test_no_eq(self):\n # Test a class with no __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n self.assertNotEqual(C(0), C(0))\n c = C(3)\n self.assertEqual(c, c)\n\n # Test a class with an __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 10\n self.assertEqual(C(3), 10)\n\n def test_overwriting_eq(self):\n # If the class has __eq__, use it no matter the value of\n # eq=.\n\n @dataclass\n class C:\n x: int\n def __eq__(self, other):\n return other == 3\n self.assertEqual(C(1), 3)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=True)\n class C:\n x: int\n def __eq__(self, other):\n return other == 4\n self.assertEqual(C(1), 4)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 5\n self.assertEqual(C(1), 5)\n self.assertNotEqual(C(1), 1)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestEq","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_22.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestOrdering(unittest.TestCase):\n def test_functools_total_ordering(self):\n # Test that functools.total_ordering works with this class.\n @total_ordering\n @dataclass\n class C:\n x: int\n def __lt__(self, other):\n # Perform the test \"backward\", just to make\n # sure this is being called.\n return self.x >= other\n\n self.assertLess(C(0), -1)\n self.assertLessEqual(C(0), -1)\n self.assertGreater(C(0), 1)\n self.assertGreaterEqual(C(0), 1)\n\n def test_no_order(self):\n # Test that no ordering functions are added by default.\n @dataclass(order=False)\n class C:\n x: int\n # Make sure no order methods are added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__lt__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n # Test that __lt__ is still called\n @dataclass(order=False)\n class C:\n x: int\n def __lt__(self, other):\n return False\n # Make sure other methods aren't added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n def test_overwriting_order(self):\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __lt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __lt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __le__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __le__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __gt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __gt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __ge__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __ge__(self):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestOrdering","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_23.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestHash(unittest.TestCase):\n def test_unsafe_hash(self):\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n y: str\n self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))\n\n def test_hash_rules(self):\n def non_bool(value):\n # Map to something else that's True, but not a bool.\n if value is None:\n return None\n if value:\n return (3,)\n return 0\n\n def test(case, unsafe_hash, eq, frozen, with_hash, result):\n with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,\n frozen=frozen):\n if result != 'exception':\n if with_hash:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n else:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n pass\n\n # See if the result matches what's expected.\n if result == 'fn':\n # __hash__ contains the function we generated.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNotNone(C.__dict__['__hash__'])\n\n elif result == '':\n # __hash__ is not present in our class.\n if not with_hash:\n self.assertNotIn('__hash__', C.__dict__)\n\n elif result == 'none':\n # __hash__ is set to None.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNone(C.__dict__['__hash__'])\n\n elif result == 'exception':\n # Creating the class should cause an exception.\n # This only happens with with_hash==True.\n assert(with_hash)\n with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n\n else:\n assert False, f'unknown result {result!r}'\n\n # There are 8 cases of:\n # unsafe_hash=True/False\n # eq=True/False\n # frozen=True/False\n # And for each of these, a different result if\n # __hash__ is defined or not.\n for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([\n (False, False, False, '', ''),\n (False, False, True, '', ''),\n (False, True, False, 'none', ''),\n (False, True, True, 'fn', ''),\n (True, False, False, 'fn', 'exception'),\n (True, False, True, 'fn', 'exception'),\n (True, True, False, 'fn', 'exception'),\n (True, True, True, 'fn', 'exception'),\n ], 1):\n test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)\n test(case, unsafe_hash, eq, frozen, True, res_defined_hash)\n\n # Test non-bool truth values, too. This is just to\n # make sure the data-driven table in the decorator\n # handles non-bool values.\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)\n\n\n def test_eq_only(self):\n # If a class defines __eq__, __hash__ is automatically added\n # and set to None. This is normal Python behavior, not\n # related to dataclasses. Make sure we don't interfere with\n # that (see bpo=32546).\n\n @dataclass\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1))\n self.assertNotEqual(C(1), C(4))\n\n # And make sure things work in this case if we specify\n # unsafe_hash=True.\n @dataclass(unsafe_hash=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1.0))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n # And check that the classes __eq__ is being used, despite\n # specifying eq=True.\n @dataclass(unsafe_hash=True, eq=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == 3 and self.i == other.i\n self.assertEqual(C(3), C(3))\n self.assertNotEqual(C(1), C(1))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n def test_0_field_hash(self):\n @dataclass(frozen=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n @dataclass(unsafe_hash=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n def test_1_field_hash(self):\n @dataclass(frozen=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n def test_hash_no_args(self):\n # Test dataclasses with no hash= argument. This exists to\n # make sure that if the @dataclass parameter name is changed\n # or the non-default hashing behavior changes, the default\n # hashability keeps working the same way.\n\n class Base:\n def __hash__(self):\n return 301\n\n # If frozen or eq is None, then use the default value (do not\n # specify any value in the decorator).\n for frozen, eq, base, expected in [\n (None, None, object, 'unhashable'),\n (None, None, Base, 'unhashable'),\n (None, False, object, 'object'),\n (None, False, Base, 'base'),\n (None, True, object, 'unhashable'),\n (None, True, Base, 'unhashable'),\n (False, None, object, 'unhashable'),\n (False, None, Base, 'unhashable'),\n (False, False, object, 'object'),\n (False, False, Base, 'base'),\n (False, True, object, 'unhashable'),\n (False, True, Base, 'unhashable'),\n (True, None, object, 'tuple'),\n (True, None, Base, 'tuple'),\n (True, False, object, 'object'),\n (True, False, Base, 'base'),\n (True, True, object, 'tuple'),\n (True, True, Base, 'tuple'),\n ]:\n\n with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):\n # First, create the class.\n if frozen is None and eq is None:\n @dataclass\n class C(base):\n i: int\n elif frozen is None:\n @dataclass(eq=eq)\n class C(base):\n i: int\n elif eq is None:\n @dataclass(frozen=frozen)\n class C(base):\n i: int\n else:\n @dataclass(frozen=frozen, eq=eq)\n class C(base):\n i: int\n\n # Now, make sure it hashes as expected.\n if expected == 'unhashable':\n c = C(10)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(c)\n\n elif expected == 'base':\n self.assertEqual(hash(C(10)), 301)\n\n elif expected == 'object':\n # I'm not sure what test to use here. object's\n # hash isn't based on id(), so calling hash()\n # won't tell us much. So, just check the\n # function used is object's.\n self.assertIs(C.__hash__, object.__hash__)\n\n elif expected == 'tuple':\n self.assertEqual(hash(C(42)), hash((42,)))\n\n else:\n assert False, f'unknown value for expected={expected!r}'\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestHash","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_24.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestFrozen(unittest.TestCase):\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n c = C(10)\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertEqual(c.i, 10)\n\n def test_frozen_empty(self):\n @dataclass(frozen=True)\n class C:\n pass\n\n c = C()\n self.assertNotHasAttr(c, 'i')\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertNotHasAttr(c, 'i')\n with self.assertRaises(FrozenInstanceError):\n del c.i\n\n def test_inherit(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n @dataclass(frozen=True)\n class D(C):\n j: int\n\n d = D(0, 10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n with self.assertRaises(FrozenInstanceError):\n d.j = 6\n self.assertEqual(d.i, 0)\n self.assertEqual(d.j, 10)\n\n def test_inherit_nonfrozen_from_empty_frozen(self):\n @dataclass(frozen=True)\n class C:\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(C):\n j: int\n\n def test_inherit_frozen_mutliple_inheritance(self):\n @dataclass\n class NotFrozen:\n pass\n\n @dataclass(frozen=True)\n class Frozen:\n pass\n\n class NotDataclass:\n pass\n\n for bases in (\n (NotFrozen, Frozen),\n (Frozen, NotFrozen),\n (Frozen, NotDataclass),\n (NotDataclass, Frozen),\n ):\n with self.subTest(bases=bases):\n with self.assertRaisesRegex(\n TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one',\n ):\n @dataclass\n class NotFrozenChild(*bases):\n pass\n\n for bases in (\n (NotFrozen, Frozen),\n (Frozen, NotFrozen),\n (NotFrozen, NotDataclass),\n (NotDataclass, NotFrozen),\n ):\n with self.subTest(bases=bases):\n with self.assertRaisesRegex(\n TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one',\n ):\n @dataclass(frozen=True)\n class FrozenChild(*bases):\n pass\n\n def test_inherit_frozen_mutliple_inheritance_regular_mixins(self):\n @dataclass(frozen=True)\n class Frozen:\n pass\n\n class NotDataclass:\n pass\n\n class C1(Frozen, NotDataclass):\n pass\n self.assertEqual(C1.__mro__, (C1, Frozen, NotDataclass, object))\n\n class C2(NotDataclass, Frozen):\n pass\n self.assertEqual(C2.__mro__, (C2, NotDataclass, Frozen, object))\n\n @dataclass(frozen=True)\n class C3(Frozen, NotDataclass):\n pass\n self.assertEqual(C3.__mro__, (C3, Frozen, NotDataclass, object))\n\n @dataclass(frozen=True)\n class C4(NotDataclass, Frozen):\n pass\n self.assertEqual(C4.__mro__, (C4, NotDataclass, Frozen, object))\n\n def test_multiple_frozen_dataclasses_inheritance(self):\n @dataclass(frozen=True)\n class FrozenA:\n pass\n\n @dataclass(frozen=True)\n class FrozenB:\n pass\n\n class C1(FrozenA, FrozenB):\n pass\n self.assertEqual(C1.__mro__, (C1, FrozenA, FrozenB, object))\n\n class C2(FrozenB, FrozenA):\n pass\n self.assertEqual(C2.__mro__, (C2, FrozenB, FrozenA, object))\n\n @dataclass(frozen=True)\n class C3(FrozenA, FrozenB):\n pass\n self.assertEqual(C3.__mro__, (C3, FrozenA, FrozenB, object))\n\n @dataclass(frozen=True)\n class C4(FrozenB, FrozenA):\n pass\n self.assertEqual(C4.__mro__, (C4, FrozenB, FrozenA, object))\n\n def test_inherit_nonfrozen_from_empty(self):\n @dataclass\n class C:\n pass\n\n @dataclass\n class D(C):\n j: int\n\n d = D(3)\n self.assertEqual(d.j, 3)\n self.assertIsInstance(d, C)\n\n # Test both ways: with an intermediate normal (non-dataclass)\n # class and without an intermediate class.\n def test_inherit_nonfrozen_from_frozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass(frozen=True)\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(I):\n pass\n\n def test_inherit_frozen_from_nonfrozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one'):\n @dataclass(frozen=True)\n class D(I):\n pass\n\n def test_inherit_from_normal_class(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n class C:\n pass\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n @dataclass(frozen=True)\n class D(I):\n i: int\n\n d = D(10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n\n def test_non_frozen_normal_derived(self):\n # See bpo-32953.\n\n @dataclass(frozen=True)\n class D:\n x: int\n y: int = 10\n\n class S(D):\n pass\n\n s = S(3)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n s.cached = True\n\n # But can't change the frozen attributes.\n with self.assertRaises(FrozenInstanceError):\n s.x = 5\n with self.assertRaises(FrozenInstanceError):\n s.y = 5\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.cached, True)\n\n with self.assertRaises(FrozenInstanceError):\n del s.x\n self.assertEqual(s.x, 3)\n with self.assertRaises(FrozenInstanceError):\n del s.y\n self.assertEqual(s.y, 10)\n del s.cached\n self.assertNotHasAttr(s, 'cached')\n with self.assertRaises(AttributeError) as cm:\n del s.cached\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n\n def test_non_frozen_normal_derived_from_empty_frozen(self):\n @dataclass(frozen=True)\n class D:\n pass\n\n class S(D):\n pass\n\n s = S()\n self.assertNotHasAttr(s, 'x')\n s.x = 5\n self.assertEqual(s.x, 5)\n\n del s.x\n self.assertNotHasAttr(s, 'x')\n with self.assertRaises(AttributeError) as cm:\n del s.x\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n\n def test_overwriting_frozen(self):\n # frozen uses __setattr__ and __delattr__.\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __setattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __setattr__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __delattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __delattr__(self):\n pass\n\n @dataclass(frozen=False)\n class C:\n x: int\n def __setattr__(self, name, value):\n self.__dict__['x'] = value * 2\n self.assertEqual(C(10).x, 20)\n\n def test_frozen_hash(self):\n @dataclass(frozen=True)\n class C:\n x: Any\n\n # If x is immutable, we can compute the hash. No exception is\n # raised.\n hash(C(3))\n\n # If x is mutable, computing the hash is an error.\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(C({}))\n\n def test_frozen_deepcopy_without_slots(self):\n # see: https://github.com/python/cpython/issues/89683\n @dataclass(frozen=True, slots=False)\n class C:\n s: str\n\n c = C('hello')\n self.assertEqual(deepcopy(c), c)\n\n def test_frozen_deepcopy_with_slots(self):\n # see: https://github.com/python/cpython/issues/89683\n with self.subTest('generated __slots__'):\n @dataclass(frozen=True, slots=True)\n class C:\n s: str\n\n c = C('hello')\n self.assertEqual(deepcopy(c), c)\n\n with self.subTest('user-defined __slots__ and no __{get,set}state__'):\n @dataclass(frozen=True, slots=False)\n class C:\n __slots__ = ('s',)\n s: str\n\n # with user-defined slots, __getstate__ and __setstate__ are not\n # automatically added, hence the error\n err = r\"^cannot\\ assign\\ to\\ field\\ 's'$\"\n self.assertRaisesRegex(FrozenInstanceError, err, deepcopy, C(''))\n\n with self.subTest('user-defined __slots__ and __{get,set}state__'):\n @dataclass(frozen=True, slots=False)\n class C:\n __slots__ = ('s',)\n __getstate__ = dataclasses._dataclass_getstate\n __setstate__ = dataclasses._dataclass_setstate\n\n s: str\n\n c = C('hello')\n self.assertEqual(deepcopy(c), c)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestFrozen","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_25.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestSlots(unittest.TestCase):\n def test_simple(self):\n @dataclass\n class C:\n __slots__ = ('x',)\n x: Any\n\n # There was a bug where a variable in a slot was assumed to\n # also have a default value (of type\n # types.MemberDescriptorType).\n with self.assertRaisesRegex(TypeError,\n r\"__init__\\(\\) missing 1 required positional argument: 'x'\"):\n C()\n\n # We can create an instance, and assign to x.\n c = C(10)\n self.assertEqual(c.x, 10)\n c.x = 5\n self.assertEqual(c.x, 5)\n\n # We can't assign to anything else.\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'y'\"):\n c.y = 5\n\n def test_derived_added_field(self):\n # See bpo-33100.\n @dataclass\n class Base:\n __slots__ = ('x',)\n x: Any\n\n @dataclass\n class Derived(Base):\n x: int\n y: int\n\n d = Derived(1, 2)\n self.assertEqual((d.x, d.y), (1, 2))\n\n # We can add a new field to the derived instance.\n d.z = 10\n\n def test_generated_slots(self):\n @dataclass(slots=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n self.assertEqual((c.x, c.y), (1, 2))\n\n c.x = 3\n c.y = 4\n self.assertEqual((c.x, c.y), (3, 4))\n\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'z'\"):\n c.z = 5\n\n def test_add_slots_when_slots_exists(self):\n with self.assertRaisesRegex(TypeError, '^C already specifies __slots__$'):\n @dataclass(slots=True)\n class C:\n __slots__ = ('x',)\n x: int\n\n def test_generated_slots_value(self):\n\n class Root:\n __slots__ = {'x'}\n\n class Root2(Root):\n __slots__ = {'k': '...', 'j': ''}\n\n class Root3(Root2):\n __slots__ = ['h']\n\n class Root4(Root3):\n __slots__ = 'aa'\n\n @dataclass(slots=True)\n class Base(Root4):\n y: int\n j: str\n h: str\n\n self.assertEqual(Base.__slots__, ('y',))\n\n @dataclass(slots=True)\n class Derived(Base):\n aa: float\n x: str\n z: int\n k: str\n h: str\n\n self.assertEqual(Derived.__slots__, ('z',))\n\n @dataclass\n class AnotherDerived(Base):\n z: int\n\n self.assertNotIn('__slots__', AnotherDerived.__dict__)\n\n def test_slots_with_docs(self):\n class Root:\n __slots__ = {'x': 'x'}\n\n @dataclass(slots=True)\n class Base(Root):\n y1: int = field(doc='y1')\n y2: int\n\n self.assertEqual(Base.__slots__, {'y1': 'y1', 'y2': None})\n\n @dataclass(slots=True)\n class Child(Base):\n z1: int = field(doc='z1')\n z2: int\n\n self.assertEqual(Child.__slots__, {'z1': 'z1', 'z2': None})\n\n def test_cant_inherit_from_iterator_slots(self):\n\n class Root:\n __slots__ = iter(['a'])\n\n class Root2(Root):\n __slots__ = ('b', )\n\n with self.assertRaisesRegex(\n TypeError,\n \"^Slots of 'Root' cannot be determined\"\n ):\n @dataclass(slots=True)\n class C(Root2):\n x: int\n\n def test_returns_new_class(self):\n class A:\n x: int\n\n B = dataclass(A, slots=True)\n self.assertIsNot(A, B)\n\n self.assertNotHasAttr(A, \"__slots__\")\n self.assertHasAttr(B, \"__slots__\")\n\n # Can't be local to test_frozen_pickle.\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsClass:\n foo: str\n bar: int\n\n @dataclass(frozen=True)\n class FrozenWithoutSlotsClass:\n foo: str\n bar: int\n\n def test_frozen_pickle(self):\n # bpo-43999\n\n self.assertEqual(self.FrozenSlotsClass.__slots__, (\"foo\", \"bar\"))\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n obj = self.FrozenWithoutSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsGetStateClass:\n foo: str\n bar: int\n\n getstate_called: bool = field(default=False, compare=False)\n\n def __getstate__(self):\n object.__setattr__(self, 'getstate_called', True)\n return [self.foo, self.bar]\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsSetStateClass:\n foo: str\n bar: int\n\n setstate_called: bool = field(default=False, compare=False)\n\n def __setstate__(self, state):\n object.__setattr__(self, 'setstate_called', True)\n object.__setattr__(self, 'foo', state[0])\n object.__setattr__(self, 'bar', state[1])\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsAllStateClass:\n foo: str\n bar: int\n\n getstate_called: bool = field(default=False, compare=False)\n setstate_called: bool = field(default=False, compare=False)\n\n def __getstate__(self):\n object.__setattr__(self, 'getstate_called', True)\n return [self.foo, self.bar]\n\n def __setstate__(self, state):\n object.__setattr__(self, 'setstate_called', True)\n object.__setattr__(self, 'foo', state[0])\n object.__setattr__(self, 'bar', state[1])\n\n def test_frozen_slots_pickle_custom_state(self):\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsGetStateClass('a', 1)\n dumped = pickle.dumps(obj, protocol=proto)\n\n self.assertTrue(obj.getstate_called)\n self.assertEqual(obj, pickle.loads(dumped))\n\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsSetStateClass('a', 1)\n obj2 = pickle.loads(pickle.dumps(obj, protocol=proto))\n\n self.assertTrue(obj2.setstate_called)\n self.assertEqual(obj, obj2)\n\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsAllStateClass('a', 1)\n dumped = pickle.dumps(obj, protocol=proto)\n\n self.assertTrue(obj.getstate_called)\n\n obj2 = pickle.loads(dumped)\n self.assertTrue(obj2.setstate_called)\n self.assertEqual(obj, obj2)\n\n def test_slots_with_default_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default='b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_with_default_factory_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default_factory=lambda:'b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_no_weakref(self):\n @dataclass(slots=True)\n class A:\n # No weakref.\n pass\n\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A()\n with self.assertRaisesRegex(TypeError,\n \"cannot create weak reference\"):\n weakref.ref(a)\n with self.assertRaises(AttributeError):\n a.__weakref__\n\n def test_slots_weakref(self):\n @dataclass(slots=True, weakref_slot=True)\n class A:\n a: int\n\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n\n self.assertIs(a.__weakref__, a_ref)\n\n def test_slots_weakref_base_str(self):\n class Base:\n __slots__ = '__weakref__'\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_slots_weakref_base_tuple(self):\n # Same as test_slots_weakref_base, but use a tuple instead of a string\n # in the base class.\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still\n # weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_weakref_slot_without_slot(self):\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n @dataclass(weakref_slot=True)\n class A:\n a: int\n\n def test_weakref_slot_make_dataclass(self):\n A = make_dataclass('A', [('a', int),], slots=True, weakref_slot=True)\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n # And make sure if raises if slots=True is not given.\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n B = make_dataclass('B', [('a', int),], weakref_slot=True)\n\n def test_weakref_slot_subclass_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n # A *can* also specify weakref_slot=True if it wants to (gh-93521)\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. But an instance of A\n # is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_weakref_slot_subclass_no_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n @dataclass(slots=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. Even though A doesn't\n # specify weakref_slot, it should still be weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_weakref_slot_normal_base_weakref_slot(self):\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n field: int\n\n # __weakref__ is in the base class, not A. But an instance of\n # A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_dataclass_derived_weakref_slot(self):\n class A:\n pass\n\n @dataclass(slots=True, weakref_slot=True)\n class B(A):\n pass\n\n self.assertEqual(B.__slots__, ())\n B()\n\n def test_dataclass_derived_generic(self):\n T = typing.TypeVar('T')\n\n @dataclass(slots=True, weakref_slot=True)\n class A(typing.Generic[T]):\n pass\n self.assertEqual(A.__slots__, ('__weakref__',))\n self.assertTrue(A.__weakref__)\n A()\n\n @dataclass(slots=True, weakref_slot=True)\n class B[T2]:\n pass\n self.assertEqual(B.__slots__, ('__weakref__',))\n self.assertTrue(B.__weakref__)\n B()\n\n def test_dataclass_derived_generic_from_base(self):\n T = typing.TypeVar('T')\n\n class RawBase: ...\n\n @dataclass(slots=True, weakref_slot=True)\n class C1(typing.Generic[T], RawBase):\n pass\n self.assertEqual(C1.__slots__, ())\n self.assertTrue(C1.__weakref__)\n C1()\n @dataclass(slots=True, weakref_slot=True)\n class C2(RawBase, typing.Generic[T]):\n pass\n self.assertEqual(C2.__slots__, ())\n self.assertTrue(C2.__weakref__)\n C2()\n\n @dataclass(slots=True, weakref_slot=True)\n class D[T2](RawBase):\n pass\n self.assertEqual(D.__slots__, ())\n self.assertTrue(D.__weakref__)\n D()\n\n def test_dataclass_derived_generic_from_slotted_base(self):\n T = typing.TypeVar('T')\n\n class WithSlots:\n __slots__ = ('a', 'b')\n\n @dataclass(slots=True, weakref_slot=True)\n class E1(WithSlots, Generic[T]):\n pass\n self.assertEqual(E1.__slots__, ('__weakref__',))\n self.assertTrue(E1.__weakref__)\n E1()\n @dataclass(slots=True, weakref_slot=True)\n class E2(Generic[T], WithSlots):\n pass\n self.assertEqual(E2.__slots__, ('__weakref__',))\n self.assertTrue(E2.__weakref__)\n E2()\n\n @dataclass(slots=True, weakref_slot=True)\n class F[T2](WithSlots):\n pass\n self.assertEqual(F.__slots__, ('__weakref__',))\n self.assertTrue(F.__weakref__)\n F()\n\n def test_dataclass_derived_generic_from_slotted_base_with_weakref(self):\n T = typing.TypeVar('T')\n\n class WithWeakrefSlot:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True, weakref_slot=True)\n class G1(WithWeakrefSlot, Generic[T]):\n pass\n self.assertEqual(G1.__slots__, ())\n self.assertTrue(G1.__weakref__)\n G1()\n @dataclass(slots=True, weakref_slot=True)\n class G2(Generic[T], WithWeakrefSlot):\n pass\n self.assertEqual(G2.__slots__, ())\n self.assertTrue(G2.__weakref__)\n G2()\n\n @dataclass(slots=True, weakref_slot=True)\n class H[T2](WithWeakrefSlot):\n pass\n self.assertEqual(H.__slots__, ())\n self.assertTrue(H.__weakref__)\n H()\n\n def test_dataclass_slot_dict(self):\n class WithDictSlot:\n __slots__ = ('__dict__',)\n\n @dataclass(slots=True)\n class A(WithDictSlot): ...\n\n self.assertEqual(A.__slots__, ())\n self.assertEqual(A().__dict__, {})\n A()\n\n @support.cpython_only\n def test_dataclass_slot_dict_ctype(self):\n # https://github.com/python/cpython/issues/123935\n # Skips test if `_testcapi` is not present:\n _testcapi = import_helper.import_module('_testcapi')\n\n @dataclass(slots=True)\n class HasDictOffset(_testcapi.HeapCTypeWithDict):\n __dict__: dict = {}\n self.assertNotEqual(_testcapi.HeapCTypeWithDict.__dictoffset__, 0)\n self.assertEqual(HasDictOffset.__slots__, ())\n\n @dataclass(slots=True)\n class DoesNotHaveDictOffset(_testcapi.HeapCTypeWithWeakref):\n __dict__: dict = {}\n self.assertEqual(_testcapi.HeapCTypeWithWeakref.__dictoffset__, 0)\n self.assertEqual(DoesNotHaveDictOffset.__slots__, ('__dict__',))\n\n @support.cpython_only\n def test_slots_with_wrong_init_subclass(self):\n # TODO: This test is for a kinda-buggy behavior.\n # Ideally, it should be fixed and `__init_subclass__`\n # should be fully supported in the future versions.\n # See https://github.com/python/cpython/issues/91126\n class WrongSuper:\n def __init_subclass__(cls, arg):\n pass\n\n with self.assertRaisesRegex(\n TypeError,\n \"missing 1 required positional argument: 'arg'\",\n ):\n @dataclass(slots=True)\n class WithWrongSuper(WrongSuper, arg=1):\n pass\n\n class CorrectSuper:\n args = []\n def __init_subclass__(cls, arg=\"default\"):\n cls.args.append(arg)\n\n @dataclass(slots=True)\n class WithCorrectSuper(CorrectSuper):\n pass\n\n # __init_subclass__ is called twice: once for `WithCorrectSuper`\n # and once for `WithCorrectSuper__slots__` new class\n # that we create internally.\n self.assertEqual(CorrectSuper.args, [\"default\", \"default\"])\n\n def test_original_class_is_gced(self):\n # gh-135228: Make sure when we replace the class with slots=True, the original class\n # gets garbage collected.\n def make_simple():\n @dataclass(slots=True)\n class SlotsTest:\n pass\n\n return SlotsTest\n\n def make_with_annotations():\n @dataclass(slots=True)\n class SlotsTest:\n x: int\n\n return SlotsTest\n\n def make_with_annotations_and_method():\n @dataclass(slots=True)\n class SlotsTest:\n x: int\n\n def method(self) -> int:\n return self.x\n\n return SlotsTest\n\n for make in (make_simple, make_with_annotations, make_with_annotations_and_method):\n with self.subTest(make=make):\n C = make()\n support.gc_collect()\n candidates = [cls for cls in object.__subclasses__() if cls.__name__ == 'SlotsTest'\n and cls.__firstlineno__ == make.__code__.co_firstlineno + 1]\n self.assertEqual(candidates, [C])\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestSlots","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_26.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestDescriptors(unittest.TestCase):\n def test_set_name(self):\n # See bpo-33141.\n\n # Create a descriptor.\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n def __get__(self, instance, owner):\n if instance is not None:\n return 1\n return self\n\n # This is the case of just normal descriptor behavior, no\n # dataclass code is involved in initializing the descriptor.\n @dataclass\n class C:\n c: int=D()\n self.assertEqual(C.c.name, 'cx')\n\n # Now test with a default value and init=False, which is the\n # only time this is really meaningful. If not using\n # init=False, then the descriptor will be overwritten, anyway.\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n self.assertEqual(C().c, 1)\n\n def test_non_descriptor(self):\n # PEP 487 says __set_name__ should work on non-descriptors.\n # Create a descriptor.\n\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n\n def test_lookup_on_instance(self):\n # See bpo-33175.\n class D:\n pass\n\n d = D()\n # Create an attribute on the instance, not type.\n d.__set_name__ = Mock()\n\n # Make sure d.__set_name__ is not called.\n @dataclass\n class C:\n i: int=field(default=d, init=False)\n\n self.assertEqual(d.__set_name__.call_count, 0)\n\n def test_lookup_on_class(self):\n # See bpo-33175.\n class D:\n pass\n D.__set_name__ = Mock()\n\n # Make sure D.__set_name__ is called.\n @dataclass\n class C:\n i: int=field(default=D(), init=False)\n\n self.assertEqual(D.__set_name__.call_count, 1)\n\n def test_init_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_getting_field_calls_get(self):\n class D:\n pass\n\n D.__set__ = Mock()\n D.__get__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__get__ is called.\n D.__get__.reset_mock()\n value = c.i\n self.assertEqual(D.__get__.call_count, 1)\n\n def test_setting_field_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c.i = 10\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_setting_uninitialized_descriptor_field(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D\n\n # D.__set__ is not called because there's no D instance to call it on\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 0)\n\n # D.__set__ still isn't called after setting i to an instance of D\n # because descriptors don't behave like that when stored as instance vars\n c.i = D()\n c.i = 5\n self.assertEqual(D.__set__.call_count, 0)\n\n def test_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n return 100\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n c = C()\n self.assertEqual(c.i, 100)\n\n c = C(5)\n self.assertEqual(c.i, 5)\n\n def test_no_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n raise AttributeError()\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):\n c = C()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestDescriptors","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_27.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestMakeDataclass(unittest.TestCase):\n def test_simple(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace={'add_one': lambda self: self.x + 1})\n c = C(10)\n self.assertEqual((c.x, c.y), (10, 5))\n self.assertEqual(c.add_one(), 11)\n\n\n def test_no_mutate_namespace(self):\n # Make sure a provided namespace isn't mutated.\n ns = {}\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace=ns)\n self.assertEqual(ns, {})\n\n def test_base(self):\n class Base1:\n pass\n class Base2:\n pass\n C = make_dataclass('C',\n [('x', int)],\n bases=(Base1, Base2))\n c = C(2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n def test_base_dataclass(self):\n @dataclass\n class Base1:\n x: int\n class Base2:\n pass\n C = make_dataclass('C',\n [('y', int)],\n bases=(Base1, Base2))\n with self.assertRaisesRegex(TypeError, 'required positional'):\n c = C(2)\n c = C(1, 2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n self.assertEqual((c.x, c.y), (1, 2))\n\n def test_init_var(self):\n def post_init(self, y):\n self.x *= y\n\n C = make_dataclass('C',\n [('x', int),\n ('y', InitVar[int]),\n ],\n namespace={'__post_init__': post_init},\n )\n c = C(2, 3)\n self.assertEqual(vars(c), {'x': 6})\n self.assertEqual(len(fields(c)), 1)\n\n def test_class_var(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ])\n c = C(1)\n self.assertEqual(vars(c), {'x': 1})\n self.assertEqual(len(fields(c)), 1)\n self.assertEqual(C.y, 10)\n self.assertEqual(C.z, 20)\n\n def test_other_params(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ],\n init=False)\n # Make sure we have a repr, but no init.\n self.assertNotIn('__init__', vars(C))\n self.assertIn('__repr__', vars(C))\n\n # Make sure random other params don't work.\n with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):\n C = make_dataclass('C',\n [],\n xxinit=False)\n\n def test_no_types(self):\n C = make_dataclass('Point', ['x', 'y', 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': typing.Any,\n 'y': typing.Any,\n 'z': typing.Any})\n\n C = make_dataclass('Point', ['x', ('y', int), 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': typing.Any,\n 'y': int,\n 'z': typing.Any})\n\n def test_no_types_get_annotations(self):\n C = make_dataclass('C', ['x', ('y', int), 'z'])\n\n self.assertEqual(\n annotationlib.get_annotations(C, format=annotationlib.Format.VALUE),\n {'x': typing.Any, 'y': int, 'z': typing.Any},\n )\n self.assertEqual(\n annotationlib.get_annotations(\n C, format=annotationlib.Format.FORWARDREF),\n {'x': typing.Any, 'y': int, 'z': typing.Any},\n )\n self.assertEqual(\n annotationlib.get_annotations(\n C, format=annotationlib.Format.STRING),\n {'x': 'typing.Any', 'y': 'int', 'z': 'typing.Any'},\n )\n\n def test_no_types_no_typing_import(self):\n with import_helper.CleanImport('typing'):\n self.assertNotIn('typing', sys.modules)\n C = make_dataclass('C', ['x', ('y', int)])\n\n self.assertNotIn('typing', sys.modules)\n self.assertEqual(\n C.__annotate__(annotationlib.Format.FORWARDREF),\n {\n 'x': annotationlib.ForwardRef('Any', module='typing'),\n 'y': int,\n },\n )\n self.assertNotIn('typing', sys.modules)\n\n for field in fields(C):\n if field.name == \"x\":\n self.assertEqual(field.type, annotationlib.ForwardRef('Any', module='typing'))\n else:\n self.assertEqual(field.name, \"y\")\n self.assertIs(field.type, int)\n\n def test_module_attr(self):\n self.assertEqual(ByMakeDataClass.__module__, __name__)\n self.assertEqual(ByMakeDataClass(1).__module__, __name__)\n self.assertEqual(WrongModuleMakeDataclass.__module__, \"custom\")\n Nested = make_dataclass('Nested', [])\n self.assertEqual(Nested.__module__, __name__)\n self.assertEqual(Nested().__module__, __name__)\n\n def test_pickle_support(self):\n for klass in [ByMakeDataClass, ManualModuleMakeDataClass]:\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n self.assertEqual(\n pickle.loads(pickle.dumps(klass, proto)),\n klass,\n )\n self.assertEqual(\n pickle.loads(pickle.dumps(klass(1), proto)),\n klass(1),\n )\n\n def test_cannot_be_pickled(self):\n for klass in [WrongNameMakeDataclass, WrongModuleMakeDataclass]:\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n with self.assertRaises(pickle.PickleError):\n pickle.dumps(klass, proto)\n with self.assertRaises(pickle.PickleError):\n pickle.dumps(klass(1), proto)\n\n def test_invalid_type_specification(self):\n for bad_field in [(),\n (1, 2, 3, 4),\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'Invalid field: '):\n make_dataclass('C', ['a', bad_field])\n\n # And test for things with no len().\n for bad_field in [float,\n lambda x:x,\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'has no len\\(\\)'):\n make_dataclass('C', ['a', bad_field])\n\n def test_duplicate_field_names(self):\n for field in ['a', 'ab']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'Field name duplicated'):\n make_dataclass('C', [field, 'a', field])\n\n def test_keyword_field_names(self):\n for field in ['for', 'async', 'await', 'as']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field, 'a'])\n\n def test_non_identifier_field_names(self):\n for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field, 'a'])\n\n def test_underscore_field_names(self):\n # Unlike namedtuple, it's okay if dataclass field names have\n # an underscore.\n make_dataclass('C', ['_', '_a', 'a_a', 'a_'])\n\n def test_funny_class_names_names(self):\n # No reason to prevent weird class names, since\n # types.new_class allows them.\n for classname in ['()', 'x,y', '*', '2@3', '']:\n with self.subTest(classname=classname):\n C = make_dataclass(classname, ['a', 'b'])\n self.assertEqual(C.__name__, classname)\n\n def test_dataclass_decorator_default(self):\n C = make_dataclass('C', [('x', int)], decorator=dataclass)\n c = C(10)\n self.assertEqual(c.x, 10)\n\n def test_dataclass_custom_decorator(self):\n def custom_dataclass(cls, *args, **kwargs):\n dc = dataclass(cls, *args, **kwargs)\n dc.__custom__ = True\n return dc\n\n C = make_dataclass('C', [('x', int)], decorator=custom_dataclass)\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertEqual(c.__custom__, True)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestMakeDataclass","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_28.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestReplace(unittest.TestCase):\n def test(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n z: int = field(init=False, default=10)\n t: int = field(init=False, default=100)\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))\n self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))\n\n\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, x=3, z=20, t=50)\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, z=20)\n replace(c, x=3, z=20, t=50)\n\n # Make sure the result is still frozen.\n with self.assertRaisesRegex(FrozenInstanceError, \"cannot assign to field 'x'\"):\n c1.x = 3\n\n # Make sure we can't replace an attribute that doesn't exist,\n # if we're also replacing one that does exist. Test this\n # here, because setting attributes on frozen instances is\n # handled slightly differently from non-frozen ones.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'a'\"):\n c1 = replace(c, x=20, a=5)\n\n def test_invalid_field_name(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'z'\"):\n c1 = replace(c, z=3)\n\n def test_invalid_object(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(C, x=3)\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(0, x=3)\n\n def test_no_init(self):\n @dataclass\n class C:\n x: int\n y: int = field(init=False, default=10)\n\n c = C(1)\n c.y = 20\n\n # Make sure y gets the default value.\n c1 = replace(c, x=5)\n self.assertEqual((c1.x, c1.y), (5, 10))\n\n # Trying to replace y is an error.\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, x=2, y=30)\n\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, y=30)\n\n def test_classvar(self):\n @dataclass\n class C:\n x: int\n y: ClassVar[int] = 1000\n\n c = C(1)\n d = C(2)\n\n self.assertIs(c.y, d.y)\n self.assertEqual(c.y, 1000)\n\n # Trying to replace y is an error: can't replace ClassVars.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an \"\n \"unexpected keyword argument 'y'\"):\n replace(c, y=30)\n\n replace(c, x=5)\n\n def test_initvar_is_specified(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int]\n\n def __post_init__(self, y):\n self.x *= y\n\n c = C(1, 10)\n self.assertEqual(c.x, 10)\n with self.assertRaisesRegex(TypeError, r\"InitVar 'y' must be \"\n r\"specified with replace\\(\\)\"):\n replace(c, x=3)\n c = replace(c, x=3, y=5)\n self.assertEqual(c.x, 15)\n\n def test_initvar_with_default_value(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int] = None\n z: InitVar[int] = 42\n\n def __post_init__(self, y, z):\n if y is not None:\n self.x += y\n if z is not None:\n self.x += z\n\n c = C(x=1, y=10, z=1)\n self.assertEqual(replace(c), C(x=12))\n self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42))\n self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1))\n\n def test_recursive_repr(self):\n @dataclass\n class C:\n f: \"C\"\n\n c = C(None)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr..C(f=...)\")\n\n def test_recursive_repr_two_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: \"C\"\n\n c = C(None, None)\n c.f = c\n c.g = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_two_attrs\"\n \"..C(f=..., g=...)\")\n\n def test_recursive_repr_indirection(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n c.f = d\n d.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection\"\n \"..C(f=TestReplace.test_recursive_repr_indirection\"\n \"..D(f=...))\")\n\n def test_recursive_repr_indirection_two(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"E\"\n\n @dataclass\n class E:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n e = E(None)\n c.f = d\n d.f = e\n e.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection_two\"\n \"..C(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..D(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..E(f=...)))\")\n\n def test_recursive_repr_misc_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: int\n\n c = C(None, 1)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_misc_attrs\"\n \"..C(f=..., g=1)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestReplace","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_29.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestAbstract(unittest.TestCase):\n def test_abc_implementation(self):\n class Ordered(abc.ABC):\n @abc.abstractmethod\n def __lt__(self, other):\n pass\n\n @abc.abstractmethod\n def __le__(self, other):\n pass\n\n @dataclass(order=True)\n class Date(Ordered):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertFalse(inspect.isabstract(Date))\n self.assertGreater(Date(2020,12,25), Date(2020,8,31))\n\n def test_maintain_abc(self):\n class A(abc.ABC):\n @abc.abstractmethod\n def foo(self):\n pass\n\n @dataclass\n class Date(A):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertTrue(inspect.isabstract(Date))\n msg = \"class Date without an implementation for abstract method 'foo'\"\n self.assertRaisesRegex(TypeError, msg, Date)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestAbstract","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_30.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestMatchArgs(unittest.TestCase):\n def test_match_args(self):\n @dataclass\n class C:\n a: int\n self.assertEqual(C(42).__match_args__, ('a',))\n\n def test_explicit_match_args(self):\n ma = ()\n @dataclass\n class C:\n a: int\n __match_args__ = ma\n self.assertIs(C(42).__match_args__, ma)\n\n def test_bpo_43764(self):\n @dataclass(repr=False, eq=False, init=False)\n class X:\n a: int\n b: int\n c: int\n self.assertEqual(X.__match_args__, (\"a\", \"b\", \"c\"))\n\n def test_match_args_argument(self):\n @dataclass(match_args=False)\n class X:\n a: int\n self.assertNotIn('__match_args__', X.__dict__)\n\n @dataclass(match_args=False)\n class Y:\n a: int\n __match_args__ = ('b',)\n self.assertEqual(Y.__match_args__, ('b',))\n\n @dataclass(match_args=False)\n class Z(Y):\n z: int\n self.assertEqual(Z.__match_args__, ('b',))\n\n # Ensure parent dataclass __match_args__ is seen, if child class\n # specifies match_args=False.\n @dataclass\n class A:\n a: int\n z: int\n @dataclass(match_args=False)\n class B(A):\n b: int\n self.assertEqual(B.__match_args__, ('a', 'z'))\n\n def test_make_dataclasses(self):\n C = make_dataclass('C', [('x', int), ('y', int)])\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=True)\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=False)\n self.assertNotIn('__match__args__', C.__dict__)\n\n C = make_dataclass('C', [('x', int), ('y', int)], namespace={'__match_args__': ('z',)})\n self.assertEqual(C.__match_args__, ('z',))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestMatchArgs","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_31.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import import_helper\n\n\nclass TestKeywordArgs(unittest.TestCase):\n def test_no_classvar_kwarg(self):\n msg = 'field a is a ClassVar but specifies kw_only'\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=True)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass(kw_only=True)\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n def test_field_marked_as_kwonly(self):\n #######################\n # Using dataclass(kw_only=True)\n @dataclass(kw_only=True)\n class A:\n a: int\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Using dataclass(kw_only=False)\n @dataclass(kw_only=False)\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Not specifying dataclass(kw_only)\n @dataclass\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n def test_match_args(self):\n # kw fields don't show up in __match_args__.\n @dataclass(kw_only=True)\n class C:\n a: int\n self.assertEqual(C(a=42).__match_args__, ())\n\n @dataclass\n class C:\n a: int\n b: int = field(kw_only=True)\n self.assertEqual(C(42, b=10).__match_args__, ('a',))\n\n def test_KW_ONLY(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n\n @dataclass(kw_only=True)\n class B:\n a: int\n _: KW_ONLY\n b: int\n c: int\n B(a=3, b=4, c=5)\n msg = \"takes 1 positional argument but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n B(3, 4, 5)\n\n # Explicitly make a field that follows KW_ONLY be non-keyword-only.\n @dataclass\n class C:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=False)\n c = C(1, 2, b=3)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(c=2, b=3, a=1)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n\n def test_KW_ONLY_as_string(self):\n @dataclass\n class A:\n a: int\n _: 'dataclasses.KW_ONLY'\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n def test_KW_ONLY_twice(self):\n msg = \"'Y' is KW_ONLY, but KW_ONLY has already been specified\"\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n Y: KW_ONLY\n b: int\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n Y: KW_ONLY\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n c: int\n Y: KW_ONLY\n\n # But this usage is okay, since it's not using KW_ONLY.\n @dataclass\n class NoDuplicateKwOnlyAnnotation:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=True)\n\n # And if inheriting, it's okay.\n @dataclass\n class BaseUsesKwOnly:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class SubclassUsesKwOnly(BaseUsesKwOnly):\n _: KW_ONLY\n d: int\n\n # Make sure the error is raised in a derived class.\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n X: KW_ONLY\n d: int\n Y: KW_ONLY\n\n\n def test_post_init(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n raise CustomError(f'{b=} {d=}')\n with self.assertRaisesRegex(CustomError, 'b=3 d=4'):\n A(1, c=2, b=3, d=4)\n\n @dataclass\n class B:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n self.a = b\n self.c = d\n b = B(1, c=2, b=3, d=4)\n self.assertEqual(asdict(b), {'a': 3, 'c': 4})\n\n def test_defaults(self):\n # For kwargs, make sure we can have defaults after non-defaults.\n @dataclass\n class A:\n a: int = 0\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n a = A(d=4, b=3)\n self.assertEqual(a.a, 0)\n self.assertEqual(a.b, 3)\n self.assertEqual(a.c, 1)\n self.assertEqual(a.d, 4)\n\n # Make sure we still check for non-kwarg non-defaults not following\n # defaults.\n err_regex = \"non-default argument 'z' follows default argument 'a'\"\n with self.assertRaisesRegex(TypeError, err_regex):\n @dataclass\n class A:\n a: int = 0\n z: int\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n def test_make_dataclass(self):\n A = make_dataclass(\"A\", ['a'], kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n B = make_dataclass(\"B\",\n ['a', ('b', int, field(kw_only=False))],\n kw_only=True)\n self.assertTrue(fields(B)[0].kw_only)\n self.assertFalse(fields(B)[1].kw_only)\n\n def test_deferred_annotations(self):\n @dataclass\n class A:\n x: undefined\n y: ClassVar[undefined]\n\n fs = fields(A)\n self.assertEqual(len(fs), 1)\n self.assertEqual(fs[0].name, 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestKeywordArgs","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"dict-union","pep":"584","introduced_in":"3.9","form":"modern","file":"dict-union/modern_01.py","code":"import collections\nimport collections.abc\nimport gc\nimport pickle\nimport random\nimport re\nimport string\nimport sys\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import import_helper\nfrom test import mapping_tests\n\n\ndef test_merge_operator(self):\n\n a = {0: 0, 1: 1, 2: 1}\n b = {1: 1, 2: 2, 3: 3}\n\n c = a.copy()\n c |= b\n\n self.assertEqual(a | b, {0: 0, 1: 1, 2: 2, 3: 3})\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n c = b.copy()\n c |= a\n\n self.assertEqual(b | a, {1: 1, 2: 1, 3: 3, 0: 0})\n self.assertEqual(c, {1: 1, 2: 1, 3: 3, 0: 0})\n\n c = a.copy()\n c |= [(1, 1), (2, 2), (3, 3)]\n\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n self.assertIs(a.__or__(None), NotImplemented)\n self.assertIs(a.__or__(()), NotImplemented)\n self.assertIs(a.__or__(\"BAD\"), NotImplemented)\n self.assertIs(a.__or__(\"\"), NotImplemented)\n\n self.assertRaises(TypeError, a.__ior__, None)\n self.assertEqual(a.__ior__(()), {0: 0, 1: 1, 2: 1})\n self.assertRaises(ValueError, a.__ior__, \"BAD\")\n self.assertEqual(a.__ior__(\"\"), {0: 0, 1: 1, 2: 1})\n","source":"cpython_tests","origin":"Lib/test/test_dict.py::DictTest.test_merge_operator","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"exception-notes","pep":"678","introduced_in":"3.11","form":"modern","file":"exception-notes/modern_01.py","code":"import copy\nimport os\nimport sys\nimport unittest\nimport pickle\nimport weakref\nimport errno\nfrom codecs import BOM_UTF8\nfrom itertools import product\nfrom textwrap import dedent\nfrom test.support import (captured_stderr, check_impl_detail,\n cpython_only, gc_collect,\n no_tracing, script_helper,\n SuppressCrashReport,\n force_not_colorized)\nfrom test.support.import_helper import import_module\nfrom test.support.os_helper import TESTFN, unlink\nfrom test.support.warnings_helper import check_warnings\nfrom test import support\n\n\ndef test_notes(self):\n for e in [BaseException(1), Exception(2), ValueError(3)]:\n with self.subTest(e=e):\n self.assertNotHasAttr(e, '__notes__')\n e.add_note(\"My Note\")\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n with self.assertRaises(TypeError):\n e.add_note(42)\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n e.add_note(\"Your Note\")\n self.assertEqual(e.__notes__, [\"My Note\", \"Your Note\"])\n\n del e.__notes__\n self.assertNotHasAttr(e, '__notes__')\n\n e.add_note(\"Our Note\")\n self.assertEqual(e.__notes__, [\"Our Note\"])\n\n e.__notes__ = 42\n self.assertEqual(e.__notes__, 42)\n\n with self.assertRaises(TypeError):\n e.add_note(\"will not work\")\n self.assertEqual(e.__notes__, 42)\n","source":"cpython_tests","origin":"Lib/test/test_exceptions.py::ExceptionTests.test_notes","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"numeric-underscores","pep":"515","introduced_in":"3.6","form":"modern","file":"numeric-underscores/modern_01.py","code":"import sys\nimport unittest\nfrom unittest import mock\nfrom test import support\nfrom test.support.numbers import (\n VALID_UNDERSCORE_LITERALS,\n INVALID_UNDERSCORE_LITERALS,\n)\n\n\nclass IntStrDigitLimitsTests(unittest.TestCase):\n\n int_class = int # Override this in subclasses to reuse the suite.\n\n def setUp(self):\n super().setUp()\n self._previous_limit = sys.get_int_max_str_digits()\n sys.set_int_max_str_digits(2048)\n\n def tearDown(self):\n sys.set_int_max_str_digits(self._previous_limit)\n super().tearDown()\n\n def test_disabled_limit(self):\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n self.assertLess(sys.get_int_max_str_digits(), 20_000)\n with support.adjust_int_max_str_digits(0):\n self.assertEqual(sys.get_int_max_str_digits(), 0)\n i = self.int_class('1' * 20_000)\n str(i)\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n\n def test_max_str_digits_edge_cases(self):\n \"\"\"Ignore the +/- sign and space padding.\"\"\"\n int_class = self.int_class\n maxdigits = sys.get_int_max_str_digits()\n\n int_class('1' * maxdigits)\n int_class(' ' + '1' * maxdigits)\n int_class('1' * maxdigits + ' ')\n int_class('+' + '1' * maxdigits)\n int_class('-' + '1' * maxdigits)\n self.assertEqual(len(str(10 ** (maxdigits - 1))), maxdigits)\n\n def check(self, i, base=None):\n with self.assertRaises(ValueError):\n if base is None:\n self.int_class(i)\n else:\n self.int_class(i, base)\n\n def test_max_str_digits(self):\n maxdigits = sys.get_int_max_str_digits()\n\n self.check('1' * (maxdigits + 1))\n self.check(' ' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1) + ' ')\n self.check('+' + '1' * (maxdigits + 1))\n self.check('-' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1))\n\n i = 10 ** maxdigits\n with self.assertRaises(ValueError):\n str(i)\n\n def test_denial_of_service_prevented_int_to_str(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 50_000, maxdigits # A test prerequisite.\n\n huge_int = int(f'0x{\"c\"*65_000}', base=16) # 78268 decimal digits.\n digits = 78_268\n with (\n support.adjust_int_max_str_digits(digits),\n support.Stopwatch() as sw_convert):\n huge_decimal = str(huge_int)\n self.assertEqual(len(huge_decimal), digits)\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if sw_convert.seconds < sw_convert.clock_info.resolution * 2:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{sw_convert.seconds} seconds.')\n\n # We test with the limit almost at the size needed to check performance.\n # The performant limit check is slightly fuzzy, give it a some room.\n with support.adjust_int_max_str_digits(int(.995 * digits)):\n with (\n self.assertRaises(ValueError) as err,\n support.Stopwatch() as sw_fail_huge):\n str(huge_int)\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(sw_fail_huge.seconds, sw_convert.seconds/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge_int = int(f'0x{\"c\"*500_000}', base=16) # 602060 digits.\n with (\n self.assertRaises(ValueError) as err,\n support.Stopwatch() as sw_fail_extra_huge):\n # If not limited, 8 seconds said Zen based cloud VM.\n str(extra_huge_int)\n self.assertIn('conversion', str(err.exception))\n self.assertLess(sw_fail_extra_huge.seconds, sw_convert.seconds/2)\n\n def test_denial_of_service_prevented_str_to_int(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 100_000, maxdigits # A test prerequisite.\n\n digits = 133700\n huge = '8'*digits\n with (\n support.adjust_int_max_str_digits(digits),\n support.Stopwatch() as sw_convert):\n int(huge)\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if sw_convert.seconds < sw_convert.clock_info.resolution * 2:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{sw_convert.seconds} seconds.')\n\n with support.adjust_int_max_str_digits(digits - 1):\n with (\n self.assertRaises(ValueError) as err,\n support.Stopwatch() as sw_fail_huge):\n int(huge)\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(sw_fail_huge.seconds, sw_convert.seconds/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge = '7'*1_200_000\n with (\n self.assertRaises(ValueError) as err,\n support.Stopwatch() as sw_fail_extra_huge):\n # If not limited, 8 seconds in the Zen based cloud VM.\n int(extra_huge)\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(sw_fail_extra_huge.seconds, sw_convert.seconds/2)\n\n def test_power_of_two_bases_unlimited(self):\n \"\"\"The limit does not apply to power of 2 bases.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n\n for base in (2, 4, 8, 16, 32):\n with self.subTest(base=base):\n self.int_class('1' * (maxdigits + 1), base)\n assert maxdigits < 100_000\n self.int_class('1' * 100_000, base)\n\n def test_underscores_ignored(self):\n maxdigits = sys.get_int_max_str_digits()\n\n triples = maxdigits // 3\n s = '111' * triples\n s_ = '1_11' * triples\n self.int_class(s) # succeeds\n self.int_class(s_) # succeeds\n self.check(f'{s}111')\n self.check(f'{s_}_111')\n\n def test_sign_not_counted(self):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '5' * max_digits\n i = int_class(s)\n pos_i = int_class(f'+{s}')\n assert i == pos_i\n neg_i = int_class(f'-{s}')\n assert -pos_i == neg_i\n str(pos_i)\n str(neg_i)\n\n def _other_base_helper(self, base):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '2' * max_digits\n i = int_class(s, base)\n if base > 10:\n with self.assertRaises(ValueError):\n str(i)\n elif base < 10:\n str(i)\n with self.assertRaises(ValueError) as err:\n int_class(f'{s}1', base)\n\n def test_int_from_other_bases(self):\n base = 3\n with self.subTest(base=base):\n self._other_base_helper(base)\n base = 36\n with self.subTest(base=base):\n self._other_base_helper(base)\n\n def test_int_max_str_digits_is_per_interpreter(self):\n # Changing the limit in one interpreter does not change others.\n code = \"\"\"if 1:\n # Subinterpreters maintain and enforce their own limit\n import sys\n sys.set_int_max_str_digits(2323)\n try:\n int('3'*3333)\n except ValueError:\n pass\n else:\n raise AssertionError('Expected a int max str digits ValueError.')\n \"\"\"\n with support.adjust_int_max_str_digits(4000):\n before_value = sys.get_int_max_str_digits()\n self.assertEqual(support.run_in_subinterp(code), 0,\n 'subinterp code failure, check stderr.')\n after_value = sys.get_int_max_str_digits()\n self.assertEqual(before_value, after_value)\n","source":"cpython_tests","origin":"Lib/test/test_int.py::IntStrDigitLimitsTests","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"numeric-underscores","pep":"515","introduced_in":"3.6","form":"modern","file":"numeric-underscores/modern_02.py","code":"import sys\nimport unittest\nfrom unittest import mock\nfrom test import support\nfrom test.support.numbers import (\n VALID_UNDERSCORE_LITERALS,\n INVALID_UNDERSCORE_LITERALS,\n)\n\n\nclass PyLongModuleTests(unittest.TestCase):\n # Tests of the functions in _pylong.py. Those get used when the\n # number of digits in the input values are large enough.\n\n def setUp(self):\n super().setUp()\n self._previous_limit = sys.get_int_max_str_digits()\n sys.set_int_max_str_digits(0)\n\n def tearDown(self):\n sys.set_int_max_str_digits(self._previous_limit)\n super().tearDown()\n\n def _test_pylong_int_to_decimal(self, n, suffix):\n s = str(n)\n self.assertEqual(s[-10:], suffix)\n s2 = str(-n)\n self.assertEqual(s2, '-' + s)\n s3 = '%d' % n\n self.assertEqual(s3, s)\n s4 = b'%d' % n\n self.assertEqual(s4, s.encode('ascii'))\n\n def test_pylong_int_to_decimal(self):\n self._test_pylong_int_to_decimal((1 << 100_000), '9883109376')\n self._test_pylong_int_to_decimal((1 << 100_000) - 1, '9883109375')\n self._test_pylong_int_to_decimal(10**30_000, '0000000000')\n self._test_pylong_int_to_decimal(10**30_000 - 1, '9999999999')\n self._test_pylong_int_to_decimal(3**60_000, '9313200001')\n\n @support.requires_resource('cpu')\n def test_pylong_int_to_decimal_2(self):\n self._test_pylong_int_to_decimal(2**1_000_000, '2747109376')\n self._test_pylong_int_to_decimal(10**300_000, '0000000000')\n self._test_pylong_int_to_decimal(3**600_000, '3132000001')\n\n def test_pylong_int_divmod(self):\n n = (1 << 100_000)\n a, b = divmod(n*3 + 1, n)\n assert a == 3 and b == 1\n\n def test_pylong_str_to_int(self):\n v1 = 1 << 100_000\n s = str(v1)\n v2 = int(s)\n assert v1 == v2\n v3 = int(' -' + s)\n assert -v1 == v3\n v4 = int(' +' + s + ' ')\n assert v1 == v4\n with self.assertRaises(ValueError) as err:\n int(s + 'z')\n with self.assertRaises(ValueError) as err:\n int(s + '_')\n with self.assertRaises(ValueError) as err:\n int('_' + s)\n\n @support.cpython_only # tests implementation details of CPython.\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @mock.patch.object(_pylong, \"int_to_decimal_string\")\n def test_pylong_misbehavior_error_path_to_str(\n self, mock_int_to_str):\n with support.adjust_int_max_str_digits(20_000):\n big_value = int('7'*19_999)\n mock_int_to_str.return_value = None # not a str\n with self.assertRaises(TypeError) as ctx:\n str(big_value)\n self.assertIn('_pylong.int_to_decimal_string did not',\n str(ctx.exception))\n mock_int_to_str.side_effect = RuntimeError(\"testABC\")\n with self.assertRaises(RuntimeError):\n str(big_value)\n\n @support.cpython_only # tests implementation details of CPython.\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @mock.patch.object(_pylong, \"int_from_string\")\n def test_pylong_misbehavior_error_path_from_str(\n self, mock_int_from_str):\n big_value = '7'*19_999\n with support.adjust_int_max_str_digits(20_000):\n mock_int_from_str.return_value = b'not an int'\n with self.assertRaises(TypeError) as ctx:\n int(big_value)\n self.assertIn('_pylong.int_from_string did not',\n str(ctx.exception))\n\n mock_int_from_str.side_effect = RuntimeError(\"test123\")\n with self.assertRaises(RuntimeError):\n int(big_value)\n\n def test_pylong_roundtrip(self):\n from random import randrange, getrandbits\n bits = 5000\n while bits <= 1_000_000:\n bits += randrange(-100, 101) # break bitlength patterns\n hibit = 1 << (bits - 1)\n n = hibit | getrandbits(bits - 1)\n assert n.bit_length() == bits\n sn = str(n)\n self.assertNotStartsWith(sn, '0')\n self.assertEqual(n, int(sn))\n bits <<= 1\n\n @support.requires_resource('cpu')\n @unittest.skipUnless(_decimal, \"C _decimal module required\")\n def test_pylong_roundtrip_huge(self):\n # k blocks of 1234567890\n k = 1_000_000 # so 10 million digits in all\n tentoten = 10**10\n n = 1234567890 * ((tentoten**k - 1) // (tentoten - 1))\n sn = \"1234567890\" * k\n self.assertEqual(n, int(sn))\n self.assertEqual(sn, str(n))\n\n @support.requires_resource('cpu')\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @unittest.skipUnless(_decimal, \"C _decimal module required\")\n def test_whitebox_dec_str_to_int_inner_failsafe(self):\n # While I believe the number of GUARD digits in this function is\n # always enough so that no more than one correction step is ever\n # needed, the code has a \"failsafe\" path that takes over if I'm\n # wrong about that. We have no input that reaches that block.\n # Here we test a contrived input that _does_ reach that block,\n # provided the number of guard digits is reduced to 1.\n sn = \"9\" * 2000156\n n = 10**len(sn) - 1\n orig_spread = _pylong._spread.copy()\n _pylong._spread.clear()\n try:\n self.assertEqual(n, _pylong._dec_str_to_int_inner(sn, GUARD=1))\n self.assertIn(999, _pylong._spread)\n finally:\n _pylong._spread.clear()\n _pylong._spread.update(orig_spread)\n\n @unittest.skipUnless(_pylong, \"pylong module required\")\n @unittest.skipUnless(_decimal, \"C _decimal module required\")\n def test_whitebox_dec_str_to_int_inner_monster(self):\n # I don't think anyone has enough RAM to build a string long enough\n # for this function to complain. So lie about the string length.\n\n class LyingStr(str):\n def __len__(self):\n return int((1 << 47) / _pylong._LOG_10_BASE_256)\n\n liar = LyingStr(\"42\")\n # We have to pass the liar directly to the complaining function. If we\n # just try `int(liar)`, earlier layers will replace it with plain old\n # \"43\".\n # Embedding `len(liar)` into the f-string failed on the WASI testbot\n # (don't know what that is):\n # OverflowError: cannot fit 'int' into an index-sized integer\n # So a random stab at worming around that.\n self.assertRaisesRegex(ValueError,\n f\"^cannot convert string of len {liar.__len__()} to int$\",\n _pylong._dec_str_to_int_inner,\n liar)\n\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n def test_pylong_compute_powers(self):\n # Basic sanity tests. See end of _pylong.py for manual heavy tests.\n def consumer(w, base, limit, need_hi):\n seen = set()\n need = set()\n def inner(w):\n if w <= limit or w in seen:\n return\n seen.add(w)\n lo = w >> 1\n hi = w - lo\n need.add(hi if need_hi else lo)\n inner(lo)\n inner(hi)\n inner(w)\n d = _pylong.compute_powers(w, base, limit, need_hi=need_hi)\n self.assertEqual(d.keys(), need)\n for k, v in d.items():\n self.assertEqual(v, base ** k)\n\n for base in 2, 5:\n for need_hi in False, True:\n for limit in 1, 11:\n for w in range(250, 550):\n consumer(w, base, limit, need_hi)\n","source":"cpython_tests","origin":"Lib/test/test_int.py::PyLongModuleTests","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"tarfile-filter","pep":"706","introduced_in":"3.12","form":"modern","file":"tarfile-filter/modern_01.py","code":"import errno\nimport sys\nimport os\nimport io\nfrom hashlib import sha256\nfrom contextlib import contextmanager, ExitStack\nfrom random import Random\nimport pathlib\nimport shutil\nimport re\nimport warnings\nimport stat\nimport unittest\nimport unittest.mock\nimport tarfile\nfrom test import archiver_tests\nfrom test import support\nfrom test.support import os_helper\nfrom test.support import script_helper\nfrom test.support import warnings_helper\n\n\nclass TestExtractionFilters(unittest.TestCase):\n\n # A temporary directory for the extraction results.\n # All files that \"escape\" the destination path should still end\n # up in this directory.\n outerdir = pathlib.Path(TEMPDIR) / 'outerdir'\n\n # The destination for the extraction, within `outerdir`\n destdir = outerdir / 'dest'\n\n @contextmanager\n def check_context(self, tar, filter, *, check_flag=True):\n \"\"\"Extracts `tar` to `self.destdir` and allows checking the result\n\n If an error occurs, it must be checked using `expect_exception`\n\n Otherwise, all resulting files must be checked using `expect_file`,\n except the destination directory itself and parent directories of\n other files.\n When checking directories, do so before their contents.\n\n A file called 'flag' is made in outerdir (i.e. outside destdir)\n before extraction; it should not be altered nor should its contents\n be read/copied.\n \"\"\"\n with os_helper.temp_dir(self.outerdir):\n flag_path = self.outerdir / 'flag'\n flag_path.write_text('capture me')\n try:\n tar.extractall(self.destdir, filter=filter)\n except Exception as exc:\n self.raised_exception = exc\n self.reraise_exception = True\n self.expected_paths = set()\n else:\n self.raised_exception = None\n self.reraise_exception = False\n self.expected_paths = set(self.outerdir.glob('**/*'))\n self.expected_paths.discard(self.destdir)\n self.expected_paths.discard(flag_path)\n try:\n yield self\n finally:\n tar.close()\n if self.reraise_exception:\n raise self.raised_exception\n self.assertEqual(self.expected_paths, set())\n if check_flag:\n self.assertEqual(flag_path.read_text(), 'capture me')\n else:\n assert filter == 'fully_trusted'\n\n def expect_file(self, name, type=None, symlink_to=None, mode=None,\n size=None, content=None):\n \"\"\"Check a single file. See check_context.\"\"\"\n if self.raised_exception:\n raise self.raised_exception\n # use normpath() rather than resolve() so we don't follow symlinks\n path = pathlib.Path(os.path.normpath(self.destdir / name))\n self.assertIn(path, self.expected_paths)\n self.expected_paths.remove(path)\n if mode is not None and os_helper.can_chmod() and os.name != 'nt':\n got = stat.filemode(stat.S_IMODE(path.stat().st_mode))\n self.assertEqual(got, mode)\n if type is None and isinstance(name, str) and name.endswith('/'):\n type = tarfile.DIRTYPE\n if symlink_to is not None:\n got = (self.destdir / name).readlink()\n expected = pathlib.Path(symlink_to)\n # The symlink might be the same (textually) as what we expect,\n # but some systems change the link to an equivalent path, so\n # we fall back to samefile().\n try:\n if expected != got:\n self.assertTrue(got.samefile(expected))\n except Exception as e:\n # attach a note, so it's shown even if `samefile` fails\n e.add_note(f'{expected=}, {got=}')\n raise\n elif type == tarfile.REGTYPE or type is None:\n self.assertTrue(path.is_file())\n elif type == tarfile.DIRTYPE:\n self.assertTrue(path.is_dir())\n elif type == tarfile.FIFOTYPE:\n self.assertTrue(path.is_fifo())\n elif type == tarfile.SYMTYPE:\n self.assertTrue(path.is_symlink())\n else:\n raise NotImplementedError(type)\n if size is not None:\n self.assertEqual(path.stat().st_size, size)\n if content is not None:\n self.assertEqual(path.read_text(), content)\n for parent in path.parents:\n self.expected_paths.discard(parent)\n\n def expect_any_tree(self, name):\n \"\"\"Check a directory; forget about its contents.\"\"\"\n tree_path = (self.destdir / name).resolve()\n self.expect_file(tree_path, type=tarfile.DIRTYPE)\n self.expected_paths = {\n p for p in self.expected_paths\n if tree_path not in p.parents\n }\n\n def expect_exception(self, exc_type, message_re='.'):\n with self.assertRaisesRegex(exc_type, message_re):\n if self.raised_exception is not None:\n raise self.raised_exception\n self.reraise_exception = False\n return self.raised_exception\n\n def test_benign_file(self):\n with ArchiveMaker() as arc:\n arc.add('benign.txt')\n for filter in 'fully_trusted', 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_file('benign.txt')\n\n def test_absolute(self):\n # Test handling a member with an absolute path\n # Inspired by 'absolute1' in https://github.com/jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add(self.outerdir / 'escaped.evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('../escaped.evil')\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n if str(self.outerdir).startswith('/'):\n # We strip leading slashes, as e.g. GNU tar does\n # (without --absolute-filenames).\n outerdir_stripped = str(self.outerdir).lstrip('/')\n self.expect_file(f'{outerdir_stripped}/escaped.evil')\n else:\n # On this system, absolute paths don't have leading\n # slashes.\n # So, there's nothing to strip. We refuse to unpack\n # to an absolute path, nonetheless.\n self.expect_exception(\n tarfile.AbsolutePathError,\n \"\"\"['\"].*escaped.evil['\"] has an absolute path\"\"\")\n\n @symlink_test\n def test_parent_symlink(self):\n # Test interplaying symlinks\n # Inspired by 'dirsymlink2a' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n\n # `current` links to `.` which is both:\n # - the destination directory\n # - `current` itself\n arc.add('current', symlink_to='.')\n\n # effectively points to ./../\n arc.add('parent', symlink_to='current/..')\n\n arc.add('parent/evil')\n\n if os_helper.can_symlink():\n with self.check_context(arc.open(), 'fully_trusted'):\n if self.raised_exception is not None:\n # Windows will refuse to create a file that's a symlink to itself\n # (and tarfile doesn't swallow that exception)\n self.expect_exception(FileExistsError)\n # The other cases will fail with this error too.\n # Skip the rest of this test.\n return\n else:\n self.expect_file('current', symlink_to='.')\n self.expect_file('parent', symlink_to='current/..')\n self.expect_file('../evil')\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"\"\"'parent/evil' would be extracted to ['\"].*evil['\"], \"\"\"\n + \"which is outside the destination\")\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.LinkOutsideDestinationError,\n \"\"\"'parent' would link to ['\"].*outerdir['\"], \"\"\"\n + \"which is outside the destination\")\n\n else:\n # No symlink support. The symlinks are ignored.\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('parent/evil')\n with self.check_context(arc.open(), 'tar'):\n self.expect_file('parent/evil')\n with self.check_context(arc.open(), 'data'):\n self.expect_file('parent/evil')\n\n @symlink_test\n @os_helper.skip_unless_symlink\n def test_realpath_limit_attack(self):\n # (CVE-2025-4517)\n\n with ArchiveMaker() as arc:\n # populate the symlinks and dirs that expand in os.path.realpath()\n # The component length is chosen so that in common cases, the unexpanded\n # path fits in PATH_MAX, but it overflows when the final symlink\n # is expanded\n steps = \"abcdefghijklmnop\"\n if sys.platform == 'win32':\n component = 'd' * 25\n elif 'PC_PATH_MAX' in os.pathconf_names:\n max_path_len = os.pathconf(self.outerdir.parent, \"PC_PATH_MAX\")\n path_sep_len = 1\n dest_len = len(str(self.destdir)) + path_sep_len\n component_len = (max_path_len - dest_len) // (len(steps) + path_sep_len)\n component = 'd' * component_len\n else:\n raise NotImplementedError(\"Need to guess component length for {sys.platform}\")\n path = \"\"\n step_path = \"\"\n for i in steps:\n arc.add(os.path.join(path, component), type=tarfile.DIRTYPE,\n mode='drwxrwxrwx')\n arc.add(os.path.join(path, i), symlink_to=component)\n path = os.path.join(path, component)\n step_path = os.path.join(step_path, i)\n # create the final symlink that exceeds PATH_MAX and simply points\n # to the top dir.\n # this link will never be expanded by\n # os.path.realpath(strict=False), nor anything after it.\n linkpath = os.path.join(*steps, \"l\"*254)\n parent_segments = [\"..\"] * len(steps)\n arc.add(linkpath, symlink_to=os.path.join(*parent_segments))\n # make a symlink outside to keep the tar command happy\n arc.add(\"escape\", symlink_to=os.path.join(linkpath, \"..\"))\n # use the symlinks above, that are not checked, to create a hardlink\n # to a file outside of the destination path\n arc.add(\"flaglink\", hardlink_to=os.path.join(\"escape\", \"flag\"))\n # now that we have the hardlink we can overwrite the file\n arc.add(\"flaglink\", content='overwrite')\n # we can also create new files as well!\n arc.add(\"escape/newfile\", content='new')\n\n with (self.subTest('fully_trusted'),\n self.check_context(arc.open(), filter='fully_trusted',\n check_flag=False)):\n if sys.platform == 'win32':\n self.expect_exception((FileNotFoundError, FileExistsError))\n elif self.raised_exception:\n # Cannot symlink/hardlink: tarfile falls back to getmember()\n self.expect_exception(KeyError)\n # Otherwise, this block should never enter.\n else:\n self.expect_any_tree(component)\n self.expect_file('flaglink', content='overwrite')\n self.expect_file('../newfile', content='new')\n self.expect_file('escape', type=tarfile.SYMTYPE)\n self.expect_file('a', symlink_to=component)\n\n for filter in 'tar', 'data':\n with self.subTest(filter), self.check_context(arc.open(), filter=filter):\n exc = self.expect_exception((OSError, KeyError))\n if isinstance(exc, OSError):\n if sys.platform == 'win32':\n # 3: ERROR_PATH_NOT_FOUND\n # 5: ERROR_ACCESS_DENIED\n # 206: ERROR_FILENAME_EXCED_RANGE\n self.assertIn(exc.winerror, (3, 5, 206))\n else:\n self.assertEqual(exc.errno, errno.ENAMETOOLONG)\n\n @symlink_test\n def test_parent_symlink2(self):\n # Test interplaying symlinks\n # Inspired by 'dirsymlink2b' in jwilk/traversal-archives\n\n # Posix and Windows have different pathname resolution:\n # either symlink or a '..' component resolve first.\n # Let's see which we are on.\n if os_helper.can_symlink():\n testpath = os.path.join(TEMPDIR, 'resolution_test')\n os.mkdir(testpath)\n\n # testpath/current links to `.` which is all of:\n # - `testpath`\n # - `testpath/current`\n # - `testpath/current/current`\n # - etc.\n os.symlink('.', os.path.join(testpath, 'current'))\n\n # we'll test where `testpath/current/../file` ends up\n with open(os.path.join(testpath, 'current', '..', 'file'), 'w'):\n pass\n\n if os.path.exists(os.path.join(testpath, 'file')):\n # Windows collapses 'current\\..' to '.' first, leaving\n # 'testpath\\file'\n dotdot_resolves_early = True\n elif os.path.exists(os.path.join(testpath, '..', 'file')):\n # Posix resolves 'current' to '.' first, leaving\n # 'testpath/../file'\n dotdot_resolves_early = False\n else:\n raise AssertionError('Could not determine link resolution')\n\n with ArchiveMaker() as arc:\n\n # `current` links to `.` which is both the destination directory\n # and `current` itself\n arc.add('current', symlink_to='.')\n\n # `current/parent` is also available as `./parent`,\n # and effectively points to `./../`\n arc.add('current/parent', symlink_to='..')\n\n arc.add('parent/evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n if os_helper.can_symlink():\n self.expect_file('current', symlink_to='.')\n self.expect_file('parent', symlink_to='..')\n self.expect_file('../evil')\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'tar'):\n if os_helper.can_symlink():\n # Fail when extracting a file outside destination\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'data'):\n if os_helper.can_symlink():\n if dotdot_resolves_early:\n # Fail when extracting a file outside destination\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n # Fail as soon as we have a symlink outside the destination\n self.expect_exception(\n tarfile.LinkOutsideDestinationError,\n \"'current/parent' would link to \"\n + \"\"\"['\"].*outerdir['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n @symlink_test\n def test_absolute_symlink(self):\n # Test symlink to an absolute path\n # Inspired by 'dirsymlink' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('parent', symlink_to=self.outerdir)\n arc.add('parent/evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n if os_helper.can_symlink():\n self.expect_file('parent', symlink_to=self.outerdir)\n self.expect_file('../evil')\n else:\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'tar'):\n if os_helper.can_symlink():\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.AbsoluteLinkError,\n \"'parent' is a link to an absolute path\")\n\n def test_absolute_hardlink(self):\n # Test hardlink to an absolute path\n # Inspired by 'dirsymlink' in https://github.com/jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('parent', hardlink_to=self.outerdir / 'foo')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_exception(KeyError, \".*foo. not found\")\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_exception(KeyError, \".*foo. not found\")\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.AbsoluteLinkError,\n \"'parent' is a link to an absolute path\")\n\n @symlink_test\n def test_sly_relative0(self):\n # Inspired by 'relative0' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n # points to `../../tmp/moo`\n arc.add('../moo', symlink_to='..//tmp/moo')\n\n try:\n with self.check_context(arc.open(), filter='fully_trusted'):\n if os_helper.can_symlink():\n if isinstance(self.raised_exception, FileExistsError):\n # XXX TarFile happens to fail creating a parent\n # directory.\n # This might be a bug, but fixing it would hurt\n # security.\n # Note that e.g. GNU `tar` rejects '..' components,\n # so you could argue this is an invalid archive and we\n # just raise an bad type of exception.\n self.expect_exception(FileExistsError)\n else:\n self.expect_file('../moo', symlink_to='..//tmp/moo')\n else:\n # The symlink can't be extracted and is ignored\n pass\n except FileExistsError:\n pass\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'../moo' would be extracted to \"\n + \"'.*moo', which is outside \"\n + \"the destination\")\n\n @symlink_test\n def test_sly_relative2(self):\n # Inspired by 'relative2' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('tmp/')\n arc.add('tmp/../../moo', symlink_to='tmp/../..//tmp/moo')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('tmp', type=tarfile.DIRTYPE)\n if os_helper.can_symlink():\n self.expect_file('../moo', symlink_to='tmp/../../tmp/moo')\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'tmp/../../moo' would be extracted to \"\n + \"\"\"['\"].*moo['\"], which is outside the \"\"\"\n + \"destination\")\n\n @symlink_test\n def test_deep_symlink(self):\n # Test that symlinks and hardlinks inside a directory\n # point to the correct file (`target` of size 3).\n # If links aren't supported we get a copy of the file.\n with ArchiveMaker() as arc:\n arc.add('targetdir/target', size=3)\n # a hardlink's linkname is relative to the archive\n arc.add('linkdir/hardlink', hardlink_to=os.path.join(\n 'targetdir', 'target'))\n # a symlink's linkname is relative to the link's directory\n arc.add('linkdir/symlink', symlink_to=os.path.join(\n '..', 'targetdir', 'target'))\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n self.expect_file('targetdir/target', size=3)\n self.expect_file('linkdir/hardlink', size=3)\n if os_helper.can_symlink():\n self.expect_file('linkdir/symlink', size=3,\n symlink_to='../targetdir/target')\n else:\n self.expect_file('linkdir/symlink', size=3)\n\n @symlink_test\n def test_chains(self):\n # Test chaining of symlinks/hardlinks.\n # Symlinks are created before the files they point to.\n with ArchiveMaker() as arc:\n arc.add('linkdir/symlink', symlink_to='hardlink')\n arc.add('symlink2', symlink_to=os.path.join(\n 'linkdir', 'hardlink2'))\n arc.add('targetdir/target', size=3)\n arc.add('linkdir/hardlink', hardlink_to=os.path.join('targetdir', 'target'))\n arc.add('linkdir/hardlink2', hardlink_to=os.path.join('linkdir', 'symlink'))\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n self.expect_file('targetdir/target', size=3)\n self.expect_file('linkdir/hardlink', size=3)\n self.expect_file('linkdir/hardlink2', size=3)\n if os_helper.can_symlink():\n self.expect_file('linkdir/symlink', size=3,\n symlink_to='hardlink')\n self.expect_file('symlink2', size=3,\n symlink_to='linkdir/hardlink2')\n else:\n self.expect_file('linkdir/symlink', size=3)\n self.expect_file('symlink2', size=3)\n\n @symlink_test\n def test_sneaky_hardlink_fallback(self):\n # (CVE-2025-4330)\n # Test that when hardlink extraction falls back to extracting members\n # from the archive, the extracted member is (re-)filtered.\n with ArchiveMaker() as arc:\n # Create a directory structure so the c/escape symlink stays\n # inside the path\n arc.add(\"a/t/dummy\")\n # Create b/ directory\n arc.add(\"b/\")\n # Point \"c\" to the bottom of the tree in \"a\"\n arc.add(\"c\", symlink_to=os.path.join(\"a\", \"t\"))\n # link to non-existant location under \"a\"\n arc.add(\"c/escape\", symlink_to=os.path.join(\"..\", \"..\",\n \"link_here\"))\n # Move \"c\" to point to \"b\" (\"c/escape\" no longer exists)\n arc.add(\"c\", symlink_to=\"b\")\n # Attempt to create a hard link to \"c/escape\". Since it doesn't\n # exist it will attempt to extract \"cescape\" but at \"boom\".\n arc.add(\"boom\", hardlink_to=os.path.join(\"c\", \"escape\"))\n\n with self.check_context(arc.open(), 'data'):\n if not os_helper.can_symlink():\n # When 'c/escape' is extracted, 'c' is a regular\n # directory, and 'c/escape' *would* point outside\n # the destination if symlinks were allowed.\n self.expect_exception(\n tarfile.LinkOutsideDestinationError)\n elif sys.platform == \"win32\":\n # On Windows, 'c/escape' points outside the destination\n self.expect_exception(tarfile.LinkOutsideDestinationError)\n else:\n e = self.expect_exception(\n tarfile.LinkFallbackError,\n \"link 'boom' would be extracted as a copy of \"\n + \"'c/escape', which was rejected\")\n self.assertIsInstance(e.__cause__,\n tarfile.LinkOutsideDestinationError)\n for filter in 'tar', 'fully_trusted':\n with self.subTest(filter), self.check_context(arc.open(), filter):\n if not os_helper.can_symlink():\n self.expect_file(\"a/t/dummy\")\n self.expect_file(\"b/\")\n self.expect_file(\"c/\")\n else:\n self.expect_file(\"a/t/dummy\")\n self.expect_file(\"b/\")\n self.expect_file(\"a/t/escape\", symlink_to='../../link_here')\n self.expect_file(\"boom\", symlink_to='../../link_here')\n self.expect_file(\"c\", symlink_to='b')\n\n @symlink_test\n def test_exfiltration_via_symlink(self):\n # (CVE-2025-4138)\n # Test changing symlinks that result in a symlink pointing outside\n # the extraction directory, unless prevented by 'data' filter's\n # normalization.\n with ArchiveMaker() as arc:\n arc.add(\"escape\", symlink_to=os.path.join('link', 'link', '..', '..', 'link-here'))\n arc.add(\"link\", symlink_to='./')\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n if os_helper.can_symlink():\n self.expect_file(\"link\", symlink_to='./')\n if filter == 'data':\n self.expect_file(\"escape\", symlink_to='link-here')\n else:\n self.expect_file(\"escape\",\n symlink_to='link/link/../../link-here')\n else:\n # Nothing is extracted.\n pass\n\n @symlink_test\n def test_chmod_outside_dir(self):\n # (CVE-2024-12718)\n # Test that members used for delayed updates of directory metadata\n # are (re-)filtered.\n with ArchiveMaker() as arc:\n # \"pwn\" is a veeeery innocent symlink:\n arc.add(\"a/pwn\", symlink_to='.')\n # But now \"pwn\" is also a directory, so it's scheduled to have its\n # metadata updated later:\n arc.add(\"a/pwn/\", mode='drwxrwxrwx')\n # Oops, \"pwn\" is not so innocent any more:\n arc.add(\"a/pwn\", symlink_to='x/../')\n # Newly created symlink points to the dest dir,\n # so it's OK for the \"data\" filter.\n arc.add('a/x', symlink_to=('../'))\n # But now \"pwn\" points outside the dest dir\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter) as cc:\n if not os_helper.can_symlink():\n self.expect_file(\"a/pwn/\")\n elif filter == 'data':\n self.expect_file(\"a/x\", symlink_to='../')\n self.expect_file(\"a/pwn\", symlink_to='.')\n else:\n self.expect_file(\"a/x\", symlink_to='../')\n self.expect_file(\"a/pwn\", symlink_to='x/../')\n if sys.platform != \"win32\":\n st_mode = cc.outerdir.stat().st_mode\n self.assertNotEqual(st_mode & 0o777, 0o777)\n\n def test_link_fallback_normalizes(self):\n # Make sure hardlink fallbacks work for non-normalized paths for all\n # filters\n with ArchiveMaker() as arc:\n arc.add(\"dir/\")\n arc.add(\"dir/../afile\")\n arc.add(\"link1\", hardlink_to='dir/../afile')\n arc.add(\"link2\", hardlink_to='dir/../dir/../afile')\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter) as cc:\n self.expect_file(\"dir/\")\n self.expect_file(\"afile\")\n self.expect_file(\"link1\")\n self.expect_file(\"link2\")\n\n def test_modes(self):\n # Test how file modes are extracted\n # (Note that the modes are ignored on platforms without working chmod)\n with ArchiveMaker() as arc:\n arc.add('all_bits', mode='?rwsrwsrwt')\n arc.add('perm_bits', mode='?rwxrwxrwx')\n arc.add('exec_group_other', mode='?rw-rwxrwx')\n arc.add('read_group_only', mode='?---r-----')\n arc.add('no_bits', mode='?---------')\n arc.add('dir/', mode='?---rwsrwt')\n arc.add('dir_all_bits/', mode='?rwsrwsrwt')\n\n # On some systems, setting the uid, gid, and/or sticky bit is a no-ops.\n # Check which bits we can set, so we can compare tarfile machinery to\n # a simple chmod.\n tmp_filename = os.path.join(TEMPDIR, \"tmp.file\")\n with open(tmp_filename, 'w'):\n pass\n try:\n new_mode = (os.stat(tmp_filename).st_mode\n | stat.S_ISVTX | stat.S_ISGID | stat.S_ISUID)\n try:\n os.chmod(tmp_filename, new_mode)\n except OSError as exc:\n if exc.errno == getattr(errno, \"EFTYPE\", 0):\n # gh-108948: On FreeBSD, regular users cannot set\n # the sticky bit.\n self.skipTest(\"chmod() failed with EFTYPE: \"\n \"regular users cannot set sticky bit\")\n else:\n raise\n\n got_mode = os.stat(tmp_filename).st_mode\n _t_file = 't' if (got_mode & stat.S_ISVTX) else 'x'\n _suid_file = 's' if (got_mode & stat.S_ISUID) else 'x'\n _sgid_file = 's' if (got_mode & stat.S_ISGID) else 'x'\n finally:\n os.unlink(tmp_filename)\n\n os.mkdir(tmp_filename)\n new_mode = (os.stat(tmp_filename).st_mode\n | stat.S_ISVTX | stat.S_ISGID | stat.S_ISUID)\n os.chmod(tmp_filename, new_mode)\n got_mode = os.stat(tmp_filename).st_mode\n _t_dir = 't' if (got_mode & stat.S_ISVTX) else 'x'\n _suid_dir = 's' if (got_mode & stat.S_ISUID) else 'x'\n _sgid_dir = 's' if (got_mode & stat.S_ISGID) else 'x'\n os.rmdir(tmp_filename)\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('all_bits',\n mode=f'?rw{_suid_file}rw{_sgid_file}rw{_t_file}')\n self.expect_file('perm_bits', mode='?rwxrwxrwx')\n self.expect_file('exec_group_other', mode='?rw-rwxrwx')\n self.expect_file('read_group_only', mode='?---r-----')\n self.expect_file('no_bits', mode='?---------')\n self.expect_file('dir/', mode=f'?---rw{_sgid_dir}rw{_t_dir}')\n self.expect_file('dir_all_bits/',\n mode=f'?rw{_suid_dir}rw{_sgid_dir}rw{_t_dir}')\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_file('all_bits', mode='?rwxr-xr-x')\n self.expect_file('perm_bits', mode='?rwxr-xr-x')\n self.expect_file('exec_group_other', mode='?rw-r-xr-x')\n self.expect_file('read_group_only', mode='?---r-----')\n self.expect_file('no_bits', mode='?---------')\n self.expect_file('dir/', mode='?---r-xr-x')\n self.expect_file('dir_all_bits/', mode='?rwxr-xr-x')\n\n with self.check_context(arc.open(), 'data'):\n normal_dir_mode = stat.filemode(stat.S_IMODE(\n self.outerdir.stat().st_mode))\n self.expect_file('all_bits', mode='?rwxr-xr-x')\n self.expect_file('perm_bits', mode='?rwxr-xr-x')\n self.expect_file('exec_group_other', mode='?rw-r--r--')\n self.expect_file('read_group_only', mode='?rw-r-----')\n self.expect_file('no_bits', mode='?rw-------')\n self.expect_file('dir/', mode=normal_dir_mode)\n self.expect_file('dir_all_bits/', mode=normal_dir_mode)\n\n def test_pipe(self):\n # Test handling of a special file\n with ArchiveMaker() as arc:\n arc.add('foo', type=tarfile.FIFOTYPE)\n\n for filter in 'fully_trusted', 'tar':\n with self.check_context(arc.open(), filter):\n if hasattr(os, 'mkfifo'):\n self.expect_file('foo', type=tarfile.FIFOTYPE)\n else:\n # The pipe can't be extracted and is skipped.\n pass\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.SpecialFileError,\n \"'foo' is a special file\")\n\n def test_special_files(self):\n # Creating device files is tricky. Instead of attempting that let's\n # only check the filter result.\n for special_type in tarfile.FIFOTYPE, tarfile.CHRTYPE, tarfile.BLKTYPE:\n tarinfo = tarfile.TarInfo('foo')\n tarinfo.type = special_type\n trusted = tarfile.fully_trusted_filter(tarinfo, '')\n self.assertIs(trusted, tarinfo)\n tar = tarfile.tar_filter(tarinfo, '')\n self.assertEqual(tar.type, special_type)\n with self.assertRaises(tarfile.SpecialFileError) as cm:\n tarfile.data_filter(tarinfo, '')\n self.assertIsInstance(cm.exception.tarinfo, tarfile.TarInfo)\n self.assertEqual(cm.exception.tarinfo.name, 'foo')\n\n def test_fully_trusted_filter(self):\n # The 'fully_trusted' filter returns the original TarInfo objects.\n with tarfile.TarFile.open(tarname) as tar:\n for tarinfo in tar.getmembers():\n filtered = tarfile.fully_trusted_filter(tarinfo, '')\n self.assertIs(filtered, tarinfo)\n\n def test_tar_filter(self):\n # The 'tar' filter returns TarInfo objects with the same name/type.\n # (It can also fail for particularly \"evil\" input, but we don't have\n # that in the test archive.)\n with tarfile.TarFile.open(tarname, encoding=\"iso8859-1\") as tar:\n for tarinfo in tar.getmembers():\n try:\n filtered = tarfile.tar_filter(tarinfo, '')\n except UnicodeEncodeError:\n continue\n self.assertIs(filtered.name, tarinfo.name)\n self.assertIs(filtered.type, tarinfo.type)\n\n def test_data_filter(self):\n # The 'data' filter either raises, or returns TarInfo with the same\n # name/type.\n with tarfile.TarFile.open(tarname, encoding=\"iso8859-1\") as tar:\n for tarinfo in tar.getmembers():\n try:\n filtered = tarfile.data_filter(tarinfo, '')\n except (tarfile.FilterError, UnicodeEncodeError):\n continue\n self.assertIs(filtered.name, tarinfo.name)\n self.assertIs(filtered.type, tarinfo.type)\n\n @unittest.skipIf(sys.platform == 'win32', 'requires native bytes paths')\n def test_filter_unencodable(self):\n # Sanity check using a valid path.\n tarinfo = tarfile.TarInfo(os_helper.TESTFN)\n filtered = tarfile.tar_filter(tarinfo, '')\n self.assertIs(filtered.name, tarinfo.name)\n filtered = tarfile.data_filter(tarinfo, '')\n self.assertIs(filtered.name, tarinfo.name)\n\n tarinfo = tarfile.TarInfo('test\\x00')\n self.assertRaises(ValueError, tarfile.tar_filter, tarinfo, '')\n self.assertRaises(ValueError, tarfile.data_filter, tarinfo, '')\n tarinfo = tarfile.TarInfo('\\ud800')\n self.assertRaises(UnicodeEncodeError, tarfile.tar_filter, tarinfo, '')\n self.assertRaises(UnicodeEncodeError, tarfile.data_filter, tarinfo, '')\n\n @unittest.skipIf(sys.platform == 'win32', 'requires native bytes paths')\n def test_extract_unencodable(self):\n # Create a member with name \\xed\\xa0\\x80 which is UTF-8 encoded\n # lone surrogate \\ud800.\n with ArchiveMaker(encoding='ascii', errors='surrogateescape') as arc:\n arc.add('\\udced\\udca0\\udc80')\n with os_helper.temp_cwd() as tmp:\n tar = arc.open(encoding='utf-8', errors='surrogatepass',\n errorlevel=1)\n self.assertEqual(tar.getnames(), ['\\ud800'])\n with self.assertRaises(UnicodeEncodeError):\n tar.extractall()\n self.assertEqual(os.listdir(), [])\n\n tar = arc.open(encoding='utf-8', errors='surrogatepass',\n errorlevel=0, debug=1)\n with support.captured_stderr() as stderr:\n tar.extractall()\n self.assertEqual(os.listdir(), [])\n self.assertIn('tarfile: UnicodeEncodeError ', stderr.getvalue())\n\n def test_change_default_filter_on_instance(self):\n tar = tarfile.TarFile(tarname, 'r')\n def strict_filter(tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n tar.extraction_filter = strict_filter\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_on_class(self):\n def strict_filter(tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n tar = tarfile.TarFile(tarname, 'r')\n with support.swap_attr(tarfile.TarFile, 'extraction_filter',\n staticmethod(strict_filter)):\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_on_subclass(self):\n class TarSubclass(tarfile.TarFile):\n def extraction_filter(self, tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n\n tar = TarSubclass(tarname, 'r')\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_to_string(self):\n tar = tarfile.TarFile(tarname, 'r')\n tar.extraction_filter = 'data'\n with self.check_context(tar, None):\n self.expect_exception(TypeError)\n\n def test_custom_filter(self):\n def custom_filter(tarinfo, path):\n self.assertIs(path, self.destdir)\n if tarinfo.name == 'move_this':\n return tarinfo.replace(name='moved')\n if tarinfo.name == 'ignore_this':\n return None\n return tarinfo\n\n with ArchiveMaker() as arc:\n arc.add('move_this')\n arc.add('ignore_this')\n arc.add('keep')\n with self.check_context(arc.open(), custom_filter):\n self.expect_file('moved')\n self.expect_file('keep')\n\n def test_bad_filter_name(self):\n with ArchiveMaker() as arc:\n arc.add('foo')\n with self.check_context(arc.open(), 'bad filter name'):\n self.expect_exception(ValueError)\n\n def test_stateful_filter(self):\n # Stateful filters should be possible.\n # (This doesn't really test tarfile. Rather, it demonstrates\n # that third parties can implement a stateful filter.)\n class StatefulFilter:\n def __enter__(self):\n self.num_files_processed = 0\n return self\n\n def __call__(self, tarinfo, path):\n try:\n tarinfo = tarfile.data_filter(tarinfo, path)\n except tarfile.FilterError:\n return None\n self.num_files_processed += 1\n return tarinfo\n\n def __exit__(self, *exc_info):\n self.done = True\n\n with ArchiveMaker() as arc:\n arc.add('good')\n arc.add('bad', symlink_to='/')\n arc.add('good')\n with StatefulFilter() as custom_filter:\n with self.check_context(arc.open(), custom_filter):\n self.expect_file('good')\n self.assertEqual(custom_filter.num_files_processed, 2)\n self.assertEqual(custom_filter.done, True)\n\n def test_errorlevel(self):\n def extracterror_filter(tarinfo, path):\n raise tarfile.ExtractError('failed with ExtractError')\n def filtererror_filter(tarinfo, path):\n raise tarfile.FilterError('failed with FilterError')\n def oserror_filter(tarinfo, path):\n raise OSError('failed with OSError')\n def tarerror_filter(tarinfo, path):\n raise tarfile.TarError('failed with base TarError')\n def valueerror_filter(tarinfo, path):\n raise ValueError('failed with ValueError')\n\n with ArchiveMaker() as arc:\n arc.add('file')\n\n # If errorlevel is 0, errors affected by errorlevel are ignored\n\n with self.check_context(arc.open(errorlevel=0), extracterror_filter):\n pass\n\n with self.check_context(arc.open(errorlevel=0), filtererror_filter):\n pass\n\n with self.check_context(arc.open(errorlevel=0), oserror_filter):\n pass\n\n with self.check_context(arc.open(errorlevel=0), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=0), valueerror_filter):\n self.expect_exception(ValueError)\n\n # If 1, all fatal errors are raised\n\n with self.check_context(arc.open(errorlevel=1), extracterror_filter):\n pass\n\n with self.check_context(arc.open(errorlevel=1), filtererror_filter):\n self.expect_exception(tarfile.FilterError)\n\n with self.check_context(arc.open(errorlevel=1), oserror_filter):\n self.expect_exception(OSError)\n\n with self.check_context(arc.open(errorlevel=1), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=1), valueerror_filter):\n self.expect_exception(ValueError)\n\n # If 2, all non-fatal errors are raised as well.\n\n with self.check_context(arc.open(errorlevel=2), extracterror_filter):\n self.expect_exception(tarfile.ExtractError)\n\n with self.check_context(arc.open(errorlevel=2), filtererror_filter):\n self.expect_exception(tarfile.FilterError)\n\n with self.check_context(arc.open(errorlevel=2), oserror_filter):\n self.expect_exception(OSError)\n\n with self.check_context(arc.open(errorlevel=2), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=2), valueerror_filter):\n self.expect_exception(ValueError)\n\n # We only handle ExtractionError, FilterError & OSError specially.\n\n with self.check_context(arc.open(errorlevel='boo!'), filtererror_filter):\n self.expect_exception(TypeError) # errorlevel is not int\n","source":"cpython_tests","origin":"Lib/test/test_tarfile.py::TestExtractionFilters","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"tarfile-filter","pep":"706","introduced_in":"3.12","form":"modern","file":"tarfile-filter/modern_02.py","code":"import errno\nimport sys\nimport os\nimport io\nfrom hashlib import sha256\nfrom contextlib import contextmanager, ExitStack\nfrom random import Random\nimport pathlib\nimport shutil\nimport re\nimport warnings\nimport stat\nimport unittest\nimport unittest.mock\nimport tarfile\nfrom test import archiver_tests\nfrom test import support\nfrom test.support import os_helper\nfrom test.support import script_helper\nfrom test.support import warnings_helper\n\n\nclass NoneInfoExtractTests(ReadTest):\n # These mainly check that all kinds of members are extracted successfully\n # if some metadata is None.\n # Some of the methods do additional spot checks.\n\n # We also test that the default filters can deal with None.\n\n extraction_filter = None\n\n @classmethod\n def setUpClass(cls):\n tar = tarfile.open(tarname, mode='r', encoding=\"iso8859-1\")\n cls.control_dir = pathlib.Path(TEMPDIR) / \"extractall_ctrl\"\n tar.errorlevel = 0\n with ExitStack() as cm:\n if cls.extraction_filter is None:\n cm.enter_context(warnings.catch_warnings(\n action=\"ignore\", category=DeprecationWarning))\n tar.extractall(cls.control_dir, filter=cls.extraction_filter)\n tar.close()\n cls.control_paths = set(\n p.relative_to(cls.control_dir)\n for p in pathlib.Path(cls.control_dir).glob('**/*'))\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.control_dir)\n\n def check_files_present(self, directory):\n got_paths = set(\n p.relative_to(directory)\n for p in pathlib.Path(directory).glob('**/*'))\n if self.extraction_filter in (None, 'data'):\n # The 'data' filter is expected to reject special files\n for path in 'ustar/fifotype', 'ustar/blktype', 'ustar/chrtype':\n got_paths.discard(pathlib.Path(path))\n self.assertEqual(self.control_paths, got_paths)\n\n @contextmanager\n def extract_with_none(self, *attr_names):\n DIR = pathlib.Path(TEMPDIR) / \"extractall_none\"\n self.tar.errorlevel = 0\n for member in self.tar.getmembers():\n for attr_name in attr_names:\n setattr(member, attr_name, None)\n with os_helper.temp_dir(DIR):\n self.tar.extractall(DIR, filter='fully_trusted')\n self.check_files_present(DIR)\n yield DIR\n\n def test_extractall_none_mtime(self):\n # mtimes of extracted files should be later than 'now' -- the mtime\n # of a previously created directory.\n now = pathlib.Path(TEMPDIR).stat().st_mtime\n with self.extract_with_none('mtime') as DIR:\n for path in pathlib.Path(DIR).glob('**/*'):\n with self.subTest(path=path):\n try:\n mtime = path.stat().st_mtime\n except OSError:\n # Some systems can't stat symlinks, ignore those\n if not path.is_symlink():\n raise\n else:\n self.assertGreaterEqual(path.stat().st_mtime, now)\n\n def test_extractall_none_mode(self):\n # modes of directories and regular files should match the mode\n # of a \"normally\" created directory or regular file\n dir_mode = pathlib.Path(TEMPDIR).stat().st_mode\n regular_file = pathlib.Path(TEMPDIR) / 'regular_file'\n regular_file.write_text('')\n regular_file_mode = regular_file.stat().st_mode\n with self.extract_with_none('mode') as DIR:\n for path in pathlib.Path(DIR).glob('**/*'):\n with self.subTest(path=path):\n if path.is_dir():\n self.assertEqual(path.stat().st_mode, dir_mode)\n elif path.is_file():\n self.assertEqual(path.stat().st_mode,\n regular_file_mode)\n\n def test_extractall_none_uid(self):\n with self.extract_with_none('uid'):\n pass\n\n def test_extractall_none_gid(self):\n with self.extract_with_none('gid'):\n pass\n\n def test_extractall_none_uname(self):\n with self.extract_with_none('uname'):\n pass\n\n def test_extractall_none_gname(self):\n with self.extract_with_none('gname'):\n pass\n\n def test_extractall_none_ownership(self):\n with self.extract_with_none('uid', 'gid', 'uname', 'gname'):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_tarfile.py::NoneInfoExtractTests","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_01.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS\nfrom test.support.os_helper import EnvironmentVarGuard\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\n\n\nclass ZoneInfoCacheTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n def setUp(self):\n self.klass.clear_cache()\n super().setUp()\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @property\n def tzpath(self):\n return [self.zoneinfo_data.tzpath]\n\n def test_ephemeral_zones(self):\n self.assertIs(\n self.klass(\"America/Los_Angeles\"), self.klass(\"America/Los_Angeles\")\n )\n\n def test_strong_refs(self):\n tz0 = self.klass(\"Australia/Sydney\")\n tz1 = self.klass(\"Australia/Sydney\")\n\n self.assertIs(tz0, tz1)\n\n def test_no_cache(self):\n\n tz0 = self.klass(\"Europe/Lisbon\")\n tz1 = self.klass.no_cache(\"Europe/Lisbon\")\n\n self.assertIsNot(tz0, tz1)\n\n def test_cache_reset_tzpath(self):\n \"\"\"Test that the cache persists when tzpath has been changed.\n\n The PEP specifies that as long as a reference exists to one zone\n with a given key, the primary constructor must continue to return\n the same object.\n \"\"\"\n zi0 = self.klass(\"America/Los_Angeles\")\n with self.tzpath_context([]):\n zi1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIs(zi0, zi1)\n\n def test_clear_cache_explicit_none(self):\n la0 = self.klass(\"America/Los_Angeles\")\n self.klass.clear_cache(only_keys=None)\n la1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIsNot(la0, la1)\n\n def test_clear_cache_one_key(self):\n \"\"\"Tests that you can clear a single key from the cache.\"\"\"\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n\n self.klass.clear_cache(only_keys=[\"America/Los_Angeles\"])\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n\n self.assertIsNot(la0, la1)\n self.assertIs(dub0, dub1)\n\n def test_clear_cache_two_keys(self):\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n tok0 = self.klass(\"Asia/Tokyo\")\n\n self.klass.clear_cache(\n only_keys=[\"America/Los_Angeles\", \"Europe/Dublin\"]\n )\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n tok1 = self.klass(\"Asia/Tokyo\")\n\n self.assertIsNot(la0, la1)\n self.assertIsNot(dub0, dub1)\n self.assertIs(tok0, tok1)\n\n def test_clear_cache_refleak(self):\n class Stringy(str):\n allow_comparisons = True\n def __eq__(self, other):\n if not self.allow_comparisons:\n raise CustomError\n return super().__eq__(other)\n __hash__ = str.__hash__\n\n key = Stringy(\"America/Los_Angeles\")\n self.klass(key)\n key.allow_comparisons = False\n try:\n # Note: This is try/except rather than assertRaises because\n # there is no guarantee that the key is even still in the cache,\n # or that the key for the cache is the original `key` object.\n self.klass.clear_cache(only_keys=\"America/Los_Angeles\")\n except CustomError:\n pass\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ZoneInfoCacheTest","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_02.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS\nfrom test.support.os_helper import EnvironmentVarGuard\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\n\n\nclass TzPathTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n @staticmethod\n @contextlib.contextmanager\n def python_tzpath_context(value):\n with EnvironmentVarGuard() as env:\n env[\"PYTHONTZPATH\"] = value\n yield\n\n def test_env_variable(self):\n \"\"\"Tests that the environment variable works with reset_tzpath.\"\"\"\n new_paths = [\n (\"\", []),\n (f\"{DRIVE}/etc/zoneinfo\", [f\"{DRIVE}/etc/zoneinfo\"]),\n (f\"{DRIVE}/a/b/c{os.pathsep}{DRIVE}/d/e/f\", [f\"{DRIVE}/a/b/c\", f\"{DRIVE}/d/e/f\"]),\n ]\n\n for new_path_var, expected_result in new_paths:\n with self.python_tzpath_context(new_path_var):\n with self.subTest(tzpath=new_path_var):\n self.module.reset_tzpath()\n tzpath = self.module.TZPATH\n self.assertSequenceEqual(tzpath, expected_result)\n\n def test_env_variable_relative_paths(self):\n test_cases = [\n [(\"path/to/somewhere\",), ()],\n [\n (f\"{DRIVE}/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (f\"{DRIVE}/usr/share/zoneinfo\",),\n ],\n [(\"../relative/path\",), ()],\n [\n (f\"{DRIVE}/usr/share/zoneinfo\", \"../relative/path\",),\n (f\"{DRIVE}/usr/share/zoneinfo\",),\n ],\n [(\"path/to/somewhere\", \"../relative/path\",), ()],\n [\n (\n f\"{DRIVE}/usr/share/zoneinfo\",\n \"path/to/somewhere\",\n \"../relative/path\",\n ),\n (f\"{DRIVE}/usr/share/zoneinfo\",),\n ],\n ]\n\n for input_paths, expected_paths in test_cases:\n path_var = os.pathsep.join(input_paths)\n with self.python_tzpath_context(path_var):\n with self.subTest(\"warning\", path_var=path_var):\n # Note: Per PEP 615 the warning is implementation-defined\n # behavior, other implementations need not warn.\n with self.assertWarns(self.module.InvalidTZPathWarning) as w:\n self.module.reset_tzpath()\n self.assertEqual(w.warnings[0].filename, __file__)\n\n tzpath = self.module.TZPATH\n with self.subTest(\"filtered\", path_var=path_var):\n self.assertSequenceEqual(tzpath, expected_paths)\n\n def test_env_variable_relative_paths_warning_location(self):\n path_var = \"path/to/somewhere\"\n\n with self.python_tzpath_context(path_var):\n with CleanImport(\"zoneinfo\", \"zoneinfo._tzpath\"):\n with self.assertWarns(RuntimeWarning) as w:\n import zoneinfo\n InvalidTZPathWarning = zoneinfo.InvalidTZPathWarning\n self.assertIsInstance(w.warnings[0].message, InvalidTZPathWarning)\n # It should represent the current file:\n self.assertEqual(w.warnings[0].filename, __file__)\n\n def test_reset_tzpath_kwarg(self):\n self.module.reset_tzpath(to=[f\"{DRIVE}/a/b/c\"])\n\n self.assertSequenceEqual(self.module.TZPATH, (f\"{DRIVE}/a/b/c\",))\n\n def test_reset_tzpath_relative_paths(self):\n bad_values = [\n (\"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"path/to/somewhere\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\", \"../relative/path\",),\n ]\n for input_paths in bad_values:\n with self.subTest(input_paths=input_paths):\n with self.assertRaises(ValueError):\n self.module.reset_tzpath(to=input_paths)\n\n def test_tzpath_type_error(self):\n bad_values = [\n \"/etc/zoneinfo:/usr/share/zoneinfo\",\n b\"/etc/zoneinfo:/usr/share/zoneinfo\",\n 0,\n ]\n\n for bad_value in bad_values:\n with self.subTest(value=bad_value):\n with self.assertRaises(TypeError):\n self.module.reset_tzpath(bad_value)\n\n def test_tzpath_attribute(self):\n tzpath_0 = [f\"{DRIVE}/one\", f\"{DRIVE}/two\"]\n tzpath_1 = [f\"{DRIVE}/three\"]\n\n with self.tzpath_context(tzpath_0):\n query_0 = self.module.TZPATH\n\n with self.tzpath_context(tzpath_1):\n query_1 = self.module.TZPATH\n\n self.assertSequenceEqual(tzpath_0, query_0)\n self.assertSequenceEqual(tzpath_1, query_1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TzPathTest","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_03.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS\nfrom test.support.os_helper import EnvironmentVarGuard\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\n\n\nclass TestModule(ZoneInfoTestBase):\n module = py_zoneinfo\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @cached_property\n def _UTC_bytes(self):\n zone_file = self.zoneinfo_data.path_from_key(\"UTC\")\n with open(zone_file, \"rb\") as f:\n return f.read()\n\n def touch_zone(self, key, tz_root):\n \"\"\"Creates a valid TZif file at key under the zoneinfo root tz_root.\n\n tz_root must exist, but all folders below that will be created.\n \"\"\"\n if not os.path.exists(tz_root):\n raise FileNotFoundError(f\"{tz_root} does not exist.\")\n\n root_dir, *tail = key.rsplit(\"/\", 1)\n if tail: # If there's no tail, then the first component isn't a dir\n os.makedirs(os.path.join(tz_root, root_dir), exist_ok=True)\n\n zonefile_path = os.path.join(tz_root, key)\n with open(zonefile_path, \"wb\") as f:\n f.write(self._UTC_bytes)\n\n def test_getattr_error(self):\n with self.assertRaises(AttributeError):\n self.module.NOATTRIBUTE\n\n def test_dir_contains_all(self):\n \"\"\"dir(self.module) should at least contain everything in __all__.\"\"\"\n module_all_set = set(self.module.__all__)\n module_dir_set = set(dir(self.module))\n\n difference = module_all_set - module_dir_set\n\n self.assertFalse(difference)\n\n def test_dir_unique(self):\n \"\"\"Test that there are no duplicates in dir(self.module)\"\"\"\n module_dir = dir(self.module)\n module_unique = set(module_dir)\n\n self.assertCountEqual(module_dir, module_unique)\n\n def test_available_timezones(self):\n with self.tzpath_context([self.zoneinfo_data.tzpath]):\n self.assertTrue(self.zoneinfo_data.keys) # Sanity check\n\n available_keys = self.module.available_timezones()\n zoneinfo_keys = set(self.zoneinfo_data.keys)\n\n # If tzdata is not present, zoneinfo_keys == available_keys,\n # otherwise it should be a subset.\n union = zoneinfo_keys & available_keys\n self.assertEqual(zoneinfo_keys, union)\n\n def test_available_timezones_weirdzone(self):\n with tempfile.TemporaryDirectory() as td:\n # Make a fictional zone at \"Mars/Olympus_Mons\"\n self.touch_zone(\"Mars/Olympus_Mons\", td)\n\n with self.tzpath_context([td]):\n available_keys = self.module.available_timezones()\n self.assertIn(\"Mars/Olympus_Mons\", available_keys)\n\n def test_folder_exclusions(self):\n expected = {\n \"America/Los_Angeles\",\n \"America/Santiago\",\n \"America/Indiana/Indianapolis\",\n \"UTC\",\n \"Europe/Paris\",\n \"Europe/London\",\n \"Asia/Tokyo\",\n \"Australia/Sydney\",\n }\n\n base_tree = list(expected)\n posix_tree = [f\"posix/{x}\" for x in base_tree]\n right_tree = [f\"right/{x}\" for x in base_tree]\n\n cases = [\n (\"base_tree\", base_tree),\n (\"base_and_posix\", base_tree + posix_tree),\n (\"base_and_right\", base_tree + right_tree),\n (\"all_trees\", base_tree + right_tree + posix_tree),\n ]\n\n with tempfile.TemporaryDirectory() as td:\n for case_name, tree in cases:\n tz_root = os.path.join(td, case_name)\n os.mkdir(tz_root)\n\n for key in tree:\n self.touch_zone(key, tz_root)\n\n with self.tzpath_context([tz_root]):\n with self.subTest(case_name):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n\n def test_exclude_posixrules(self):\n expected = {\n \"America/New_York\",\n \"Europe/London\",\n }\n\n tree = list(expected) + [\"posixrules\"]\n\n with tempfile.TemporaryDirectory() as td:\n for key in tree:\n self.touch_zone(key, td)\n\n with self.tzpath_context([td]):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TestModule","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.14","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_04.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS\nfrom test.support.os_helper import EnvironmentVarGuard\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\n\n\nclass ExtensionBuiltTest(unittest.TestCase):\n \"\"\"Smoke test to ensure that the C and Python extensions are both tested.\n\n Because the intention is for the Python and C versions of ZoneInfo to\n behave identically, these tests necessarily rely on implementation details,\n so the tests may need to be adjusted if the implementations change. Do not\n rely on these tests as an indication of stable properties of these classes.\n \"\"\"\n\n def test_cache_location(self):\n # The pure Python version stores caches on attributes, but the C\n # extension stores them in C globals (at least for now)\n self.assertNotHasAttr(c_zoneinfo.ZoneInfo, \"_weak_cache\")\n self.assertHasAttr(py_zoneinfo.ZoneInfo, \"_weak_cache\")\n\n def test_gc_tracked(self):\n import gc\n\n self.assertTrue(gc.is_tracked(py_zoneinfo.ZoneInfo))\n self.assertTrue(gc.is_tracked(c_zoneinfo.ZoneInfo))\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ExtensionBuiltTest","origin_revision":"v3.14.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_01.py","code":"from typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_02.py","code":"import typing\nx: typing.List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_03.py","code":"from typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: List[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"legacy","file":"builtin-generics/legacy_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> List[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_01.py","code":"from typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[from import of List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_02.py","code":"import typing\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[import of typing + typing.List]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_03.py","code":"from typing import List\nSomeAlias = list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_04.py","code":"from __future__ import annotations\nfrom typing import List\nx: list[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_05.py","code":"from __future__ import annotations\nfrom typing import List\ndef f(x: list[int]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_06.py","code":"from __future__ import annotations\nfrom typing import List\ndef f() -> list[int]: ...\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_01.py","code":"x = lambda foo: None","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[lambdas do not have type annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_02.py","code":"from __future__ import annotations\nfrom typing import List\nSomeAlias = List[int]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"unchanged","file":"builtin-generics/unchanged_03.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep585_test.py::test_fix_generic_types_noop[not a PEP 585 type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_01.py","code":"[x for a in b for x in a]","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[listcomp]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_02.py","code":"{x for a in b for x in a}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[setcomp]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_03.py","code":"(x for a in b for x in a)","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[genexp]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_04.py","code":"{k: v for a in b for k, v in a.items()}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[dictcomp]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_05.py","code":"[x for a in b for x in a.whatever()]","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[alternative loop variable list]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_06.py","code":"{k: v for a in b for k, v in a.whatever().items()}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[alternative loop variable dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_07.py","code":"print(x for a in b for x in a)","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[generator in a call]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_08.py","code":"[(x)for(a)in(b)for(x)in(a)]","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[evil list parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_09.py","code":"{(k):(v)for(a)in(b)for(k),(v)in(((a).items)())}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[evil dict parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_10.py","code":"{(k):(v)for(a)in(b)for(k),(v)in( ((a).items)())}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[evil dict parens 2]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_11.py","code":"import itertools\nitertools.chain.from_iterable(x)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[from_iterable]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_12.py","code":"import itertools\nitertools.chain(*x)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[chain, one star arg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_13.py","code":"import itertools\nitertools.chain( *x )","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[chain star with whitespace]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_14.py","code":"import itertools\nitertools.chain(*x, *y)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[chain, multiple starred]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_15.py","code":"import itertools\nitertools.chain(a, b, c)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[chain, multiple arguments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_16.py","code":"from itertools import chain\nchain.from_iterable(x)\n","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[from import]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_17.py","code":"import itertools\nitertools.chain(x)\n","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[single arg to iter]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"legacy","file":"comprehension-unpacking/legacy_18.py","code":"import itertools\nitertools.chain(\n x,\n # comment\n)\n","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[comment after single arg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_01.py","code":"[*a for a in b]","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[listcomp]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_02.py","code":"{*a for a in b}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[setcomp]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_03.py","code":"(*a for a in b)","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[genexp]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_04.py","code":"{**a for a in b}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[dictcomp]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_05.py","code":"[*a.whatever() for a in b]","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[alternative loop variable list]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_06.py","code":"{**a.whatever() for a in b}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[alternative loop variable dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_07.py","code":"print(*a for a in b)","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[generator in a call]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_08.py","code":"[*(a)for(a)in(b)]","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[evil list parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_09.py","code":"{**(a)for(a)in(b)}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[evil dict parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_10.py","code":"{**(a)for(a)in(b)}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_fix[evil dict parens 2]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_11.py","code":"(*it for it in x)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[from_iterable]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_12.py","code":"(*it for it in x)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[chain, one star arg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_13.py","code":"(*it for it in x)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[chain star with whitespace]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_14.py","code":"(*it for it in (*x, *y))","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[chain, multiple starred]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_15.py","code":"(*it for it in (a, b, c))","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[chain, multiple arguments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_16.py","code":"from itertools import chain\n(*it for it in x)\n","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[from import]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_17.py","code":"iter(x)\n","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[single arg to iter]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_18.py","code":"iter(x)\n","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_fix[comment after single arg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_01.py","code":"foo(x for x in y)","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_noop_before_315[this would chang behaviour: genexpr to args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_02.py","code":"[x for a in b for x in a if x % 2 == 0]","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_noop[not allowed when conditions occur list]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_03.py","code":"{k: v for a in b for k, v in a.items() if x % 2 == 0}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_noop[not allowed when conditions occur dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_04.py","code":"{k: v for a in b for k, v in a.items(1)}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_noop[unrelated items call args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_05.py","code":"{k: v for a in b for k, v in a.items(n=1)}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_noop[unrelated items call kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_06.py","code":"{k: v for a in b for k, v in a}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_noop[no items call]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_07.py","code":"{k: v for a in b for k, v in a.iteritems()}","source":"pyupgrade_tests","origin":"comprehension_splat_test.py::test_noop[not an items call]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_08.py","code":"import itertools\nitertools.chain.from_iterable(it=x)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_noop[from_iterable named argument]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_09.py","code":"import itertools\nitertools.chain.from_iterable(*x)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_noop[from_iterable starred argument]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"unchanged","file":"comprehension-unpacking/unchanged_10.py","code":"import itertools\nitertools.chain(it=x)","source":"pyupgrade_tests","origin":"itertools_chain_test.py::test_noop[chain named argument]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_01.py","code":"from __future__ import annotations\ndef foo(var: \"MyClass\") -> \"MyClass\":\n x: \"MyClass\"\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Simple annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_02.py","code":"from __future__ import annotations\nasync def foo(var: \"MyClass\") -> \"MyClass\":\n ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[simple async annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_03.py","code":"from __future__ import annotations\ndef foo(*, inplace: \"bool\"): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Kwonly, typed]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_04.py","code":"from __future__ import annotations\ndef foo(*args: \"str\", **kwargs: \"int\"): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Vararg and kwarg typed]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_05.py","code":"from __future__ import annotations\nfrom typing import Tuple\nx: Tuple[\"MyClass\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_06.py","code":"from __future__ import annotations\nfrom typing import Callable\nx: Callable[[\"MyClass\"], None]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[List within Callable]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_07.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nclass Foo(NamedTuple):\n x: \"MyClass\"\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Inherit from NamedTuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_08.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\", foo=\"int\", total=False)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict keyword syntax]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_09.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\", {\"foo\": \"int\"})\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict dict syntax]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_10.py","code":"from __future__ import annotations\nimport typing\nclass D(typing.TypedDict):\n E: typing.TypedDict(\"E\", {\"foo\": \"int\"})\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[typing.TypedDict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_11.py","code":"from __future__ import annotations\nfrom typing import Annotated\nx: Annotated[\"str\", \"metadata\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Annotated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_12.py","code":"from __future__ import annotations\nimport typing\nx: typing.Annotated[\"str\", \"metadata\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[typing.Annotated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_13.py","code":"from __future__ import annotations\nx: Arg(\"str\", \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Arg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_14.py","code":"from __future__ import annotations\nx: DefaultArg(\"str\", \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_15.py","code":"from __future__ import annotations\nx: NamedArg(\"str\", \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_16.py","code":"from __future__ import annotations\nx: DefaultNamedArg(\"str\", \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_17.py","code":"from __future__ import annotations\nx: DefaultNamedArg(\"str\", name=\"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with one keyword argument]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_18.py","code":"from __future__ import annotations\nx: DefaultNamedArg(name=\"name\", type=\"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with keyword arguments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_19.py","code":"from __future__ import annotations\nx: VarArg(\"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[VarArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_20.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[List[List[\"MyClass\"]]]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Nested]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_21.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", [(\"foo\", \"int\"), (\"bar\", \"str\")])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, no kwarg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_22.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", fields=[(\"foo\", \"int\"), (\"bar\", \"str\")])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, one kwarg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_23.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(typename=\"X\", fields=[(\"foo\", \"int\")])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, two kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_24.py","code":"from __future__ import annotations\ndef foo(var0, /, var1: \"MyClass\") -> \"MyClass\":\n x: \"MyClass\"\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[posonly args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_25.py","code":"from __future__ import annotations\nx: (\n \"int | \"\n \"str\"\n)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[multiline implicit-concat annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_26.py","code":"def f(x: \"X\") -> \"Y\": pass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fixes_in_py314","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"legacy","file":"deferred-annotations/legacy_27.py","code":"from __future__ import annotations\ndef f[T: \"int\"](t: T) -> T:\n return t\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_typevar_bound","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_01.py","code":"from __future__ import annotations\ndef foo(var: MyClass) -> MyClass:\n x: MyClass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Simple annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_02.py","code":"from __future__ import annotations\nasync def foo(var: MyClass) -> MyClass:\n ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[simple async annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_03.py","code":"from __future__ import annotations\ndef foo(*, inplace: bool): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Kwonly, typed]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_04.py","code":"from __future__ import annotations\ndef foo(*args: str, **kwargs: int): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Vararg and kwarg typed]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_05.py","code":"from __future__ import annotations\nfrom typing import Tuple\nx: Tuple[MyClass]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_06.py","code":"from __future__ import annotations\nfrom typing import Callable\nx: Callable[[MyClass], None]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[List within Callable]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_07.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nclass Foo(NamedTuple):\n x: MyClass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Inherit from NamedTuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_08.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\", foo=int, total=False)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict keyword syntax]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_09.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\", {\"foo\": int})\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict dict syntax]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_10.py","code":"from __future__ import annotations\nimport typing\nclass D(typing.TypedDict):\n E: typing.TypedDict(\"E\", {\"foo\": int})\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[typing.TypedDict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_11.py","code":"from __future__ import annotations\nfrom typing import Annotated\nx: Annotated[str, \"metadata\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Annotated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_12.py","code":"from __future__ import annotations\nimport typing\nx: typing.Annotated[str, \"metadata\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[typing.Annotated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_13.py","code":"from __future__ import annotations\nx: Arg(str, \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Arg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_14.py","code":"from __future__ import annotations\nx: DefaultArg(str, \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_15.py","code":"from __future__ import annotations\nx: NamedArg(str, \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_16.py","code":"from __future__ import annotations\nx: DefaultNamedArg(str, \"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_17.py","code":"from __future__ import annotations\nx: DefaultNamedArg(str, name=\"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with one keyword argument]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_18.py","code":"from __future__ import annotations\nx: DefaultNamedArg(name=\"name\", type=str)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with keyword arguments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_19.py","code":"from __future__ import annotations\nx: VarArg(str)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[VarArg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_20.py","code":"from __future__ import annotations\nfrom typing import List\nx: List[List[List[MyClass]]]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Nested]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_21.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", [(\"foo\", int), (\"bar\", str)])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, no kwarg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_22.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", fields=[(\"foo\", int), (\"bar\", str)])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, one kwarg]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_23.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(typename=\"X\", fields=[(\"foo\", int)])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with types, two kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_24.py","code":"from __future__ import annotations\ndef foo(var0, /, var1: MyClass) -> MyClass:\n x: MyClass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[posonly args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_25.py","code":"from __future__ import annotations\nx: (\n int | str\n)\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[multiline implicit-concat annotation]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_26.py","code":"def f(x: X) -> Y: pass\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fixes_in_py314","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"modern","file":"deferred-annotations/modern_27.py","code":"from __future__ import annotations\ndef f[T: int](t: T) -> T:\n return t\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_typevar_bound","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_01.py","code":"from typing import Literal\nx: \"str\"\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[missing __future__ import]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_02.py","code":"from __future__ import annotations\nfrom typing import Literal\nx: Literal[\"foo\", \"bar\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_03.py","code":"from __future__ import annotations\nfrom typing import TypeVar\nx = TypeVar(\"x\", \"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[TypeVar]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_04.py","code":"from __future__ import annotations\nfrom typing import cast\nx = cast(x, \"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[cast]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_05.py","code":"from __future__ import annotations\nfrom typing import List\nX = List[\"MyClass\"]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Alias]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_06.py","code":"from __future__ import annotations\nX: MyCallable(\"X\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Custom callable]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_07.py","code":"from __future__ import annotations\ndef foo(x, *args, **kwargs): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Untyped]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_08.py","code":"from __future__ import annotations\ndef foo(*, inplace): ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Kwonly, untyped]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_09.py","code":"from __future__ import annotations\nfrom typing import Annotated\nx: Annotated[1:2] = ...\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[Annotated with invalid slice]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_10.py","code":"from __future__ import annotations\ndef f[X](x: X) -> X: return x\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563_noop[TypeVar without bound]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_11.py","code":"from __future__ import annotations\nfrom typing import TypedDict\nclass D(TypedDict):\n E: TypedDict(\"E\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[TypedDict no type (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_12.py","code":"from __future__ import annotations\nfrom typing import Annotated\nx: Annotated[()]\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[Empty Annotated (garbage)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_13.py","code":"from __future__ import annotations\nx: DefaultNamedArg(name=\"name\", quox=\"str\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with invalid arguments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_14.py","code":"from __future__ import annotations\nx: DefaultNamedArg(name=\"name\")\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[DefaultNamedArg with no type (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_15.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", [(\"foo\",), (\"bar\",)])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with length-1 tuples (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_16.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple(\"X\", [\"foo\", \"bar\"])\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with missing types (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"deferred-annotations","pep":"649","introduced_in":"3.14","form":"unchanged","file":"deferred-annotations/unchanged_17.py","code":"from __future__ import annotations\nfrom typing import NamedTuple\nx: NamedTuple()\n","source":"pyupgrade_tests","origin":"typing_pep563_test.py::test_fix_typing_pep563[NamedTuple with no args (invalid syntax)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"legacy","file":"explicit-encoding/legacy_01.py","code":"open(\"foo\", encoding=\"utf-8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[simple case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"legacy","file":"explicit-encoding/legacy_02.py","code":"open(\"foo\", encoding=\"UTF8\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[alternative spelling]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"legacy","file":"explicit-encoding/legacy_03.py","code":"open(*args, encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"modern","file":"explicit-encoding/modern_01.py","code":"open(\"foo\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[simple case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"modern","file":"explicit-encoding/modern_02.py","code":"open(\"foo\")\n","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[alternative spelling]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"modern","file":"explicit-encoding/modern_03.py","code":"open(*args)","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_fix[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_01.py","code":"open(\"foo\", encoding=\"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop_before_315","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_02.py","code":"open(\"foo\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_03.py","code":"open(\"foo\", encoding=\"latin1\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"latin1\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_04.py","code":"open(\"foo\", encoding=\"us-ascii\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", encoding=\"us-ascii\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"explicit-encoding","pep":"597","introduced_in":"3.10","form":"unchanged","file":"explicit-encoding/unchanged_05.py","code":"open(\"foo\", \"r\", \"utf-8\")","source":"pyupgrade_tests","origin":"open_encoding_test.py::test_noop[open(\"foo\", \"r\", \"utf-8\")]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_01.py","code":"\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_02.py","code":"\"{1} {0}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_03.py","code":"\"{x.y}\".format(x=z)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_04.py","code":"\"{.x} {.y}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_05.py","code":"\"{} {}\".format(a.b, c.d)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_06.py","code":"\"{}\".format(a())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_07.py","code":"\"{}\".format(a.b())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_08.py","code":"\"{}\".format(a.b().c())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_09.py","code":"\"hello {}!\".format(name)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_10.py","code":"\"{}{{}}{}\".format(escaped, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_11.py","code":"\"{}{b}{}\".format(a, c, b=b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_12.py","code":"\"{}\".format(0x0)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_13.py","code":"\"\\N{snowman} {}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_14.py","code":"u\"foo{}\".format(1)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_15.py","code":"async def c(): return '{}'.format(await 1+foo())","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_16.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_17.py","code":"\"{x}\" \"{y}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"legacy","file":"fstring/legacy_18.py","code":"(\n \"{x}\"\n \"{y}\"\n).format(**locals())\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_01.py","code":"f\"{a} {b}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a, b)-f\"{a} {b}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_02.py","code":"f\"{b} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{1} {0}\".format(a, b)-f\"{b} {a}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_03.py","code":"f\"{z.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{x.y}\".format(x=z)-f\"{z.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_04.py","code":"f\"{a.x} {b.y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{.x} {.y}\".format(a, b)-f\"{a.x} {b.y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_05.py","code":"f\"{a.b} {c.d}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{} {}\".format(a.b, c.d)-f\"{a.b} {c.d}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_06.py","code":"f\"{a()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a())-f\"{a()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_07.py","code":"f\"{a.b()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b())-f\"{a.b()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_08.py","code":"f\"{a.b().c()}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(a.b().c())-f\"{a.b().c()}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_09.py","code":"f\"hello {name}!\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"hello {}!\".format(name)-f\"hello {name}!\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_10.py","code":"f\"{escaped}{{}}{y}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{{}}{}\".format(escaped, y)-f\"{escaped}{{}}{y}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_11.py","code":"f\"{a}{b}{c}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}{b}{}\".format(a, c, b=b)-f\"{a}{b}{c}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_12.py","code":"f\"{0x0}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[\"{}\".format(0x0)-f\"{0x0}\"]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_13.py","code":"f\"\\N{snowman} {a}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[named escape sequences]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_14.py","code":"f\"foo{1}\"","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings[u-prefixed format]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_15.py","code":"async def c(): return f'{await 1+foo()}'","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_await_py37","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_16.py","code":"f\"{x}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[normal case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_17.py","code":"f\"{x}\" f\"{y}\"","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"modern","file":"fstring/modern_18.py","code":"(\n f\"{x}\"\n f\"{y}\"\n)\n","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals[joined strings with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_01.py","code":"'{'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_02.py","code":"'}'.format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['}'.format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_03.py","code":"\"{}\" . format(x)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\" . format(x)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_04.py","code":"\"{}\".format(\n a,\n)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(\\n a,\\n)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_05.py","code":"\"{} {}\".format(*a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{} {}\".format(*a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_06.py","code":"\"{0} {0}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{0} {0}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_07.py","code":"\"{x} {x}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x} {x}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_08.py","code":"\"{x.y} {x.z}\".format(arg)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{x.y} {x.z}\".format(arg)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_09.py","code":"b\"{} {}\".format(a, b)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[b\"{} {}\".format(a, b)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_10.py","code":"\"{:{}}\".format(x, y)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{:{}}\".format(x, y)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_11.py","code":"\"{a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_12.py","code":"\"{a.a[b]}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a.a[b]}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_13.py","code":"\"{}{}\".format(a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}{}\".format(a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_14.py","code":"\"{a}{b}\".format(a=a)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{a}{b}\".format(a=a)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_15.py","code":"\"{}\".format(a['\\\\'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a['\\\\\\\\'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_16.py","code":"\"{}\".format(a[\"b\"])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[\"{}\".format(a[\"b\"])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_17.py","code":"'{}'.format(a['b'])","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop['{}'.format(a['b'])]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_18.py","code":"async def c(): return '{}'.format(await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_19.py","code":"async def c(): return '{}'.format(1 + await 3)","source":"pyupgrade_tests","origin":"fstrings_test.py::test_fix_fstrings_noop[async def c(): return '{}'.format(1 + await 3)]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_20.py","code":"\"{x}\".format(**locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[not 3.6+]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring","pep":"498","introduced_in":"3.6","form":"unchanged","file":"fstring/unchanged_21.py","code":"\"{x} {y}\".format(x, **locals())","source":"pyupgrade_tests","origin":"format_locals_test.py::test_fix_format_locals_noop[mixed locals() and params]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"legacy","file":"lazy-imports/legacy_01.py","code":"from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import LiteralString\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_fix[simple case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"legacy","file":"lazy-imports/legacy_02.py","code":"from typing_extensions import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import LiteralString\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_fix[via typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"legacy","file":"lazy-imports/legacy_03.py","code":"from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n import typing as T\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_fix[import-import]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"legacy","file":"lazy-imports/legacy_04.py","code":"if False:\n from typing import LiteralString\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_fix[old-style type checking block]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"modern","file":"lazy-imports/modern_01.py","code":"from typing import TYPE_CHECKING\nlazy from typing import LiteralString\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_fix[simple case]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"modern","file":"lazy-imports/modern_02.py","code":"from typing import TYPE_CHECKING\nlazy from typing import LiteralString\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_fix[via typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"modern","file":"lazy-imports/modern_03.py","code":"from typing import TYPE_CHECKING\nlazy import typing as T\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_fix[import-import]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"modern","file":"lazy-imports/modern_04.py","code":"lazy from typing import LiteralString\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_fix[old-style type checking block]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"unchanged","file":"lazy-imports/unchanged_01.py","code":"from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import Protocol\nelse:\n Protocol = object\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_noop[with else]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"unchanged","file":"lazy-imports/unchanged_02.py","code":"from typing import TYPE_CHECKING\nif TYPE_CHECKING:\n from typing import LiteralString\n class SomeClass: pass\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_noop[has other junk]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"unchanged","file":"lazy-imports/unchanged_03.py","code":"from typing import TYPE_CHECKING\ndef f():\n if TYPE_CHECKING:\n from typing import LiteralString\n","source":"pyupgrade_tests","origin":"type_checking_imports_test.py::test_noop[not at module scope]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"sentinel","pep":"661","introduced_in":"3.15","form":"legacy","file":"sentinel/legacy_01.py","code":"_MISSING = object()\n","source":"pyupgrade_tests","origin":"sentinel_test.py::test_fix","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"sentinel","pep":"661","introduced_in":"3.15","form":"modern","file":"sentinel/modern_01.py","code":"_MISSING = sentinel('_MISSING')\n","source":"pyupgrade_tests","origin":"sentinel_test.py::test_fix","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"sentinel","pep":"661","introduced_in":"3.15","form":"unchanged","file":"sentinel/unchanged_01.py","code":"if True:\n _MISSING = object()\n","source":"pyupgrade_tests","origin":"sentinel_test.py::test_noop[not directly at module scope]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"sentinel","pep":"661","introduced_in":"3.15","form":"unchanged","file":"sentinel/unchanged_02.py","code":"_MISSING = _MISSING2 = object()\n","source":"pyupgrade_tests","origin":"sentinel_test.py::test_noop[multi-assign]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"sentinel","pep":"661","introduced_in":"3.15","form":"unchanged","file":"sentinel/unchanged_03.py","code":"_MISSING = object(int)\n","source":"pyupgrade_tests","origin":"sentinel_test.py::test_noop[probably some other object idk]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_01.py","code":"if s.startswith(\"foo\"):\n s = s[len(\"foo\"):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_02.py","code":"if s.startswith(S):\n s = s[len(S):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_03.py","code":"if s.endswith(\"foo\"):\n s = s[:-1 * len(\"foo\")]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_04.py","code":"if s.endswith(S):\n s = s[:-1 * len(S)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_05.py","code":"if s.startswith(x):\n s = s[len(x):] # TODO: removeprefix\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_06.py","code":"if True:\n if s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_07.py","code":"if True:\n something_else()\n if s.startswith(x):\n s = s[len(x):]\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"legacy","file":"str-affix-removal/legacy_08.py","code":"if (\n x.startswith(y)\n):\n x = x[len(y):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_01.py","code":"s = s.removeprefix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_02.py","code":"s = s.removeprefix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removeprefix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_03.py","code":"s = s.removesuffix(\"foo\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_04.py","code":"s = s.removesuffix(S)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[removesuffix constant]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_05.py","code":"s = s.removeprefix(x)\n# after\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[with comment]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_06.py","code":"if True:\n s = s.removeprefix(x)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[allowed inside if]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_07.py","code":"if True:\n something_else()\n s = s.removeprefix(x)\n another_thing()\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[inside block with other statements]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"modern","file":"str-affix-removal/modern_08.py","code":"x = x.removeprefix(y)\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_fix[if with parens]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_01.py","code":"if x.startswith(S):\n x = x[len(S):]\nelif x.endswith(T):\n x = x[:-1 * len(T)]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop_before_39","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_02.py","code":"if s.startswith(\"a\"):\n s = s.lstrip(\"a\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[unrelated]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_03.py","code":"if s.startswith(x):\n s = s[2:]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[cannot prove x is 2]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_04.py","code":"if s.startswith(x):\n s = s[len(x):]\nelse:\n print(\"no!)\")\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has else]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"str-affix-removal","pep":"616","introduced_in":"3.9","form":"unchanged","file":"str-affix-removal/unchanged_05.py","code":"if something:\n print(\"something!\")\nelif s.startswith(x):\n s = s[len(x):]\n","source":"pyupgrade_tests","origin":"removeprefix_removesuffix_test.py::test_noop[has elif]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_01.py","code":"from __future__ import annotations\nfrom typing import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_02.py","code":"from __future__ import annotations\nfrom typing_extensions import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing_extensions.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_03.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_04.py","code":"from __future__ import annotations\nfrom collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_05.py","code":"from collections.abc import Generator\ndef f() -> Generator[int, None, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"legacy","file":"type-param-defaults/legacy_06.py","code":"from collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int, None]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_01.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_02.py","code":"from __future__ import annotations\nfrom typing_extensions import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[typing_extensions.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_03.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_04.py","code":"from __future__ import annotations\nfrom collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_future_annotations[collections.abc.AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_05.py","code":"from collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[Generator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_06.py","code":"from collections.abc import AsyncGenerator\nasync def f() -> AsyncGenerator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_with_3_13[AsyncGenerator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"unchanged","file":"type-param-defaults/unchanged_01.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_noop[already converted!]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"unchanged","file":"type-param-defaults/unchanged_02.py","code":"from __future__ import annotations\nfrom collections.abc import Generator\ndef f() -> Generator[int, int, None]: yield 1\ndef g() -> Generator[int, int, int]: yield 1\n","source":"pyupgrade_tests","origin":"typing_pep696_typevar_defaults_test.py::test_fix_pep696_noop[non-None send/return type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_01.py","code":"from typing import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_02.py","code":"import typing\nD = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": typing.Literal[\"b\", b\"c\"]})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_05.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a\": int}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {\n # first comment\n \"a\": int, # inline comment\n # second comment\n \"b\": str,\n # third comment\n}, total=False)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_07.py","code":"from typing_extensions import TypedDict\nD = TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_08.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int})\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_09.py","code":"import typing_extensions\nD = typing_extensions.TypedDict(\"D\", {\"a\": int}, total=True)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nFoo = TypedDict(\"Foo\", {\"lsts\": List[List[int]]})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_11.py","code":"import typing\nif True:\n if False:\n pass\n D = typing.TypedDict(\"D\", a=int)\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"legacy","file":"typed-dict/legacy_12.py","code":"from typing import TypedDict\nFoo = TypedDict(\"Foo\", {\"union\": str | int | None})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_01.py","code":"from typing import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from imported]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_02.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from attribute]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_03.py","code":"import typing\nclass D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_04.py","code":"import typing\nclass D(typing.TypedDict):\n a: typing.Literal['b', b'c']\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[with Literal of bytes]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_05.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[TypedDict from dict literal with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_06.py","code":"import typing\nclass D(typing.TypedDict, total=False):\n # first comment\n a: int # inline comment\n # second comment\n b: str\n # third comment\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[preserves comments]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_07.py","code":"from typing_extensions import TypedDict\nclass D(TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_08.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[dict TypedDict from typing_extensions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_09.py","code":"import typing_extensions\nclass D(typing_extensions.TypedDict, total=True):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[keyword TypedDict from typing_extensions, with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_10.py","code":"from typing import List\nfrom typing_extensions import TypedDict\nclass Foo(TypedDict):\n lsts: List[List[int]]","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[index unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_11.py","code":"import typing\nif True:\n if False:\n pass\n class D(typing.TypedDict):\n a: int\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[right after a dedent]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_12.py","code":"from typing import TypedDict\nclass Foo(TypedDict):\n union: str | int | None","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict[BitOr unparse error]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_01.py","code":"from wat import TypedDict\nQ = TypedDict(\"Q\")\n","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[from imported from elsewhere]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_02.py","code":"import typing\nD = typing.TypedDict(\"D\")","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_03.py","code":"import typing\nD = typing.TypedDict(\"D\", {})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[no typed args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_04.py","code":"import typing\nD = typing.TypedDict(\"D\", {}, a=int)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[both]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_05.py","code":"import typing\nD = typing.TypedDict(\"D\", 1)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[not a dict]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_06.py","code":"import typing\nD = typing.TypedDict(\"D\", {1: str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not a string]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_07.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"a-b\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is not an identifier]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_08.py","code":"import typing\nD = typing.TypedDict(\"D\", {\"class\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[key is a keyword]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_09.py","code":"import typing\nD = typing.TypedDict(\"D\", {**d, \"a\": str})","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[dictionary splat operator]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_10.py","code":"import typing\nC = typing.TypedDict(\"C\", *types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_11.py","code":"import typing\nD = typing.TypedDict(\"D\", **types)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[starstarkwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"unchanged","file":"typed-dict/unchanged_12.py","code":"import typing\nD = typing.TypedDict(\"D\", x=int, total=False)","source":"pyupgrade_tests","origin":"typing_classes_test.py::test_typing_typed_dict_noop[kw_typed_dict with total]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_01.py","code":"from typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_02.py","code":"import typing\nx: typing.Union[int]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_03.py","code":"import typing\nx: typing.Union[Foo[str, int], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_04.py","code":"import typing\nx: typing.Union[typing.List[str], str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_05.py","code":"import typing\nx: typing.Union[int, str,]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_06.py","code":"import typing\nx: typing.Union[(int, str)]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_07.py","code":"import typing\nx: typing.Union[\n int,\n str\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_08.py","code":"import typing\nx: typing.Union[\n int,\n str,\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_09.py","code":"from typing import Optional\nx: Optional[str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_10.py","code":"import typing\nx: typing.Optional[\n ComplicatedLongType[int]\n]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: Optional[\"str\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_12.py","code":"from typing import Union, Sequence\ndef f(x: Union[Union[A, B], Sequence[Union[C, D]]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_13.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_14.py","code":"from typing import Annotated, Union\nx: Union[str, Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_15.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x}(\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_16.py","code":"from typing import Annotated, Optional\nx: Optional[Annotated[int, f\"{x})\"]]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: Union[int, str]) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"legacy","file":"union-syntax/legacy_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> Union[int, str]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_01.py","code":"from typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_02.py","code":"x: int\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union of only one value]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_03.py","code":"x: Foo[str, int] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing a value with brackets]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_04.py","code":"x: list[str] | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union containing pep585 rewritten type]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_05.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union trailing comma]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_06.py","code":"x: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union, parenthesized tuple]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_07.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_08.py","code":"x: (\n int |\n str\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Union multiple lines with trailing commas]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_09.py","code":"from typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_10.py","code":"x: None | (\n ComplicatedLongType[int]\n)\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite multi-line]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_11.py","code":"from __future__ import annotations\nfrom typing import Optional\nx: str | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[Optional rewrite with forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_12.py","code":"from typing import Union\nfrom collections.abc import Sequence\ndef f(x: A | B | Sequence[C | D]): pass\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[nested unions]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_13.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x})\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_14.py","code":"from typing import Annotated, Union\nx: str | Annotated[int, f\"{x}(\"]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[union, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_15.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x}(\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore open brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_16.py","code":"from typing import Annotated, Optional\nx: Annotated[int, f\"{x})\"] | None\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types[optional, 3.12: ignore close brace in fstring]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_17.py","code":"from __future__ import annotations\nfrom typing import Union\nx: int | str\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[variable annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_18.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f(x: int | str) -> None: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[argument annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"modern","file":"union-syntax/modern_19.py","code":"from __future__ import annotations\nfrom typing import Union\ndef f() -> int | str: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_generic_types_future_annotations[return annotations]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_01.py","code":"from __future__ import annotations\nfrom typing import Union\nSomeAlias = Union[int, str]\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[<3.9 not in a type annotation context]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_02.py","code":"from typing import Union\ndef f() -> Union[()]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ empty Union]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_03.py","code":"from typing import Optional\ndef f() -> Optional[\"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Optional of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_04.py","code":"from typing import Union\ndef f() -> Union[int, \"str\"]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[3.10+ Union of forward reference]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"union-syntax","pep":"604","introduced_in":"3.10","form":"unchanged","file":"union-syntax/unchanged_05.py","code":"from typing import Union\ndef f() -> Union[1:2]: ...\n","source":"pyupgrade_tests","origin":"typing_pep604_test.py::test_fix_pep604_types_noop[invalid Union slicing]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack[Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[Unpack [Shape]]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"legacy","file":"variadic-generics/legacy_03.py","code":"from typing import Unpack\ndef f(*args: Unpack[tuple[int, ...]]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_01.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack[Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_02.py","code":"from typing import Generic, TypeVarTuple, Unpack\nShape = TypeVarTuple('Shape')\nclass C(Generic[*Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[Unpack [Shape]]):\\n pass-from typing import Generic, TypeVarTuple, Unpack\\nShape = TypeVarTuple('Shape')\\nclass C(Generic[*Shape]):\\n pass]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_03.py","code":"from typing import Unpack\ndef f(*args: *tuple[int, ...]): pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_typing_unpack[Unpack for *args]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_01.py","code":"from typing import Unpack\nfoo(Unpack())","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_02.py","code":"from typing import TypeVarTuple, Unpack\nShape = TypeVarTuple(\"Shape\")\nclass Foo(Unpack[Shape]):\n pass","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[Not inside a subscript]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_03.py","code":"from typing import Unpack\nfrom typing import TypedDict\nclass D(TypedDict):\n x: int\ndef f(**kwargs: Unpack[D]) -> None: pass\n","source":"pyupgrade_tests","origin":"typing_pep646_unpack_test.py::test_fix_pep646_noop[3.12 TypedDict for kwargs]","origin_revision":"9c75025","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_19.py","code":"# parse_options: {\"target-version\": \"3.14\"}\n[*x for x in y]\n{*x for x in y}\n{**x for x in y}\n(*x for x in y)\nf(*x for x in y)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/pep_798_unpacking_comprehensions_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_20.py","code":"# parse_options: {\"target-version\": \"3.14\"}\n[*x for x in y]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/starred_list_comp_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_21.py","code":"# parse_options: {\"target-version\": \"3.15\"}\n[*x for x in y]\n{*x for x in y}\n{**x for x in y}\n(*x for x in y)\nf(*x for x in y)\n[*x async for x in y]\n{*x async for x in y}\n{**x async for x in y}\n(*x async for x in y)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep_798_unpacking_comprehensions_py315.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"comprehension-unpacking","pep":"798","introduced_in":"3.15","form":"modern","file":"comprehension-unpacking/modern_22.py","code":"# parse_options: {\"target-version\": \"3.15\"}\n[*x for x in y]\n[*factor.dims for factor in bases]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/starred_list_comp_py315.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_01.py","code":"from contextvars import ContextVar\nfrom types import MappingProxyType\nimport re\nimport collections\nimport time\n\n# Okay\nContextVar(\"cv\")\nContextVar(\"cv\", default=())\nContextVar(\"cv\", default=(1, 2, 3))\nContextVar(\"cv\", default=\"foo\")\nContextVar(\"cv\", default=tuple())\nContextVar(\"cv\", default=frozenset())\nContextVar(\"cv\", default=MappingProxyType({}))\nContextVar(\"cv\", default=re.compile(\"foo\"))\nContextVar(\"cv\", default=float(1))\nContextVar(\"cv\", default=frozenset[str]())\nContextVar[frozenset[str]](\"cv\", default=frozenset[str]())\n\n# Bad\nContextVar(\"cv\", default=[])\nContextVar(\"cv\", default={})\nContextVar(\"cv\", default=list())\nContextVar(\"cv\", default=set())\nContextVar(\"cv\", default=dict())\nContextVar(\"cv\", default=[char for char in \"foo\"])\nContextVar(\"cv\", default={char for char in \"foo\"})\nContextVar(\"cv\", default={char: idx for idx, char in enumerate(\"foo\")})\nContextVar(\"cv\", default=collections.deque())\nContextVar(\"cv\", default=set[str]())\nContextVar[set[str]](\"cv\", default=set[str]())\n\ndef bar() -> list[int]:\n return [1, 2, 3]\n\nContextVar(\"cv\", default=bar())\nContextVar(\"cv\", default=time.time())\n\ndef baz(): ...\nContextVar(\"cv\", default=baz())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_02.py","code":"from contextvars import ContextVar\n\nfrom fastapi import Query\nContextVar(\"cv\", default=Query(None))\n\nfrom something_else import Depends\nContextVar(\"cv\", default=Depends())\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_bugbear/B039_extended.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_01.py","code":"import typing\nfrom dataclasses import dataclass, field\nfrom typing import ClassVar, Sequence\n\nKNOWINGLY_MUTABLE_DEFAULT = []\n\n\n@dataclass\nclass A:\n mutable_default: list[int] = []\n immutable_annotation: typing.Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: typing.ClassVar[list[int]] = []\n\n\n@dataclass\nclass B:\n mutable_default: list[int] = []\n immutable_annotation: Sequence[int] = []\n without_annotation = []\n correct_code: list[int] = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: list[int] = field(default_factory=list)\n class_variable: ClassVar[list[int]] = []\n\n# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n@dataclass\nclass AWithQuotes:\n mutable_default: 'list[int]' = []\n immutable_annotation: 'typing.Sequence[int]' = []\n without_annotation = []\n correct_code: 'list[int]' = KNOWINGLY_MUTABLE_DEFAULT\n perfectly_fine: 'list[int]' = field(default_factory=list)\n class_variable: 'typing.ClassVar[list[int]]'= []\n\n\n# Mutable defaults wrapped in field() calls\n@dataclass\nclass C:\n mutable_default: list[int] = field(default=[]) # RUF008\n mutable_default2: dict[str, int] = field(default={}) # RUF008\n mutable_default3: set[int] = field(default=set()) # RUF008\n mutable_default4: dict[str, int] = field(default=dict()) # RUF008\n correct_factory: list[int] = field(default_factory=list) # okay\n immutable_default: tuple[int, ...] = field(default=()) # okay\n immutable_default2: str = field(default=\"hello\") # okay\n immutable_default3: int = field(default=1) # okay\n non_mutable_var: list[int] = field(default=KNOWINGLY_MUTABLE_DEFAULT) # okay\n class_variable: ClassVar[list[int]] = field(default=[]) # okay\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_02.py","code":"# Lint should account for deferred annotations\n# See https://github.com/astral-sh/ruff/issues/15857\n\nfrom __future__ import annotations\n\nimport typing\nfrom dataclasses import dataclass\n\n\n@dataclass\nclass Example():\n \"\"\"Class that uses ClassVar.\"\"\"\n\n options: ClassVar[dict[str, str]] = {}\n\n\nif typing.TYPE_CHECKING:\n from typing import ClassVar\n\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF008_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_03.py","code":"import datetime\nimport re\nimport typing\nfrom dataclasses import dataclass, field\nfrom fractions import Fraction\nfrom pathlib import Path\nfrom typing import ClassVar, NamedTuple\n\n\ndef default_function() -> list[int]:\n return []\n\n\nclass ImmutableType(NamedTuple):\n something: int = 8\n\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\n fine_path: Path = Path()\n fine_date: datetime.date = datetime.date(2042, 1, 1)\n fine_timedelta: datetime.timedelta = datetime.timedelta(hours=7)\n fine_tuple: tuple[int] = tuple([1])\n fine_regex: re.Pattern = re.compile(r\".*\")\n fine_float: float = float(\"-inf\")\n fine_int: int = int(12)\n fine_complex: complex = complex(1, 2)\n fine_str: str = str(\"foo\")\n fine_bool: bool = bool(\"foo\")\n fine_fraction: Fraction = Fraction(1, 2)\n\n\nDEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES = ImmutableType(40)\nDEFAULT_A_FOR_ALL_DATACLASSES = A([1, 2, 3])\n\n\n@dataclass\nclass B:\n hidden_mutable_default: list[int] = default_function()\n another_dataclass: A = A()\n not_optimal: ImmutableType = ImmutableType(20)\n good_variant: ImmutableType = DEFAULT_IMMUTABLETYPE_FOR_ALL_DATACLASSES\n okay_variant: A = DEFAULT_A_FOR_ALL_DATACLASSES\n\n fine_dataclass_function: list[int] = field(default_factory=list)\n\n\nclass IntConversionDescriptor:\n def __init__(self, *, default):\n self._default = default\n\n def __set_name__(self, owner, name):\n self._name = \"_\" + name\n\n def __get__(self, obj, type):\n if obj is None:\n return self._default\n\n return getattr(obj, self._name, self._default)\n\n def __set__(self, obj, value):\n setattr(obj, self._name, int(value))\n\n\n@dataclass\nclass InventoryItem:\n quantity_on_hand: IntConversionDescriptor = IntConversionDescriptor(default=100)\n\n\n# Regression tests for:\n# https://github.com/astral-sh/ruff/issues/6447\nfrom typing import NewType\n\nListOfStrings = NewType(\"ListOfStrs\", list[str])\nStringsToInts = NewType(\"IntsToStrings\", dict[str, int])\n\nSpecialString = NewType(name=\"SpecialString\", tp=str)\nNegativeInteger = NewType(\"NegInt\", tp=int)\n\nInvalid1 = NewType(*Foo)\nInvalid2 = NewType(\"Invalid2\", name=Foo)\nInvalid3 = NewType(\"Invalid3\", name=Foo, lorem=\"ipsum\")\n\n@dataclass\nclass DataclassWithNewTypeFields:\n # Errors\n a: ListOfStrings = ListOfStrings([])\n b: StringsToInts = StringsToInts()\n c: Invalid1 = Invalid1()\n d: Invalid2 = Invalid2()\n e: Invalid3 = Invalid3()\n\n # No errors\n e: SpecialString = SpecialString(\"Lorem ipsum\")\n f: NegativeInteger = NegativeInteger(-110)\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/15772\ndef f() -> int:\n return 0\n\n@dataclass\nclass ShouldMatchB008RuleOfImmutableTypeAnnotationIgnored:\n this_is_not_fine: list[int] = default_function()\n # ignored\n this_is_fine: int = f()\n\n\n# Test for:\n# https://github.com/astral-sh/ruff/issues/17424\n@dataclass(frozen=True)\nclass C:\n foo: int = 1\n\n\n@dataclass\nclass D:\n c: C = C()\n\n\n@dataclass\nclass E:\n c: C = C()\n\n# https://github.com/astral-sh/ruff/issues/20266\n@dataclass(frozen=True)\nclass C:\n @dataclass(frozen=True)\n class D:\n foo: int = 1\n\n d: D = D() # OK","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_04.py","code":"from dataclasses import dataclass \nfrom typing import TYPE_CHECKING\n\n\ndef default_function() ->list[int]:\n return []\n\n@dataclass()\nclass A:\n hidden_mutable_default: list[int] = default_function()\n class_variable: typing.ClassVar[list[int]] = default_function()\n another_class_var: ClassVar[list[int]] = default_function()\n\nif TYPE_CHECKING:\n from typing import ClassVar\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF009_deferred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_05.py","code":"from dataclasses import InitVar, KW_ONLY, MISSING, dataclass, field\nfrom typing import ClassVar\n\n\n@dataclass\nclass C:\n # Errors\n no_annotation = r\"foo\"\n missing = MISSING\n field = field()\n\n # No errors\n __slots__ = (\"foo\", \"bar\")\n __radd__ = __add__\n _private_attr = 100\n\n with_annotation: str\n with_annotation_and_default: int = 42\n with_annotation_and_field_specifier: bytes = field()\n\n class_var_no_arguments: ClassVar = 42\n class_var_with_arguments: ClassVar[int] = 42\n\n init_var_no_arguments: InitVar = \"lorem\"\n init_var_with_arguments: InitVar[str] = \"ipsum\"\n\n kw_only: KW_ONLY\n tu, ple, [unp, ack, ing] = (0, 1, 2, [3, 4, 5])\n mul, [ti, ple] = (a, ssign), ment = {1: b\"3\", \"2\": 4}, [6j, 5]\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF045.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_06.py","code":"from dataclasses import dataclass\nfrom enum import Enum, Flag, IntEnum, IntFlag, StrEnum, ReprEnum\n\nimport attr\nimport attrs\n\n\n## Errors\n\n@dataclass\nclass E(Enum): ...\n\n\n@dataclass # Foobar\nclass E(Flag): ...\n\n\n@dataclass()\nclass E(IntEnum): ...\n\n\n@dataclass() # Foobar\nclass E(IntFlag): ...\n\n\n@dataclass(\n frozen=True\n)\nclass E(StrEnum): ...\n\n\n@dataclass( # Foobar\n frozen=True\n)\nclass E(ReprEnum): ...\n\n\n@dataclass(\n frozen=True\n) # Foobar\nclass E(Enum): ...\n\n\n## No errors\n\n@attrs.define\nclass E(Enum): ...\n\n\n@attrs.frozen\nclass E(Enum): ...\n\n\n@attrs.mutable\nclass E(Enum): ...\n\n\n@attr.s\nclass E(Enum): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/ruff/RUF049.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"except-without-parens","pep":"758","introduced_in":"3.14","form":"modern","file":"except-without-parens/modern_01.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntry:\n pass\nexcept x, y:\n pass\ntry:\n pass\nexcept* x, y:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/except_stmt_unparenthesized_tuple_no_as_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"except-without-parens","pep":"758","introduced_in":"3.14","form":"modern","file":"except-without-parens/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ntry:\n pass\nexcept x, y:\n pass\ntry:\n pass\nexcept* x, y:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/except_stmt_unparenthesized_tuple_no_as_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_01.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ntry: ...\nexcept* ValueError: ...\nexcept* KeyError: ...\nexcept * Error: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/except_star_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_02.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntry:\n pass\nexcept x, y:\n pass\ntry:\n pass\nexcept* x, y:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/except_stmt_unparenthesized_tuple_no_as_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_03.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ntry: ...\nexcept* ValueError: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/except_star_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"exception-groups","pep":"654","introduced_in":"3.11","form":"modern","file":"exception-groups/modern_04.py","code":"# parse_options: {\"target-version\": \"3.14\"}\ntry:\n pass\nexcept x, y:\n pass\ntry:\n pass\nexcept* x, y:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/except_stmt_unparenthesized_tuple_no_as_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_01.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf'Magic wand: { bag['wand'] }' # nested quotes\nf\"{'\\n'.join(a)}\" # escape sequence\nf'''A complex trick: {\n bag['bag'] # comment\n}'''\nf\"{f\"{f\"{f\"{f\"{f\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nf\"{f'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nf\"{\n 1\n}\"\nf\"test {a \\\n } more\" # line continuation\nf\"\"\"{f\"\"\"{x}\"\"\"}\"\"\" # mark the whole triple quote\nf\"{'\\n'.join(['\\t', '\\v', '\\r'])}\" # multiple escape sequences, multiple errors\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/pep701_f_string_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\n# nested interpolations also need to be checked\nf'{1: abcd \"{'aa'}\" }'\nf'{1: abcd \"{\"\\n\"}\" }'\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/pep701_nested_interpolation_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_03.py","code":"# parse_options: {\"target-version\": \"3.12\"}\nf'Magic wand: { bag['wand'] }' # nested quotes\nf\"{'\\n'.join(a)}\" # escape sequence\nf'''A complex trick: {\n bag['bag'] # comment\n}'''\nf\"{f\"{f\"{f\"{f\"{f\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nf\"{f'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nf\"{\n 1\n}\"\nf\"test {a \\\n } more\" # line continuation\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep701_f_string_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"modern","file":"fstring-grammar/modern_04.py","code":"# Empty f-strings\nf\"\"\nF\"\"\nf''\nf\"\"\"\"\"\"\nf''''''\n\nf\"{\" f\"}\"\nf\"{foo!s}\"\nf\"{3,}\"\nf\"{3!=4:}\"\nf'{3:{\"}\"}>10}'\nf'{3:{\"{\"}>10}'\nf\"{ foo = }\"\nf\"{ foo = :.3f }\"\nf\"{ foo = !s }\"\nf\"{ 1, 2 = }\"\nf'{f\"{3.1415=:.1f}\":*^20}'\n\n{\"foo \" f\"bar {x + y} \" \"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nf\"\\{foo}\\{bar:\\}\"\nf\"\\\\{{foo\\\\}}\"\nf\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nf\"{ ( foo ) = }\"\n\nf\"normal {foo} {{another}} {bar} {{{three}}}\"\nf\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nf\"normal {x:y + 2}\"\nf\"{x:{{1}.pop()}}\"\nf\"{(lambda x:{x})}\"\nf\"{x =}\"\nf\"{ x = }\"\nf\"{x=!a}\"\nf\"{x:.3f!r =}\"\nf\"{x = !r :.3f}\"\nf\"{x:.3f=!r}\"\n\"hello\" f\"{x}\"\nf\"{x}\" f\"{y}\"\nf\"{x}\" \"world\"\nf\"Invalid args in command: {command, *args}\"\n\"foo\" f\"{x}\" \"bar\"\n(\n f\"a\"\n F\"b\"\n \"c\"\n rf\"d\"\n fr\"e\"\n)\n\n# With unicode strings\nu\"foo\" f\"{bar}\" \"baz\" \" some\"\n\"foo\" f\"{bar}\" u\"baz\" \" some\"\n\"foo\" f\"{bar}\" \"baz\" u\" some\"\nu\"foo\" f\"bar {baz} really\" u\"bar\" \"no\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/f_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_01.py","code":"f\"hello {x:} world\"\nf\"hello {x:.3f} world\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/fstring_format_spec_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf\"{1:''}\" # but this is okay on all versions\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_nested_quote_in_format_spec_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"fstring-grammar","pep":"701","introduced_in":"3.12","form":"unchanged","file":"fstring-grammar/unchanged_03.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nf\"outer {'# not a comment'}\"\nf'outer {x:{\"# not a comment\"} }'\nf\"\"\"{f'''{f'{\"# not a comment\"}'}'''}\"\"\"\nf\"\"\"{f'''# before expression {f'# aro{f\"#{1+1}#\"}und #'}'''} # after expression\"\"\"\nf\"\"\"{\n 1\n}\"\"\"\nf\"escape outside of \\t {expr}\\n\"\nf\"test\\\"abcd\"\nf\"{1:\\x64}\" # escapes are valid in the format spec\nf\"{1:\\\"d\\\"}\" # this also means that escaped outer quotes are valid\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep701_f_string_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"modern","file":"lazy-imports/modern_05.py","code":"# parse_options: {\"target-version\": \"3.14\"}\nlazy import foo\nlazy from bar import baz\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/lazy_import_stmt_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"modern","file":"lazy-imports/modern_06.py","code":"# parse_options: {\"target-version\": \"3.15\"}\nlazy from . import basic2\nlazy from .basic2 import x, f\nlazy from . import b, x\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/lazy_import_relative_py315.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"modern","file":"lazy-imports/modern_07.py","code":"# parse_options: {\"target-version\": \"3.15\"}\nimport contextlib\nwith contextlib.nullcontext():\n lazy import os\nwith contextlib.nullcontext():\n lazy from sys import path\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/lazy_import_semantic_ok_py315.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"modern","file":"lazy-imports/modern_08.py","code":"# parse_options: {\"target-version\": \"3.15\"}\nlazy import foo\nlazy import foo as bar\nlazy from bar import baz\nlazy from sys import x as y\nlazy = 1\nimport foo as lazy\nfrom lazy import qux\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/lazy_import_stmt_py315.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"lazy-imports","pep":"810","introduced_in":"3.15","form":"unchanged","file":"lazy-imports/unchanged_04.py","code":"# parse_options: {\"target-version\": \"3.15\"}\nlazy\nimport os\n\nlazy # comment\nfrom sys import path\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/lazy_import_soft_keyword_split_py315.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_01.py","code":"import typing\nimport typing_extensions\nfrom typing import Literal\n\n# Shouldn't affect non-union field types.\nfield1: Literal[1] # OK\n\n# Should emit for duplicate field types.\nfield2: Literal[1] | Literal[2] # Error\n\n# Should emit for union types in arguments.\ndef func1(arg1: Literal[1] | Literal[2]): # Error\n print(arg1)\n\n\n# Should emit for unions in return types.\ndef func2() -> Literal[1] | Literal[2]: # Error\n return \"my Literal[1]ing\"\n\n\n# Should emit in longer unions, even if not directly adjacent.\nfield3: Literal[1] | Literal[2] | str # Error\nfield4: str | Literal[1] | Literal[2] # Error\nfield5: Literal[1] | str | Literal[2] # Error\nfield6: Literal[1] | bool | Literal[2] | str # Error\n\n# Should emit for non-type unions.\nfield7 = Literal[1] | Literal[2] # Error\n\n# Should emit for parenthesized unions.\nfield8: Literal[1] | (Literal[2] | str) # Error\n\n# Should handle user parentheses when fixing.\nfield9: Literal[1] | (Literal[2] | str) # Error\nfield10: (Literal[1] | str) | Literal[2] # Error\n\n# Should emit for union in generic parent type.\nfield11: dict[Literal[1] | Literal[2], str] # Error\n\n# Should emit for unions with more than two cases\nfield12: Literal[1] | Literal[2] | Literal[3] # Error\nfield13: Literal[1] | Literal[2] | Literal[3] | Literal[4] # Error\n\n# Should emit for unions with more than two cases, even if not directly adjacent\nfield14: Literal[1] | Literal[2] | str | Literal[3] # Error\n\n# Should emit for unions with mixed literal internal types\nfield15: Literal[1] | Literal[\"foo\"] | Literal[True] # Error\n\n# Shouldn't emit for duplicate field types with same value; covered by Y016\nfield16: Literal[1] | Literal[1] # OK\n\n# Shouldn't emit if in new parent type\nfield17: Literal[1] | dict[Literal[2], str] # OK\n\n# Shouldn't emit if not in a union parent\nfield18: dict[Literal[1], Literal[2]] # OK\n\n# Should respect name of literal type used\nfield19: typing.Literal[1] | typing.Literal[2] # Error\n\n# Should emit in cases with newlines\nfield20: typing.Union[\n Literal[\n 1 # test\n ],\n Literal[2],\n] # Error, newline and comment will not be emitted in message\n\n# Should handle multiple unions with multiple members\nfield21: Literal[1, 2] | Literal[3, 4] # Error\n\n# Should emit in cases with `typing.Union` instead of `|`\nfield22: typing.Union[Literal[1], Literal[2]] # Error\n\n# Should emit in cases with `typing_extensions.Literal`\nfield23: typing_extensions.Literal[1] | typing_extensions.Literal[2] # Error\n\n# Should emit in cases with nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], str]] # Error\n\n# Should emit in cases with mixed `typing.Union` and `|`\nfield25: typing.Union[Literal[1], Literal[2] | str] # Error\n\n# Should emit only once in cases with multiple nested `typing.Union`\nfield24: typing.Union[Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]]] # Error\n\n# Should use the first literal subscript attribute when fixing\nfield25: typing.Union[typing_extensions.Literal[1], typing.Union[Literal[2], typing.Union[Literal[3], Literal[4]]], str] # Error\n\nfrom typing import IO, Literal\n\nInlineOption = Literal[\"a\"] | Literal[\"b\"] | IO[str]\n\n# Should use unsafe fix when comments are deleted\nfield26: (\n # First comment\n Literal[\"a\", \"b\"]\n # Second comment\n | Literal[\"c\", \"d\"]\n)\nfield27: (\n Literal[\"a\", \"b\"] # First comment\n | Literal[\"c\", \"d\"] # Second comment\n)\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI030.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_02.py","code":"import typing\nfrom typing import Literal, TypeAlias, Union\n\nA: str | Literal[\"foo\"]\nB: TypeAlias = typing.Union[Literal[b\"bar\", b\"foo\"], bytes, str]\nC: TypeAlias = typing.Union[Literal[5], int, typing.Union[Literal[\"foo\"], str]]\nD: TypeAlias = typing.Union[Literal[b\"str_bytes\", 42], bytes, int]\nE: TypeAlias = typing.Union[typing.Union[typing.Union[typing.Union[Literal[\"foo\"], str]]]]\nF: TypeAlias = typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\nG: typing.Union[str, typing.Union[typing.Union[typing.Union[Literal[\"foo\"], int]]]]\n\ndef func(x: complex | Literal[1J], y: Union[Literal[3.14], float]): ...\n\n# OK\nA: Literal[\"foo\"]\nB: TypeAlias = Literal[b\"bar\", b\"foo\"]\nC: TypeAlias = typing.Union[Literal[5], Literal[\"foo\"]]\nD: TypeAlias = Literal[b\"str_bytes\", 42]\n\ndef func(x: Literal[1J], y: Literal[3.14]): ...\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI051.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_03.py","code":"from typing import Literal\nimport typing as t\nimport typing_extensions\n\nx: Literal[True, False, True, False] # PYI062 twice here\n\ny: Literal[1, print(\"hello\"), 3, Literal[4, 1]] # PYI062 on the last 1\n\nz: Literal[{1, 3, 5}, \"foobar\", {1,3,5}] # PYI062 on the set literal\n\nLiteral[1, Literal[1]] # once\nLiteral[1, 2, Literal[1, 2]] # twice\nLiteral[1, Literal[1], Literal[1]] # twice\nLiteral[1, Literal[2], Literal[2]] # once\nt.Literal[1, t.Literal[2, t.Literal[1]]] # once\ntyping_extensions.Literal[1, 1, 1] # twice\nLiteral[\n 1, # comment\n Literal[ # another comment\n 1\n ]\n] # once\n\n# Ensure issue is only raised once, even on nested literals\nMyType = Literal[\"foo\", Literal[True, False, True], \"bar\"] # PYI062\n\nn: Literal[\"No\", \"duplicates\", \"here\", 1, \"1\"]\n\n\n# nested literals, all equivalent to `Literal[1]`\nLiteral[Literal[1]] # no duplicate\nLiteral[Literal[Literal[1], Literal[1]]] # once\nLiteral[Literal[1], Literal[Literal[Literal[1]]]] # once\n","source":"ruff_tests","origin":"crates/ruff_linter/resources/test/fixtures/flake8_pyi/PYI062.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_01.py","code":"# parse_options: { \"target-version\": \"3.9\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/match_before_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\nmatch foo:\n case +1: ...\n case {+1: 2}: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unary_plus_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_03.py","code":"match 2:\n case Class(x=x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_keyword_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_04.py","code":"match x:\n case [a] | [a]: ...\n case (x, y) | (x, y): ...\n case (x, (y | y)): ...\n case [a, _] | [a, _]: ...\n case [a] | [C(a)]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/different_match_pattern_bindings.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_05.py","code":"match x:\n case {x.a: 1, x.a: 2}: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/duplicate_match_key_attr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_06.py","code":"match x:\n case 2: ...\n case var: ...\nmatch x:\n case 2: ...\n case _: ...\nmatch x:\n case var if True: ... # don't try to refute a guarded pattern\n case 2: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/irrefutable_case_pattern_at_end.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_07.py","code":"# parse_options: { \"target-version\": \"3.10\" }\nmatch 2:\n case 1:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_after_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_08.py","code":"match foo:\n case foo_bar: ...\nmatch foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_09.py","code":"match foo:\n case case: ...\nmatch foo:\n case match: ...\nmatch foo:\n case type: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_as_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_10.py","code":"match foo:\n case match.bar: ...\n case case.bar: ...\n case type.bar: ...\n case match.case.type.bar.type.case.match: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_attr_pattern_soft_keyword.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_11.py","code":"match foo:\n case _: ...\nmatch 1:\n case _: ...\nmatch 1.0:\n case _: ...\nmatch 1j:\n case _: ...\nmatch \"foo\":\n case _: ...\nmatch f\"foo {x}\":\n case _: ...\nmatch {1, 2}:\n case _: ...\nmatch ~foo:\n case _: ...\nmatch ...:\n case _: ...\nmatch not foo:\n case _: ...\nmatch await foo():\n case _: ...\nmatch lambda foo: foo:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_12.py","code":"match match:\n case _: ...\nmatch case:\n case _: ...\nmatch type:\n case _: ...\nmatch None:\n case _: ...\nmatch True:\n case _: ...\nmatch False:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_13.py","code":"match (1, 2) # Identifier\nmatch (1, 2): # Keyword\n case _: ...\nmatch [1:] # Identifier\nmatch [1, 2]: # Keyword\n case _: ...\nmatch * foo # Identifier\nmatch - foo # Identifier\nmatch -foo: # Keyword\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_keyword_or_identifier.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_14.py","code":"match subject:\n case [a, b]: ...\n case (a, b): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_parentheses_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_15.py","code":"match subject:\n case a if x: ...\n case a, b: ...\n case a, b if x: ...\n case a: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_sequence_pattern_terminator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_16.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_17.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_18.py","code":"match 2:\n case Class(x) | [x] | x: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/multiple_assignment_in_case_pattern.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_19.py","code":"match ruff:\n case {\"lint\": {\"select\": x} | {\"extend-select\": x}} | {\"select\": x}:\n ...\nmatch 42:\n case [[x] | [x]] | x: ...\nmatch 42:\n case [[x | x] | [x]] | x: ...\nmatch 42:\n case ast.Subscript(n, ast.Constant() | ast.Slice()) | ast.Attribute(n): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/nested_alternative_patterns.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_20.py","code":"# parse_options: {\"target-version\": \"3.15\"}\nmatch foo:\n case +1: ...\n # this is also now valid inside more complicated patterns\n case {+1: 2}: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unary_plus_py315.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_21.py","code":"# Unary addition isn't allowed before Python 3.15.\nmatch subject:\n case +1:\n pass\n case 1 | +2 | -3:\n pass\n case [1, +2, -3]:\n pass\n case Foo(x=+1, y=-2):\n pass\n case {True: +1, False: -2}:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/invalid/statements/match/unary_add_usage.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_22.py","code":"# Empty f-strings\nf\"\"\nF\"\"\nf''\nf\"\"\"\"\"\"\nf''''''\n\nf\"{\" f\"}\"\nf\"{foo!s}\"\nf\"{3,}\"\nf\"{3!=4:}\"\nf'{3:{\"}\"}>10}'\nf'{3:{\"{\"}>10}'\nf\"{ foo = }\"\nf\"{ foo = :.3f }\"\nf\"{ foo = !s }\"\nf\"{ 1, 2 = }\"\nf'{f\"{3.1415=:.1f}\":*^20}'\n\n{\"foo \" f\"bar {x + y} \" \"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nf\"\\{foo}\\{bar:\\}\"\nf\"\\\\{{foo\\\\}}\"\nf\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nf\"{ ( foo ) = }\"\n\nf\"normal {foo} {{another}} {bar} {{{three}}}\"\nf\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nf\"normal {x:y + 2}\"\nf\"{x:{{1}.pop()}}\"\nf\"{(lambda x:{x})}\"\nf\"{x =}\"\nf\"{ x = }\"\nf\"{x=!a}\"\nf\"{x:.3f!r =}\"\nf\"{x = !r :.3f}\"\nf\"{x:.3f=!r}\"\n\"hello\" f\"{x}\"\nf\"{x}\" f\"{y}\"\nf\"{x}\" \"world\"\nf\"Invalid args in command: {command, *args}\"\n\"foo\" f\"{x}\" \"bar\"\n(\n f\"a\"\n F\"b\"\n \"c\"\n rf\"d\"\n fr\"e\"\n)\n\n# With unicode strings\nu\"foo\" f\"{bar}\" \"baz\" \" some\"\n\"foo\" f\"{bar}\" u\"baz\" \" some\"\n\"foo\" f\"{bar}\" \"baz\" u\" some\"\nu\"foo\" f\"bar {baz} really\" u\"bar\" \"no\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/f_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_23.py","code":"# Empty t-strings\nt\"\"\nt\"\"\nt''\nt\"\"\"\"\"\"\nt''''''\n\nt\"{\" t\"}\"\nt\"{foo!s}\"\nt\"{3,}\"\nt\"{3!=4:}\"\nt'{3:{\"}\"}>10}'\nt'{3:{\"{\"}>10}'\nt\"{ foo = }\"\nt\"{ foo = :.3f }\"\nt\"{ foo = !s }\"\nt\"{ 1, 2 = }\"\nt'{t\"{3.1415=:.1f}\":*^20}'\n\n{t\"foo \" t\"bar {x + y} \" t\"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nt\"\\{foo}\\{bar:\\}\"\nt\"\\\\{{foo\\\\}}\"\nt\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nt\"{ ( foo ) = }\"\n\nt\"normal {foo} {{another}} {bar} {{{three}}}\"\nt\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nt\"normal {x:y + 2}\"\nt\"{x:{{1}.pop()}}\"\nt\"{(lambda x:{x})}\"\nt\"{x =}\"\nt\"{ x = }\"\nt\"{x=!a}\"\nt\"{x:.3f!r =}\"\nt\"{x = !r :.3f}\"\nt\"{x:.3f=!r}\"\nt\"hello\" t\"{x}\"\nt\"{x}\" t\"{y}\"\nt\"{x}\" t\"world\"\nt\"Invalid args in command: {command, *args}\"\nt\"foo\" t\"{x}\" t\"bar\"\n(\n t\"a\"\n t\"b\"\n t\"c\"\n rt\"d\"\n tr\"e\"\n)\n\n# Nesting\nt\"{f\"{t\"{this}\"}\"}\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/t_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"modern","file":"pattern-matching/modern_24.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_01.py","code":"match[0]: int\nmatch [x, y, z]: dict\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_annotated_assignment.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_02.py","code":"match not in case\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_1.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_03.py","code":"match\nmatch != foo\n(foo, match)\n[foo, match]\n{foo, match}\nmatch;\nmatch: int\nmatch,\nmatch.foo\nmatch / foo\nmatch << foo\nmatch and foo\nmatch is not foo\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_classify_as_identifier_2.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"pattern-matching","pep":"634","introduced_in":"3.10","form":"unchanged","file":"pattern-matching/unchanged_04.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_01.py","code":"# parse_options: {\"target-version\": \"3.8\"}\ndef foo(a, /): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pos_only_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_02.py","code":"lambda: a\nlambda: 1\nlambda x: 1\nlambda x, y: ...\nlambda a, b, c: 1\nlambda a, b=20, c=30: 1\nlambda x, y: x * y\nlambda y, z=1: z * y\nlambda *a: a\nlambda *a, z, x=0: ...\nlambda *, a, b, c: 1\nlambda *, a, b=20, c=30: 1\nlambda a, b, c, *, d, e: 0\nlambda **kwargs: f()\nlambda *args, **kwargs: f() + 1\nlambda *args, a, b=1, **kwargs: f() + 1\nlambda a, /: ...\nlambda a, /, b: ...\nlambda a=1, /,: ...\nlambda a, b, /, *, c: ...\nlambda kw=1, *, a: ...\nlambda a, b=20, /, c=30: 1\nlambda a, b, /, c, *, d, e: 0\nlambda a, b, /, c, *d, e, **f: 0","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/lambda.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"positional-only-params","pep":"570","introduced_in":"3.8","form":"modern","file":"positional-only-params/modern_03.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"template-strings","pep":"750","introduced_in":"3.14","form":"modern","file":"template-strings/modern_01.py","code":"# parse_options: {\"target-version\": \"3.13\"}\nt\"{hey}\"\nt'{there}'\nt\"\"\"what's\nhappening?\"\"\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/template_strings_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"template-strings","pep":"750","introduced_in":"3.14","form":"modern","file":"template-strings/modern_02.py","code":"# parse_options: {\"target-version\": \"3.14\"}\nt'Magic wand: { bag['wand'] }' # nested quotes\nt\"{'\\n'.join(a)}\" # escape sequence\nt'''A complex trick: {\n bag['bag'] # comment\n}'''\nt\"{t\"{t\"{t\"{t\"{t\"{1+1}\"}\"}\"}\"}\"}\" # arbitrary nesting\nt\"{t'''{\"nested\"} inner'''} outer\" # nested (triple) quotes\nt\"test {a \\\n } more\" # line continuation\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/pep750_t_string_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"template-strings","pep":"750","introduced_in":"3.14","form":"modern","file":"template-strings/modern_03.py","code":"# parse_options: {\"target-version\": \"3.14\"}\nt\"{hey}\"\nt'{there}'\nt\"\"\"what's\nhappening?\"\"\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/template_strings_py314.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"template-strings","pep":"750","introduced_in":"3.14","form":"modern","file":"template-strings/modern_04.py","code":"# Empty t-strings\nt\"\"\nt\"\"\nt''\nt\"\"\"\"\"\"\nt''''''\n\nt\"{\" t\"}\"\nt\"{foo!s}\"\nt\"{3,}\"\nt\"{3!=4:}\"\nt'{3:{\"}\"}>10}'\nt'{3:{\"{\"}>10}'\nt\"{ foo = }\"\nt\"{ foo = :.3f }\"\nt\"{ foo = !s }\"\nt\"{ 1, 2 = }\"\nt'{t\"{3.1415=:.1f}\":*^20}'\n\n{t\"foo \" t\"bar {x + y} \" t\"baz\": 10}\nmatch foo:\n case \"one\":\n pass\n case \"implicitly \" \"concatenated\":\n pass\n\nt\"\\{foo}\\{bar:\\}\"\nt\"\\\\{{foo\\\\}}\"\nt\"\"\"{\n foo:x\n y\n z\n}\"\"\"\nt\"{ ( foo ) = }\"\n\nt\"normal {foo} {{another}} {bar} {{{three}}}\"\nt\"normal {foo!a} {bar!s} {baz!r} {foobar}\"\nt\"normal {x:y + 2}\"\nt\"{x:{{1}.pop()}}\"\nt\"{(lambda x:{x})}\"\nt\"{x =}\"\nt\"{ x = }\"\nt\"{x=!a}\"\nt\"{x:.3f!r =}\"\nt\"{x = !r :.3f}\"\nt\"{x:.3f=!r}\"\nt\"hello\" t\"{x}\"\nt\"{x}\" t\"{y}\"\nt\"{x}\" t\"world\"\nt\"Invalid args in command: {command, *args}\"\nt\"foo\" t\"{x}\" t\"bar\"\n(\n t\"a\"\n t\"b\"\n t\"c\"\n rt\"d\"\n tr\"e\"\n)\n\n# Nesting\nt\"{f\"{t\"{this}\"}\"}\"\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/t_string.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_07.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\nclass D[S, T = int, U = uint](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_param_default_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_08.py","code":"type Alias[T] = list[T]\ndef f[T](t: T): ...\nclass C[T]: ...\nclass C[T, U, V]: ...\ntype Alias[T, U: str, V: (str, bytes), *Ts, **P, D = default] = ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_duplicate_type_parameter_names.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_09.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_default_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_10.py","code":"type X[**P] = int\ntype X[**P = int] = int\ntype X[T, **P] = int\ntype X[T, **P = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_param_spec.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_11.py","code":"type X[T] = int\ntype X[T = int] = int\ntype X[T: int = int] = int\ntype X[T: (int, int) = int] = int\ntype X[T: int = int, U: (int, int) = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_12.py","code":"type X[*Ts] = int\ntype X[*Ts = int] = int\ntype X[*Ts = *int] = int\ntype X[T, *Ts] = int\ntype X[T, *Ts = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var_tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_13.py","code":"class Test:\n ...\n\n\nclass Test():\n def __init__(self):\n pass\n\n\nclass Test(a=1, *A, **k):\n ...\n\n\nclass Test:\n def method():\n a, b = data\n\n\nclass Test(A, B):\n def __init__(self):\n pass\n\n def method_with_default(self, arg='default'):\n pass\n\n\n# Class with generic types:\n\n# TypeVar\nclass Test[T](): ...\n\n# TypeVar with default\nclass Test[T = str](): ...\n\n# TypeVar with bound\nclass Test[T: str](): ...\n\n# TypeVar with bound and default\nclass Test[T: int | str = int](): ...\n\n# TypeVar with tuple bound\nclass Test[T: (str, bytes)](): ...\n\n# Multiple TypeVar\nclass Test[T, U](): ...\n\n# Trailing comma\nclass Test[T, U,](): ...\n\n# TypeVarTuple\nclass Test[*Ts](): ...\n\n# TypeVarTuple with default\nclass Test[*Ts = Unpack[tuple[int, str]]](): ...\n\n# TypeVarTuple with starred default\nclass Test[*Ts = *tuple[int, str]](): ...\n\n# ParamSpec\nclass Test[**P](): ...\n\n# ParamSpec with default\nclass Test[**P = [int, str]](): ...\n\n# Mixed types\nclass Test[X, Y: str, *U, **P]():\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_14.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_01.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\nclass D[S, T = int, U = uint](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_param_default_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_02.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ntype x = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/type_stmt_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_03.py","code":"# parse_options: {\"target-version\": \"3.12\"}\nclass Foo[S: (str, bytes), T: float, *Ts, **P]: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/class_type_params_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_04.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ndef foo[T](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/function_type_params_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_05.py","code":"type Alias[T] = list[T]\ndef f[T](t: T): ...\nclass C[T]: ...\nclass C[T, U, V]: ...\ntype Alias[T, U: str, V: (str, bytes), *Ts, **P, D = default] = ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_duplicate_type_parameter_names.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_06.py","code":"return; import a; from x import y; z; type T = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/simple_stmts_with_semicolons.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_07.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ntype X[T = int] = int\ndef f[T = int](): ...\nclass C[T = int](): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_default_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_08.py","code":"type X[**P] = int\ntype X[**P = int] = int\ntype X[T, **P] = int\ntype X[T, **P = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_param_spec.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_09.py","code":"type X[T] = int\ntype X[T = int] = int\ntype X[T: int = int] = int\ntype X[T: (int, int) = int] = int\ntype X[T: int = int, U: (int, int) = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_10.py","code":"type X[*Ts] = int\ntype X[*Ts = int] = int\ntype X[*Ts = *int] = int\ntype X[T, *Ts] = int\ntype X[T, *Ts = int] = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_param_type_var_tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_11.py","code":"# parse_options: {\"target-version\": \"3.12\"}\ntype x = int\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/type_stmt_py312.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_12.py","code":"class Test:\n ...\n\n\nclass Test():\n def __init__(self):\n pass\n\n\nclass Test(a=1, *A, **k):\n ...\n\n\nclass Test:\n def method():\n a, b = data\n\n\nclass Test(A, B):\n def __init__(self):\n pass\n\n def method_with_default(self, arg='default'):\n pass\n\n\n# Class with generic types:\n\n# TypeVar\nclass Test[T](): ...\n\n# TypeVar with default\nclass Test[T = str](): ...\n\n# TypeVar with bound\nclass Test[T: str](): ...\n\n# TypeVar with bound and default\nclass Test[T: int | str = int](): ...\n\n# TypeVar with tuple bound\nclass Test[T: (str, bytes)](): ...\n\n# Multiple TypeVar\nclass Test[T, U](): ...\n\n# Trailing comma\nclass Test[T, U,](): ...\n\n# TypeVarTuple\nclass Test[*Ts](): ...\n\n# TypeVarTuple with default\nclass Test[*Ts = Unpack[tuple[int, str]]](): ...\n\n# TypeVarTuple with starred default\nclass Test[*Ts = *tuple[int, str]](): ...\n\n# ParamSpec\nclass Test[**P](): ...\n\n# ParamSpec with default\nclass Test[**P = [int, str]](): ...\n\n# Mixed types\nclass Test[X, Y: str, *U, **P]():\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_13.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_14.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"unchanged","file":"type-param-syntax/unchanged_01.py","code":"_\n(_)\n__\n__init__\nname\n(name)\n\n# Soft keywords used as name\nmatch\ncase\ntype\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/name.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/param_with_star_annotation_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_05.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_06.py","code":"def foo(*args: *int | str): ...\ndef foo(*args: *(int or str)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_07.py","code":"# parse_options: {\"target-version\": \"3.11\"}\ndef foo(*args: *Ts): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/param_with_star_annotation_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_08.py","code":"# parse_options: {\"target-version\": \"3.11\"}\nlst[*index] # simple index\nclass Array(Generic[DType, *Shape]): ... # motivating example from the PEP\nlst[a, *b, c] # different positions\nlst[a, b, *c] # different positions\nlst[*a, *b] # multiple unpacks\narray[3:5, *idxs] # mixed with slices\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/star_index_py311.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_09.py","code":"*a\n*(a + 1)\n*x.attr\n\narray_slice = array[0, *indexes, -1]\narray[0, *indexes, -1] = array_slice\narray[*indexes_to_select, *indexes_to_select]\narray[3:5, *indexes_to_select]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/starred.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_10.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_11.py","code":"def no_parameters():\n pass\n\n\ndef positional_parameters(a, b, c):\n pass\n\n\ndef positional_parameters_with_default_values(a, b=20, c=30):\n pass\n\n\ndef positional_parameters_with_default_values2(a, b=20, /, c=30):\n pass\n\n\ndef positional_only_and_positional_parameters(a, /, b, c):\n pass\n\n\ndef pos_args_with_defaults_and_varargs_and_kwargs(a, b=20, /, c=30, *args, **kwargs):\n pass\n\n\ndef keyword_only_parameters(*, a, b, c):\n pass\n\n\ndef keyword_only_parameters_with_defaults(*, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs(*args, a, b=20, c=30):\n pass\n\n\ndef kw_only_args_with_defaults_and_kwargs(*, a, b=20, c=30, **kwargs):\n pass\n\n\ndef kw_only_args_with_defaults_and_varargs_and_kwargs(*args, a, b=20, c=30, **kwargs):\n pass\n\n\ndef pos_and_kw_only_args(a, b, /, c, *, d, e, f):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults(a, b, /, c, *, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs(a, b, /, c, *args, d, e=20, f=30):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_kwargs(\n a, b, /, c, *, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef pos_and_kw_only_args_with_defaults_and_varargs_and_kwargs(\n a, b, /, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\ndef positional_and_keyword_parameters(a, b, c, *, d, e, f):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults(a, b, c, *, d, e=20, f=30):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs(\n a, b, c, *args, d, e=20, f=30\n):\n pass\n\n\ndef positional_and_keyword_parameters_with_defaults_and_varargs_and_kwargs(\n a, b, c, *args, d, e=20, f=30, **kwargs\n):\n pass\n\n\n# Function definitions with type parameters\n\n\ndef func[T](a: T) -> T:\n pass\n\n\ndef func[T: str](a: T) -> T:\n pass\n\n\ndef func[T: (str, bytes)](a: T) -> T:\n pass\n\n\ndef func[*Ts](*a: *Ts) -> Tuple[*Ts]:\n pass\n\n\ndef func[**P](*args: P.args, **kwargs: P.kwargs):\n pass\n\n\ndef func[T, U: str, *Ts, **P]():\n pass\n\n\ndef ellipsis(): ...\n\n\ndef multiple_statements() -> int:\n call()\n pass\n ...\n\n\ndef foo(*args):\n pass\n\n\ndef foo(**kwargs):\n pass\n\n\ndef foo(*args, **kwargs):\n pass\n\n\ndef foo(a, /):\n pass\n\n\ndef foo(a, /, b):\n pass\n\n\ndef foo(a=1, /,):\n pass\n\n\ndef foo(a, b, /, *, c):\n pass\n\n\ndef foo(kw=1, *, a):\n pass\n\n\ndef foo(x: int, y: \"str\", z: 1 + 2):\n pass\n\n\ndef foo(self, a=1, b=2, c=3):\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/function.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_12.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"unchanged","file":"variadic-generics/unchanged_04.py","code":"# parse_options: {\"target-version\": \"3.10\"}\nout[(*(slice(None) for _ in range(2)), *ind)] = 1\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_star_index_py310.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_01.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/decorator_named_expression_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_02.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_03.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_comp_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_04.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{x := 1, 2, 3}\n{1, x := 2, 3}\n{1, 2, x := 3}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/unparenthesized_named_expr_set_literal_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_05.py","code":"# parse_options: { \"target-version\": \"3.7\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/err/walrus_py37.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_06.py","code":"# parse_options: { \"target-version\": \"3.9\" }\n@buttons[0].clicked.connect\ndef spam(): ...\n@(x := lambda x: x)(foo)\ndef bar(): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/decorator_expression_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_07.py","code":"match x := 1:\n case _: ...\nmatch (x := 1):\n case _: ...\n# Starred expressions are only allowed in tuple expression\nmatch *x | y, z:\n case _: ...\nmatch await x:\n case _: ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_subject_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_08.py","code":"match x:\n case y if a := 1: ...\nmatch x:\n case y if a if True else b: ...\nmatch x:\n case y if lambda a: b: ...\nmatch x:\n case y if (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/match_stmt_valid_guard_expr.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_09.py","code":"[a := 0 for x in range(0)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/non_rebound_comprehension_variable.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_10.py","code":"# parse_options: {\"target-version\": \"3.8\"}\nlst[(x:=1)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_index_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_11.py","code":"# parse_options: {\"target-version\": \"3.8\"}\n{(x := 1), 2, 3}\n{(last := x) for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/parenthesized_named_expr_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_12.py","code":"# parse_options: {\"target-version\": \"3.9\"}\nlst[x:=1]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_index_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_13.py","code":"# parse_options: {\"target-version\": \"3.9\"}\n{x := 1, 2, 3}\n{last := x for x in range(3)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/unparenthesized_named_expr_py39.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_14.py","code":"class F(y := list): ...\ndef f():\n class G((yield 1)): ...\n class H((yield from 1)): ...\nasync def f():\n class G((await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_class.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_15.py","code":"# parse_options: {\"target-version\": \"3.13\"}\ndef f() -> (y := 3): ...\ndef g(arg: (x := 1)): ...\ndef outer():\n def i(x: (yield 1)): ...\n def k() -> (yield 1): ...\n def m(x: (yield from 1)): ...\n def o() -> (yield from 1): ...\nasync def outer():\n def f() -> (await 1): ...\n def g(arg: (await 1)): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_function_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_16.py","code":"# parse_options: {\"target-version\": \"3.13\"}\na: (x := 1)\ndef outer():\n b: (yield 1)\n c: (yield from 1)\nasync def outer():\n d: (await 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/valid_annotation_py313.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_17.py","code":"# parse_options: { \"target-version\": \"3.8\" }\n(x := 1)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/inline/ok/walrus_py38.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_18.py","code":"# This only tests the call arguments and not the expression before the opening parenthesis.\n\n# Simple\ncall()\ncall(x, y)\ncall(x, y,) # Trailing comma\ncall(x=1, y=2)\ncall(*x)\ncall(**x)\n\n# Order\ncall(x, y=1)\ncall(x, *y)\ncall(x, **y)\ncall(x=1, *y)\ncall(x=1, **y)\ncall(*x, **y)\ncall(*x, y, z)\ncall(**x, y=1, z=2)\ncall(*x1, *x2, **y1, **y2)\ncall(x=1, **y, z=1)\n\n# Keyword expression\ncall(x=1 if True else 2)\ncall(x=await y)\ncall(x=lambda y: y)\ncall(x=(y := 1))\n\n# Yield expression\ncall((yield x))\ncall((yield from x))\n\n# Named expression\ncall(x := 1)\ncall(x := 1 for i in iter)\n\n# Starred expressions\ncall(*x and y)\ncall(*x | y)\ncall(*await x)\ncall(*lambda x: x)\ncall(*x if True else y)\n\n# Double starred\ncall(**x)\ncall(**x and y)\ncall(**await x)\ncall(**x if True else y)\ncall(**(yield x))\ncall(**lambda x: x)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/arguments.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_19.py","code":"# Simple\n{}\n{1: 2}\n{1: 2, a: 1, b: 'hello'}\n\n# Mixed indentations\n{\n}\n{\n 1:\n 2,\n 3\n :4\n}\n\n# Nested\n{{1: 2}: {3: {4: 5}}}\n\n# Lambda expressions\n{lambda x: x: 1}\n{'A': lambda p: None, 'B': C,}\n\n# Named expressions\n{(x := 1): y}\n{(x := 1): (y := 2)}\n\n# Double star unpacking\n{**d}\n{a: b, **d}\n{**a, **b}\n{\"a\": \"b\", **c, \"d\": \"e\"}\n{1: 2, **{'nested': 'dict'}}\n{x * 1: y ** 2, **call()}\n# Here, `not` isn't allowed but parentheses resets the precedence\n{**(not x)}\n\n# Random expressions\n{1: x if True else y}\n{x if True else y: y for x in range(10) for y in range(10)}\n{{1, 2}: 3, x: {1: 2,},}\n{(x): (y), (z): (a)}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/dictionary.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_20.py","code":"(x for target in iter)\n(x async for target in iter)\n(x for target in iter if x in y if a and b if c)\n(x for target1 in iter1 if x and y for target2 in iter2 if a > b)\n(x for target1 in iter1 if x and y async for target2 in iter2 if a > b)\n\n# Named expression\n(x := y + 1 for y in z)\n\n# If expression\n(x if y else y for y in z)\n\n# Arguments\n\" \".join(\n sql\n for sql in (\n \"LIMIT %d\" % limit if limit else None,\n (\"OFFSET %d\" % offset) if offset else None,\n )\n)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/generator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_21.py","code":"# Simple lists\n[]\n[1]\n[1,]\n[1, 2, 3]\n[1, 2, 3,]\n\n# Mixed with indentations\n[\n]\n[\n 1\n]\n[\n 1,\n 2,\n]\n\n# Nested\n[[[1]]]\n[[1, 2], [3, 4]]\n\n# Named expression\n[x := 2]\n[x := 2,]\n[1, x := 2, 3]\n\n# Star expression\n[1, *x, 3]\n[1, *x | y, 3]\n\n# Random expressions\n[1 + 2, [1, 2, 3, 4], (a, b + c, d), {a, b, c}, {a: 1}, x := 2]\n[call1(call2(value.attr()) for element in iter)]\n[item in xs]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/list.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_22.py","code":"(name := 0)\n(name := (x * y))\n(name := 1 + 1)\n(name := (*x, y))\n(name := x if True else y)\n(name := lambda x: x)\n(name := (yield x))\n(name := (yield from x))","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/named.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_23.py","code":"(expr)\n(expr)()\n(expr)()()()\n\n(a and b or c)\n(lambda x: x)\n(x := 2)\n(yield x)\n(yield from x)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/parenthesized.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_24.py","code":"# Simple sets\n{}\n{1}\n{1,}\n{1, 2, 3}\n{1, 2, 3,}\n\n# Mixed with indentations\n{\n}\n{\n 1\n}\n{\n 1,\n 2,\n}\n\n# Nested\n{{1}}\n{{1, 2}, {3, 4}}\n\n# Named expression\n{x := 2}\n{1, x := 2, 3}\n{1, (x := 2),}\n\n# Star expression\n{1, *x, 3}\n{1, *x | y, 3}\n\n# Random expressions\n{1 + 2, (a, b), {1, 2, 3}, {a: b, **d}}\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/set.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_25.py","code":"# Various combinations\nx[:]\nx[1:]\nx[:2]\nx[1:2]\nx[::]\nx[1::]\nx[:2:]\nx[1:2:]\nx[::3]\nx[1::3]\nx[:2:3]\nx[1:2:3]\n\n# Named expression\nx[y := 2]\nx[(y := 2):]\nx[y := 2,]\n\n# These are two separate slice elements\nx[1,:2,]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/slice.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_26.py","code":"data[0][0]\ndata[0, 1]\ndata[0:,]\ndata[0:, 1]\ndata[0:1, 2]\ndata[0:1:2, 3, a:b + 1]\ndata[a := b]\ndata[:, :11]\ndata[1, 2, 3]\ndata[~flag]\ndata[(a := 0):]\ndata[(a := 0):y]\n\n# This is a single element tuple with a starred expression\ndata[*x]\ndata[*x and y]\ndata[*(x := y)]\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/subscript.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_27.py","code":"# With parentheses\n()\n(())\n((()), ())\n(a,)\n(a, b)\n(a, b,)\n((a, b))\n\n# Without parentheses\na,\na, b\na, b,\n\n# Starred expression\n*a,\na, *b\n*a | b, *await x, (), *()\n(*a,)\n(a, *b)\n(*a | b, *await x, (), *())\n\n# Named expression\n(x := 1,)\n(x, y := 2)\n(x, y := 2, z)\nx, (y := 2), z\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/tuple.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_28.py","code":"# Simple\n-1\n+1\n~1\nnot x\n\n# Multiple\n---1\n-+~1\nnot-+~1\nnot not x\n\n# Precedence check\n- await 1\n+ await 1 ** -2\n~(1, 2)\n-1 + 2\n\n# Precedence check for `not` operator because it is higher than other unary operators\nnot a and b or not c | d and not e\nnot (x := 1)\nnot a | (not b)\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/unary_op.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_29.py","code":"yield\nyield x\nyield x + 1\nyield x and y\nyield call()\nyield [1, 2]\nyield {3, 4}\nyield {x: 5}\nyield x, y\nyield (x, y)\nyield x == y\nyield (x := 1)\nyield x, *y\nyield *x,\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_30.py","code":"yield from x\nyield from x + 1\nyield from x and y\nyield from call()\nyield from [1, 2]\nyield from {3, 4}\nyield from {x: 5}\nyield from (x, y)\nyield from x == y\nyield from (x := 1)\nyield from (x, *x | y)","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/expressions/yield_from.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_31.py","code":"@function_decorator\ndef test():\n pass\n\n\n@class_decorator\nclass Test:\n pass\n\n\n@decorator\ndef f(): ...\n\n\n@a.b.c\ndef f(): ...\n\n\n@a\n@a.b.c\ndef f(): ...\n\n\n@a\n@1 | 2\n@a.b.c\nclass T: ...\n\n\n@x := 1\n@x if True else y\n@lambda x: x\n@x and y\n@(yield x)\n@(*x, *y)\ndef f(): ...\n\n\n# This is not multiple decorators on the same line but rather a binary (`@`) expression\n@x @y\ndef foo(): ...\n\n\n@x\n\n\n@y\n\n\ndef foo(): ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/other/decorator.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_32.py","code":"# These test cases specifically tests out parsing a list of with items that start with a\n# left parenthesis. This makes parsing ambiguous as to whether the left parenthesis is to\n# parenthesize the with items or part of a parenthesized expression. It's not to test the\n# with statement itself.\n\n# The following sections basically separates between which node does the\n# start parenthesis belongs to.\n\n# Parenthesized with items\n# ------------------------\n#\n# - The opening parenthesis belongs to the with statement.\n# - The range of the first with item shouldn't include the parenthesis.\nwith (item): ...\nwith (item,): ... # with a trailing comma\nwith (((item))): ...\nwith (item1, item2): ...\nwith (item1, item2,): ... # with a trailing comma\nwith ((item1), (item2), item3 as f, (item4)): ...\nwith ((item1, item2), item3): ...\nwith ((x, y) as f): ...\nwith (item1 as f1, item2 as f2): ...\nwith (item1 as f1, item2 as f2,): ... # with a trailing comma\nwith (item == 10,): ...\nwith ((item := 10)): ...\nwith ((item := 10,)): ...\nwith ((*item,)): ...\nwith ((item1 := 10), item2): ...\nwith (item1 as f, (item2 := 10)): ...\nwith (foo()): ...\nwith (foo(),): ...\nwith (foo() as f): ...\nwith (f\"{item := 42}\"): ...\nwith (f\"{(item := 42)}\"): ...\nwith ((x for x in range(10)), item): ...\nwith (item, (x for x in range(10))): ...\nwith (item, (x for x in range(10)), item): ...\nwith (data[1:2]): ...\nwith (data[1:2] as f): ...\nwith ((x for x in iter) as y): ...\n\n# Parenthesized expression\n# ------------------------\n#\n# - The opening parenthesis belongs to the context expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (item) as f: ...\nwith (item := 10): ...\nwith (item := 10) as f: ...\nwith ( item := 1 ): ...\nwith (item1 := 42), item2: ...\nwith (root + filename).read(): ... # Postfix expression\nwith (root + filename).read() as f: ... # Postfix expression\nwith (foo)(): ... # Postfix expression\nwith (foo)() as f: ... # Postfix expression\nwith (foo()) as f: ...\nwith (data[1:2]) as f: ...\nwith (1, 2, 3)[0]: ... # Postfix expression\nwith (1, 2, 3)[0] as f: ... # Postfix expression\nwith (item1), (item2): ...\nwith (open('a.py')), (open('b.py')): ...\nwith (yield x): ...\nwith ((yield x)): ...\nwith (yield from x): ...\nwith ((yield from x)): ...\nwith (yield x) as f: ...\nwith (yield x,) as f: ...\n\n\n# Tuple expression\n# ----------------\n#\n# - This is a sub-case of the parenthesized expression and requires transforming the list of\n# with items from the speculative parsing to a single with item containing a tuple expression.\n# - The opening parenthesis belongs to the tuple expression of the first with item.\n# - The range of the first with item should include the parenthesis.\nwith (): ...\nwith () as f: ...\nwith (item := 42,): ...\nwith (1, item := 2): ...\nwith (item1 := 10, item2): ...\nwith (item1, item2 := 2, item3) as f: ...\nwith (item,) as f: ...\nwith (*item,): ...\nwith (*item,) as f: ...\nwith (item1, item2) as f: ...\nwith (item1, item2,) as f: ...\nwith (item1, item2), item3: ...\nwith ((item1, item2), item3) as f: ...\nwith (item1,), item2, (item3, item4) as f: ...\nwith (item1, item2) as f1, item3 as f2: ...\nwith (item1, *item2): ...\nwith (item1, *item2) as f: ...\nwith (item1 := 10, *item2): ...\nwith ((item1 := 10), *item2): ...\n\n\n# Parenthesized generator expression\n# ----------------------------------\n#\n# - The opening parenthesis belongs to the generator expression\n# - The range of the with item should include the parenthesis\nwith (x for x in range(10)): ...\nwith (x async for x in range(10)): ...\nwith (x for x in range(10)), item: ...","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/ambiguous_lpar_with_items.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_33.py","code":"if 1: 10\nelif 2: 20\nelse: 30\n\nif True:\n 1\n ...\nif x < 1:\n ...\nelse:\n pass\n\nif a:\n pass\nelif b:\n ...\n\nif a and b:\n ...\nelif True:\n ...\nelif c:\n ...\nelif d:\n ...\nelse:\n f()\n\n# Valid test expression\nif a := b: ...\nelif a := b: ...\nif lambda x: x: ...\nelif lambda x: x: ...\nif await x: ...\nelif await x: ...\nif (yield x): ...\nelif (yield x): ...\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/if.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_34.py","code":"# Cases sampled from Lib/test/test_patma.py\n\n# case test_patma_098\nmatch x:\n case -0j:\n y = 0\n# case test_patma_142\nmatch x:\n case bytes(z):\n y = 0\n# case test_patma_073\nmatch x:\n case 0 if 0:\n y = 0\n case 0 if 1:\n y = 1\n# case test_patma_006\nmatch 3:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_049\nmatch x:\n case [0, 1] | [1, 0]:\n y = 0\n# case black_check_sequence_then_mapping\nmatch x:\n case [*_]:\n return \"seq\"\n case {}:\n return \"map\"\n# case test_patma_035\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | True} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_107\nmatch x:\n case 0.25 + 1.75j:\n y = 0\n# case test_patma_097\nmatch x:\n case -0j:\n y = 0\n# case test_patma_007\nmatch 4:\n case 0 | 1 | 2 | 3:\n x = True\n# case test_patma_154\nmatch x:\n case 0 if x:\n y = 0\n# case test_patma_134\nmatch x:\n case {1: 0}:\n y = 0\n case {0: 0}:\n y = 1\n case {**z}:\n y = 2\n# case test_patma_185\nmatch Seq():\n case [*_]:\n y = 0\n# case test_patma_063\nmatch x:\n case 1:\n y = 0\n case 1:\n y = 1\n# case test_patma_248\nmatch x:\n case {\"foo\": bar}:\n y = bar\n# case test_patma_019\nmatch (0, 1, 2):\n case [0, 1, *x, 2]:\n y = 0\n# case test_patma_052\nmatch x:\n case [0]:\n y = 0\n case [1, 0] if (x := x[:0]):\n y = 1\n case [1, 0]:\n y = 2\n# case test_patma_191\nmatch w:\n case [x, y, *_]:\n z = 0\n# case test_patma_110\nmatch x:\n case -0.25 - 1.75j:\n y = 0\n# case test_patma_151\nmatch (x,):\n case [y]:\n z = 0\n# case test_patma_114\nmatch x:\n case A.B.C.D:\n y = 0\n# case test_patma_232\nmatch x:\n case None:\n y = 0\n# case test_patma_058\nmatch x:\n case 0:\n y = 0\n# case test_patma_233\nmatch x:\n case False:\n y = 0\n# case test_patma_078\nmatch x:\n case []:\n y = 0\n case [\"\"]:\n y = 1\n case \"\":\n y = 2\n# case test_patma_156\nmatch x:\n case z:\n y = 0\n# case test_patma_189\nmatch w:\n case [x, y, *rest]:\n z = 0\n# case test_patma_042\nmatch x:\n case (0 as z) | (1 as z) | (2 as z) if z == x % 2:\n y = 0\n# case test_patma_034\nmatch x:\n case {0: [1, 2, {}]}:\n y = 0\n case {0: [1, 2, {}] | False} | {1: [[]]} | {0: [1, 2, {}]} | [] | \"X\" | {}:\n y = 1\n case []:\n y = 2\n# case test_patma_123\nmatch (0, 1, 2):\n case 0, *x:\n y = 0\n# case test_patma_126\nmatch (0, 1, 2):\n case *x, 2,:\n y = 0\n# case test_patma_151\nmatch x,:\n case y,:\n z = 0\n# case test_patma_152\nmatch w, x:\n case y, z:\n v = 0\n# case test_patma_153\nmatch w := x,:\n case y as v,:\n z = 0\n\nmatch x:\n # F-strings aren't allowed as patterns but it's a soft syntax error in Python.\n case f\"{y}\":\n pass\nmatch {\"test\": 1}:\n case {\n **rest,\n }:\n print(rest)\nmatch {\"label\": \"test\"}:\n case {\n \"label\": str() | None as label,\n }:\n print(label)\nmatch x:\n case [0, 1,]:\n y = 0\nmatch x:\n case (0, 1,):\n y = 0\nmatch x:\n case (0,):\n y = 0\nmatch x,:\n case z:\n pass\nmatch x, y:\n case z:\n pass\nmatch x, y,:\n case z:\n pass\n\n# PatternMatchSingleton\nmatch x:\n case None:\n ...\n case True:\n ...\n case False:\n ...\n\n# PatternMatchValue\nmatch x:\n case a.b:\n ...\n case a.b.c:\n ...\n case '':\n ...\n case b'':\n ...\n case 1:\n ...\n case 1.0:\n ...\n case 1.0J:\n ...\n case 1 + 1j:\n ...\n case -1:\n ...\n case -1.:\n ...\n case -0b01:\n ...\n case (1):\n ...\n\n# PatternMatchOr\nmatch x:\n case 1 | 2:\n ...\n case '' | 1.1 | -1 | 1 + 1j | a.b:\n ...\n\n# PatternMatchAs\nmatch x:\n case a:\n ...\nmatch x:\n case a as b:\n ...\nmatch x:\n case 1 | 2 as two:\n ...\n case 1 + 3j as sum:\n ...\n case a.b as ab:\n ...\n case _ as x:\n ...\nmatch x:\n case _:\n ...\n\n# PatternMatchSequence\nmatch x:\n case 1, 2, 3:\n ...\n case (1, 2, 3,):\n ...\n case (1 + 2j, a, None, a.b):\n ...\n case (1 as X, b) as S:\n ...\n case [1, 2, 3 + 1j]:\n ...\n case ([1,2], 3):\n ...\n case [1]:\n ...\n\n# PatternMatchStar\nmatch x:\n case *a,:\n ...\n case *_,:\n ...\n case [1, 2, *rest]:\n ...\n case (*_, 1, 2):\n ...\n\n# PatternMatchClass\nmatch x:\n case Point():\n ...\n case a.b.Point():\n ...\n case Point2D(x=0):\n ...\n case Point2D(x=0, y=0,):\n ...\n case Point2D(0, 1):\n ...\n case Point2D([0, 1], y=1):\n ...\n case Point2D(x=[0, 1], y=1):\n ...\n\n# PatternMatchMapping\nmatch x := b:\n case {1: _}:\n ...\n case {'': a, None: (1, 2), **rest}:\n ...\n\n# Pattern guard\nmatch y:\n case a if b := c: ...\n case e if 1 < 2: ...\n\n# `match` as an identifier\nmatch *a + b, c # ((match * a) + b), c\nmatch *(a + b), c # (match * (a + b)), c\nmatch (*a + b, c) # match ((*(a + b)), c)\nmatch -a * b + c # (match - (a * b)) + c\nmatch -(a * b) + c # (match - (a * b)) + c\nmatch (-a) * b + c # (match (-(a * b))) + c\nmatch ().a # (match()).a\nmatch (()).a # (match(())).a\nmatch ((),).a # (match(())).a\nmatch [a].b # (match[a]).b\nmatch [a,].b # (match[(a,)]).b (not (match[a]).b)\nmatch [(a,)].b # (match[(a,)]).b\nmatch()[a:\n b] # (match())[a: b]\nif match := 1: pass\nmatch match:\n case 1: pass\n case 2:\n pass\nmatch = lambda query: query == event\nprint(match(12))\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/match.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_35.py","code":"return\nreturn x\nreturn *x, *y\nreturn (x := 1)\nreturn None\nreturn x and y\nreturn 1 < 2\nreturn 1, 2,\nreturn call()\nreturn attr.value()\nreturn await x\nreturn lambda x: y\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/return.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_36.py","code":"type X = int\ntype X = int | str\ntype X = int | \"ForwardRefY\"\ntype X[T] = T | list[X[T]] # recursive\ntype X[T] = int\ntype X[T] = list[T] | set[T]\ntype X[T, *Ts, **P] = (T, Ts, P)\ntype X[T: int, *Ts, **P] = (T, Ts, P)\ntype X[T: (int, str), *Ts, **P] = (T, Ts, P)\ntype X[T = int] = T | str\ntype X[T: int | str = int] = T | int | str\ntype X[*Ts = *tuple[int, str]] = tuple[int, *Ts, str]\ntype X[**P = [int, str]] = Callable[P, str]\n\n# Soft keyword as alias name\ntype type = int\ntype match = int\ntype case = int\n\n# Soft keyword as value\ntype foo = type\ntype foo = match\ntype foo = case\n\n# Multine definitions\ntype \\\n\tX = int\ntype X \\\n\t= int\ntype X = \\\n\tint\ntype X = (\n int\n)\ntype \\\n X[T] = T\ntype X \\\n [T] = T\ntype X[T] \\\n = T\n\n# Simple statements\ntype X = int; type X = str; type X = type\nclass X: type X = int\n\ntype Point = tuple[float, float]\ntype Point[T] = tuple[T, T]\ntype IntFunc[**P] = Callable[P, int] # ParamSpec\ntype LabeledTuple[*Ts] = tuple[str, *Ts] # TypeVarTuple\ntype HashableSequence[T: Hashable] = Sequence[T] # TypeVar with bound\ntype IntOrStrSequence[T: (int, str)] = Sequence[T] # TypeVar with constraints\n\n# Type as an identifier\ntype *a + b, c # ((type * a) + b), c\ntype *(a + b), c # (type * (a + b)), c\ntype (*a + b, c) # type ((*(a + b)), c)\ntype -a * b + c # (type - (a * b)) + c\ntype -(a * b) + c # (type - (a * b)) + c\ntype (-a) * b + c # (type (-(a * b))) + c\ntype ().a # (type()).a\ntype (()).a # (type(())).a\ntype ((),).a # (type(())).a\ntype [a].b # (type[a]).b\ntype [a,].b # (type[(a,)]).b (not (type[a]).b)\ntype [(a,)].b # (type[(a,)]).b\ntype()[a:\n b] # (type())[a: b]\nif type := 1: pass\ntype = lambda query: query == event\nprint(type(12))\ntype(type)\na = (\n\ttype in C\n)\na = (\n\ttype(b)\n)\ntype (\n\tX = int\n)\ntype = 1\ntype = x = 1\nx = type = 1\nlambda x: type","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/type.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"walrus","pep":"572","introduced_in":"3.8","form":"modern","file":"walrus/modern_37.py","code":"while x:\n ...\n\nwhile (x > 1) and y:\n pass\nelse:\n ...\n\nwhile x and y:\n ...\n print('Hello World!')\n\nelse:\n print('Olá, Mundo!')\n ...\n\nwhile a := b: ...\nwhile (a := b) and c: ...\nwhile lambda x: x: ...\nwhile await x: ...\n\nif True:\n while x:\n pass\n else:\n pass\nelse:\n pass\n","source":"ruff_tests","origin":"crates/ruff_python_parser/resources/valid/statement/while.py","origin_revision":"d1e1b1f69b","license":"MIT"} {"cut":"val","version":"3.15","idiom_id":"annotated","pep":"593","introduced_in":"3.9","form":"modern","file":"annotated/modern_01.py","code":"\"\"\"\nTests the typing.Annotated special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#annotated\n\n# > The first argument to Annotated must be a valid type\n\nfrom dataclasses import InitVar, dataclass\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Literal,\n NotRequired,\n Required,\n TypeAlias,\n TypeVar,\n TypedDict,\n Union,\n)\n\nT = TypeVar(\"T\")\n\n\nGood1: Annotated[Union[int, str], \"\"]\nGood2: Annotated[int | None, \"\"]\nGood3: Annotated[list[int], \"\"]\nGood4: Annotated[Any, \"\"]\nGood5: Annotated[tuple[int, ...] | list[int], \"\"]\nGood6: Annotated[Callable[..., int], \"\"]\nGood7: Annotated[\"int | str\", \"\"]\nGood8: Annotated[list[\"int | str\"], \"\"]\n\n\nBad1: Annotated[[int, str], \"\"] # E: invalid type expression\nBad2: Annotated[((int, str),), \"\"] # E: invalid type expression\nBad3: Annotated[[int for i in range(1)], \"\"] # E: invalid type expression\nBad4: Annotated[{\"a\": \"b\"}, \"\"] # E: invalid type expression\nBad5: Annotated[(lambda: int)(), \"\"] # E: invalid type expression\nBad6: Annotated[[int][0], \"\"] # E: invalid type expression\nBad7: Annotated[int if 1 < 3 else str, \"\"] # E: invalid type expression\nBad8: Annotated[var1, \"\"] # E: invalid type expression\nBad9: Annotated[True, \"\"] # E: invalid type expression\nBad10: Annotated[1, \"\"] # E: invalid type expression\nBad11: Annotated[list or set, \"\"] # E: invalid type expression\nBad12: Annotated[f\"{'int'}\", \"\"] # E: invalid type expression\n\n\n# > Multiple type annotations are supported (Annotated supports variadic arguments):\n\nMulti1: Annotated[int | str, 3, \"\"]\nMulti2: Annotated[int | str, 3, \"\", lambda x: x, max(1, 2)]\n\n# > Annotated must be called with at least two arguments ( Annotated[int] is not valid)\n\nBad13: Annotated[int] # E: requires at least two arguments\n\n\n# > Annotated types can be nested\n\nNested1: list[Annotated[dict[str, Annotated[str, \"\"]], \"\"]]\nNested2: Annotated[list[Annotated[dict[str, Annotated[Literal[1, 2, 3], \"\"]], \"\"]], \"\"]\n\n\n# > Annotated is not type compatible with type or type[T]\nSmallInt: TypeAlias = Annotated[int, \"\"]\n\nnot_type1: type[Any] = Annotated[int, \"\"] # E\nnot_type2: type[Any] = SmallInt # E\n\n\ndef func4(x: type[T]) -> T:\n return x()\n\n\nfunc4(Annotated[str, \"\"]) # E\nfunc4(SmallInt) # E\n\n\n# > An attempt to call Annotated (whether parameterized or not) should be\n# > treated as a type error by type checkers.\n\nAnnotated() # E\nAnnotated[int, \"\"]() # E\nSmallInt(1) # E\n\n\nclass ClassA:\n a: ClassVar[Annotated[int, \"\"]] = 1\n b: Annotated[ClassVar[int], \"\"] = 1\n c: Final[Annotated[int, \"\"]] = 1\n d: Annotated[Final[int], \"\"] = 1\n\n\n@dataclass\nclass ClassB:\n a: InitVar[Annotated[int, \"\"]]\n b: Annotated[InitVar[int], \"\"]\n\n\nclass ClassC(TypedDict):\n a: Annotated[Required[int], \"\"]\n b: Required[Annotated[int, \"\"]]\n c: Annotated[NotRequired[int], \"\"]\n d: NotRequired[Annotated[int, \"\"]]\n\n\nTA1: TypeAlias = Annotated[int | str, \"\"]\nTA2 = Annotated[Literal[1, 2], \"\"]\nTA3 = Annotated[T, \"\"]\n","source":"typing_tests","origin":"conformance/tests/qualifiers_annotated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_07.py","code":"\"\"\"\nTests the handling of builtins.type[T].\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#type\n\n\nfrom typing import Any, Callable, Generic, Type, TypeAlias, TypeVar, assert_type\n\n\nclass User:\n ...\n\n\nclass BasicUser(User):\n ...\n\n\nclass ProUser(User):\n ...\n\n\nclass TeamUser(User):\n ...\n\n\ndef func1(user_class: type) -> User:\n return user_class()\n\n\ndef func2(user_class: type[User]) -> User:\n return user_class()\n\n\nU = TypeVar(\"U\", bound=User)\n\n\ndef func3(user_class: type[U]) -> U:\n return user_class()\n\n\nassert_type(func1(TeamUser), User)\nassert_type(func2(TeamUser), User)\nassert_type(func3(TeamUser), TeamUser)\n\n\n# > Note that it is legal to use a union of classes as the parameter for type[].\n\n\ndef func4(user_class: type[BasicUser | ProUser]) -> User:\n return user_class()\n\n\nassert_type(func4(BasicUser), User)\nassert_type(func4(ProUser), User)\nfunc4(TeamUser) # E\n\n\n# > Any other special constructs like Callable are not allowed as an argument to type.\n\nT = TypeVar(\"T\")\n\n\ndef func5(x: type[T]) -> None:\n pass\n\n\nfunc5(User) # OK\nfunc5(tuple) # OK\nfunc5(Callable) # E\n\n\n# > When type is parameterized it requires exactly one parameter. Plain type\n# > without brackets, the root of Python’s metaclass hierarchy, is equivalent to type[Any].\n\nbad_type1: type[int, str] # E\n\n\nclass MyMetaA(type):\n ...\n\n\ndef func6(a: type, b: type[Any]):\n assert_type(a, type[Any])\n a = b # OK\n b = a # OK\n a = type # OK\n b = type # OK\n\n\n# > Regarding the behavior of type[Any] (or type), accessing attributes of a\n# > variable with this type only provides attributes and methods defined by\n# > type (for example, __repr__() and __mro__). Such a variable can be called\n# > with arbitrary arguments, and the return type is Any.\n\n\ndef func7(a: type, b: type[Any], c: Type, d: Type[Any]):\n assert_type(a.__mro__, tuple[type, ...])\n assert_type(a.unknown, Any)\n assert_type(a.unknown(), Any)\n\n assert_type(b.__mro__, tuple[type, ...])\n assert_type(b.unknown, Any)\n assert_type(b.unknown(), Any)\n\n assert_type(c.__mro__, tuple[type, ...])\n assert_type(c.unknown, Any)\n assert_type(c.unknown(), Any)\n\n assert_type(d.__mro__, tuple[type, ...])\n assert_type(d.unknown, Any)\n assert_type(d.unknown(), Any)\n\n\ndef func8(a: type[object], b: Type[object]):\n assert_type(a.__name__, str)\n a.unknown # E\n\n assert_type(b.__name__, str)\n b.unknown # E\n\n\n# > type is covariant in its parameter, because type[Derived] is a subtype of type[Base]:\n\n\ndef func9(pro_user_class: type[ProUser]):\n assert_type(func3(pro_user_class), ProUser)\n\n\nTA1: TypeAlias = Type\nTA2: TypeAlias = Type[Any]\nTA3: TypeAlias = type\nTA4: TypeAlias = type[Any]\n\n\ndef func10(a: TA1, b: TA2, c: TA3, d: TA4):\n assert_type(a, type[Any])\n assert_type(b, type[Any])\n assert_type(c, type[Any])\n assert_type(d, type[Any])\n\n\nTA1.unknown # E\nTA2.unknown # E\nTA3.unknown # E\nTA4.unknown # E\n\nTA7: TypeAlias = type[T]\nTA8: TypeAlias = Type[T]\n\n\ndef func11(t1: TA7[T]) -> T:\n return t1()\n\n\ndef func12(t1: TA8[T]) -> T:\n return t1()\n\n\nassert_type(func11(int), int)\nassert_type(func12(int), int)\n\n\ndef func13(v: type):\n x1: Callable[..., Any] = v # OK\n x2: Callable[[int, int], int] = v # OK\n x3: object = v # OK\n x4: type = v # OK\n x5: type[int] = v # OK\n x6: type[Any] = v # OK\n\n\nclass ClassA(Generic[T]):\n def method1(self, v: type) -> type[T]:\n return v # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_type.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"builtin-generics","pep":"585","introduced_in":"3.9","form":"modern","file":"builtin-generics/modern_08.py","code":"\"\"\"\nTests the handling of builtins.tuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#tuple-type-form\n\n# > The type of a tuple can be expressed by listing the element types.\nfrom typing import Literal\n\n\nt1: tuple[int] = (1,) # OK\nt1 = (1, 2) # E\nt2: tuple[int, int] = (1, 2) # OK\nt2 = (1,) # E\nt2 = (1, \"\") # E\n\n\ndef func1() -> tuple[Literal[1], Literal[2]]:\n return (1, 2)\n\n\n# > The empty tuple can be typed as tuple[()].\n\nt10: tuple[()] = () # OK\nt10 = (1,) # E\n\n\ndef func2() -> list[tuple[()]]:\n return [(), (), ()]\n\n\n# > Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis.\nt20: tuple[int, ...] = () # OK\nt20 = (1,) # OK\nt20 = (1, 2, 3, 4) # OK\nt20 = (1, 2, 3, \"\") # E\n\n\nt30: tuple[int, ...] # OK\nt31: tuple[int, int, ...] # E\nt32: tuple[...] # E\nt33: tuple[..., int] # E\nt34: tuple[int, ..., int] # E\nt35: tuple[*tuple[str], ...] # E\nt36: tuple[*tuple[str, ...], ...] # E\n","source":"typing_tests","origin":"conformance/tests/tuples_type_form.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_01.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a base class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Generic, TypeVar, dataclass_transform\n\nT = TypeVar(\"T\")\n\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelBase:\n not_a_field: str\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n def __init__(self, not_a_field: str) -> None:\n self.not_a_field = not_a_field\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen dataclass cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass GenericModelBase(Generic[T]):\n not_a_field: T\n\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass GenericCustomer(GenericModelBase[int]):\n id: int = model_field()\n\n\ngc_1 = GenericCustomer(id=3)\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelBaseFrozen:\n not_a_field: str\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_02.py","code":"\"\"\"\nTests the dataclass_transform mechanism supports the \"converter\" parameter\nin a field specifier class.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#converters\n\nfrom typing import (\n Any,\n Callable,\n TypeVar,\n dataclass_transform,\n overload,\n)\n\nT = TypeVar(\"T\")\nS = TypeVar(\"S\")\n\n\ndef model_field(\n *,\n converter: Callable[[S], T],\n default: S | None = None,\n default_factory: Callable[[], S] | None = None,\n) -> T:\n raise NotImplementedError\n\n\n@dataclass_transform(field_specifiers=(model_field,))\nclass ModelBase:\n ...\n\n\n# > The converter must be a callable that must accept a single positional\n# > argument (but may accept other optional arguments, which are ignored for\n# > typing purposes).\n\n\ndef bad_converter1() -> int:\n return 0\n\n\ndef bad_converter2(*, x: int) -> int:\n return 0\n\n\nclass DC1(ModelBase):\n field1: int = model_field(converter=bad_converter1) # E\n field2: int = model_field(converter=bad_converter2) # E\n\n\n# > The type of the first positional parameter provides the type of the\n# > synthesized __init__ parameter for the field.\n\n# > The return type of the callable must be assignable to the field’s\n# > declared type.\n\n\ndef converter_simple(s: str) -> int:\n return int(s)\n\n\ndef converter_with_param_before_args(s: str, *args: int, **kwargs: int) -> int:\n return int(s)\n\n\ndef converter_with_args(*args: str) -> int:\n return int(args[0])\n\n\n@overload\ndef overloaded_converter(s: str) -> int:\n ...\n\n\n@overload\ndef overloaded_converter(s: list[str]) -> int:\n ...\n\n\ndef overloaded_converter(s: str | list[str], *args: str) -> int | str:\n return 0\n\n\nclass ConverterClass:\n @overload\n def __init__(self, val: str) -> None:\n ...\n\n @overload\n def __init__(self, val: bytes) -> None:\n ...\n\n def __init__(self, val: str | bytes) -> None:\n pass\n\n\nclass DC2(ModelBase):\n field0: int = model_field(converter=converter_simple)\n field1: int = model_field(converter=converter_with_param_before_args)\n field2: int = model_field(converter=converter_with_args)\n field3: ConverterClass = model_field(converter=ConverterClass)\n field4: int = model_field(converter=overloaded_converter)\n field5: dict[str, str] = model_field(converter=dict, default=())\n\n\nDC2(1, \"f1\", \"f2\", b\"f3\", []) # E\nDC2(\"f0\", \"f1\", \"f2\", 1, []) # E\nDC2(\"f0\", \"f1\", \"f2\", \"f3\", 3j) # E\n\n\ndc1 = DC2(\"f0\", \"f1\", \"f2\", b\"f6\", [])\n\ndc1.field0 = \"f1\"\ndc1.field3 = \"f6\"\ndc1.field3 = b\"f6\"\n\ndc1.field0 = 1 # E\ndc1.field3 = 1 # E\n\ndc2 = DC2(\"f0\", \"f1\", \"f2\", \"f6\", \"1\", ((\"a\", \"1\"), (\"b\", \"2\")))\n\n\n# > If default or default_factory are provided, the type of the default value\n# > should be assignable to the first positional parameter of the converter.\n\n\nclass DC3(ModelBase):\n field0: int = model_field(converter=converter_simple, default=\"\")\n field1: int = model_field(converter=converter_simple, default=1) # E\n\n field2: int = model_field(converter=converter_simple, default_factory=str)\n field3: int = model_field(converter=converter_simple, default_factory=int) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_converter.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_03.py","code":"\"\"\"\nTests the dataclass_transform mechanism honors implicit default values\nin field parameters.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#field-specifier-parameters\n\nfrom typing import Any, Callable, Literal, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n# > Field specifier functions can use overloads that implicitly specify the\n# > value of init using a literal bool value type (Literal[False] or Literal[True]).\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any],\n init: Literal[False] = False,\n) -> Any:\n ...\n\n\n@overload\ndef field1(\n *,\n default: str | None = None,\n resolver: None = None,\n init: Literal[True] = True,\n) -> Any:\n ...\n\n\ndef field1(\n *,\n default: str | None = None,\n resolver: Callable[[], Any] | None = None,\n init: bool = True,\n) -> Any:\n ...\n\n\ndef field2(*, init: bool = False, kw_only: bool = True) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(kw_only_default=True, field_specifiers=(field1, field2))\ndef create_model(*, init: bool = True) -> Callable[[type[T]], type[T]]:\n raise NotImplementedError\n\n\n@create_model()\nclass CustomerModel1:\n id: int = field1(resolver=lambda: 0)\n name: str = field1(default=\"Voldemort\")\n\n\nCustomerModel1()\nCustomerModel1(name=\"hi\")\n\n# This should generate an error because \"id\" is not\n# supposed to be part of the init function.\nCustomerModel1(id=1, name=\"hi\") # E\n\n\n@create_model()\nclass CustomerModel2:\n id: int = field2()\n name: str = field2(init=True)\n\n\n# This should generate an error because kw_only is True\n# by default for field2.\nCustomerModel2(1) # E\n\nCustomerModel2(name=\"Fred\")\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_field.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_04.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a decorator function.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\nfrom typing import Any, Callable, TypeVar, dataclass_transform, overload\n\nT = TypeVar(\"T\")\n\n\n@overload\n@dataclass_transform(kw_only_default=True, order_default=True)\ndef create_model(cls: T) -> T:\n ...\n\n\n@overload\ndef create_model(\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n) -> Callable[[T], T]:\n ...\n\n\ndef create_model(*args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n\n@create_model(kw_only=False, order=False)\nclass Customer1:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2:\n id: int\n name: str\n\n\n@create_model(frozen=True)\nclass Customer2Subclass(Customer2):\n salary: float\n\n\nc1_1 = Customer1(id=3, name=\"Sue\")\nc1_1.id = 4\n\nc1_2 = Customer1(3, \"Sue\")\nc1_2.name = \"Susan\"\n\n# This should generate an error because of a type mismatch.\nc1_2.name = 3 # E\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\n# This should generate an error because salary is not\n# a defined field.\nc1_3 = Customer1(id=3, name=\"Sue\", salary=40000) # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_2 = Customer2(0, \"John\") # E\n\nv2 = c2_1 < c2_2\n\n\n@dataclass_transform(kw_only_default=True, order_default=True, frozen_default=True)\ndef create_model_frozen(cls: T) -> T:\n raise NotImplementedError\n\n\n@create_model_frozen\nclass Customer3:\n id: int\n name: str\n\n\n# This should generate an error because a non-frozen class\n# cannot inherit from a frozen class.\n@create_model # E[Customer3Subclass]\nclass Customer3Subclass(Customer3): # E[Customer3Subclass]\n age: int\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_func.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclass-transform","pep":"681","introduced_in":"3.11","form":"modern","file":"dataclass-transform/modern_05.py","code":"\"\"\"\nTests the dataclass_transform mechanism when it is applied to a metaclass.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#the-dataclass-transform-decorator\n\n\nfrom typing import Any, dataclass_transform\n\nclass ModelField:\n def __init__(self, *, init: bool = True, default: Any | None = None) -> None:\n ...\n\n\ndef model_field(\n *, init: bool = True, default: Any | None = None, alias: str | None = None\n) -> Any:\n raise NotImplementedError\n\n\n@dataclass_transform(\n kw_only_default=True,\n field_specifiers=(ModelField, model_field),\n)\nclass ModelMeta(type):\n not_a_field: str\n\n def __init__(self, *args, **kwargs) -> None:\n self.not_a_field: str = \"not a field\"\n\n\nclass ModelBase(metaclass=ModelMeta):\n def __init_subclass__(\n cls,\n *,\n frozen: bool = False,\n kw_only: bool = True,\n order: bool = True,\n ) -> None:\n ...\n\n\nclass Customer1(ModelBase, frozen=True):\n id: int = model_field()\n name: str = model_field()\n name2: str = model_field(alias=\"other_name\", default=\"None\")\n\n\n# This should generate an error because a non-frozen class cannot\n# derive from a frozen one.\nclass Customer1Subclass(Customer1, frozen=False): # E\n salary: float = model_field()\n\n\nclass Customer2(ModelBase, order=True):\n id: int\n name: str = model_field(default=\"None\")\n\n\nc1_1 = Customer1(id=3, name=\"Sue\", other_name=\"Susan\")\n\n# This should generate an error because the class is frozen.\nc1_1.id = 4 # E\n\n# This should generate an error because the class is kw_only.\nc1_2 = Customer1(3, \"Sue\") # E\n\n# OK (other_name is optional).\nc1_3 = Customer1(id=3, name=\"John\")\n\n# This should generate an error because comparison methods are\n# not synthesized.\nv1 = c1_1 < c1_2 # E\n\nc2_1 = Customer2(id=0, name=\"John\")\n\nc2_2 = Customer2(id=1)\n\nv2 = c2_1 < c2_2\n\n# This should generate an error because Customer2 supports\n# keyword-only parameters for its constructor.\nc2_3 = Customer2(0, \"John\") # E\n\n\n@dataclass_transform(frozen_default=True)\nclass ModelMetaFrozen(type):\n pass\n\n\nclass ModelBaseFrozen(metaclass=ModelMetaFrozen):\n ...\n\n\nclass Customer3(ModelBaseFrozen):\n id: int\n name: str\n\n\nc3_1 = Customer3(id=2, name=\"hi\")\n\n# This should generate an error because Customer3 is frozen.\nc3_1.id = 4 # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_transform_meta.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_07.py","code":"\"\"\"\nTests the handling of descriptors within a dataclass.\n\"\"\"\n\n# This portion of the dataclass spec is under-specified in the documentation,\n# but its behavior can be determined from the runtime implementation.\n\nfrom dataclasses import dataclass\nfrom typing import Any, Generic, TypeVar, assert_type, overload\n\nT = TypeVar(\"T\")\n\n\nclass Desc1:\n @overload\n def __get__(self, __obj: None, __owner: Any) -> \"Desc1\":\n ...\n\n @overload\n def __get__(self, __obj: object, __owner: Any) -> int:\n ...\n\n def __get__(self, __obj: object | None, __owner: Any) -> \"int | Desc1\":\n raise NotImplementedError\n\n def __set__(self, __obj: object, __value: int) -> None:\n ...\n\n\n@dataclass\nclass DC1:\n y: Desc1 = Desc1()\n\n\ndc1 = DC1(3)\n\nassert_type(dc1.y, int)\nassert_type(DC1.y, Desc1)\n\n\nclass Desc2(Generic[T]):\n @overload\n def __get__(self, instance: None, owner: Any) -> list[T]:\n ...\n\n @overload\n def __get__(self, instance: object, owner: Any) -> T:\n ...\n\n def __get__(self, instance: object | None, owner: Any) -> list[T] | T:\n raise NotImplementedError\n\n\n@dataclass\nclass DC2:\n x: Desc2[int]\n y: Desc2[str]\n z: Desc2[str] = Desc2()\n\n\nassert_type(DC2.x, list[int])\nassert_type(DC2.y, list[str])\nassert_type(DC2.z, list[str])\n\ndc2 = DC2(Desc2(), Desc2(), Desc2())\nassert_type(dc2.x, int)\nassert_type(dc2.y, str)\nassert_type(dc2.z, str)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_descriptors.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_08.py","code":"\"\"\"\nTests validation of frozen dataclass instances.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#frozen-instances\n\nfrom dataclasses import dataclass\n\n@dataclass(frozen=True)\nclass DC1:\n a: float\n b: str\n\ndc1 = DC1(1, \"\")\n\ndc1.a = 1 # E: dataclass is frozen\ndc1.b = \"\" # E: dataclass is frozen\n\n\n# This should generate an error because a non-frozen dataclass\n# cannot inherit from a frozen dataclass.\n@dataclass # E[DC2]\nclass DC2(DC1): # E[DC2]\n pass\n\n@dataclass\nclass DC3:\n a: int\n\n# This should generate an error because a frozen dataclass\n# cannot inherit from a non-frozen dataclass.\n@dataclass(frozen=True) # E[DC4]\nclass DC4(DC3): # E[DC4]\n pass\n\n\n@dataclass(frozen=True)\nclass DC1Child(DC1):\n # This should be allowed because attributes within a frozen\n # dataclass are covariant rather than invariant.\n a: int\n","source":"typing_tests","origin":"conformance/tests/dataclasses_frozen.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_09.py","code":"\"\"\"\nTests the synthesis of the __hash__ method in a dataclass.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import Callable, Hashable, assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n\n\nassert_type(DC1.__hash__, None)\n\n# These should generate errors because DC1 isn't hashable.\nDC1(0).__hash__() # E\nv1: Hashable = DC1(0) # E\n\n\n@dataclass(eq=True, frozen=True)\nclass DC2:\n a: int\n\n\ndc2_hash: Callable[..., int] = DC2.__hash__ # OK\nDC2(0).__hash__() # OK\nv2: Hashable = DC2(0) # OK\n\n\n@dataclass(eq=True)\nclass DC3:\n a: int\n\n\nassert_type(DC3.__hash__, None)\n\n# These should generate errors because DC3 isn't hashable.\nDC3(0).__hash__() # E\nv3: Hashable = DC3(0) # E\n\n\n@dataclass(frozen=True)\nclass DC4:\n a: int\n\n\ndc4_hash: Callable[..., int] = DC4.__hash__ # OK\nDC4(0).__hash__() # OK\nv4: Hashable = DC4(0) # OK\n\n\n@dataclass(eq=True, unsafe_hash=True)\nclass DC5:\n a: int\n\n\ndc5_hash: Callable[..., int] = DC5.__hash__ # OK\nDC5(0).__hash__() # OK\nv5: Hashable = DC5(0) # OK\n\n\n@dataclass(eq=True)\nclass DC6:\n a: int\n\n def __hash__(self) -> int:\n return 0\n\n\ndc6_hash: Callable[..., int] = DC6.__hash__ # OK\nDC6(0).__hash__() # OK\nv6: Hashable = DC6(0) # OK\n\n\n@dataclass(frozen=True)\nclass DC7:\n a: int\n\n def __eq__(self, other) -> bool:\n return self.a == other.a\n\n\ndc7_hash: Callable[..., int] = DC7.__hash__ # OK\nDC7(0).__hash__() # OK\nv7: Hashable = DC7(0) # OK\n","source":"typing_tests","origin":"conformance/tests/dataclasses_hash.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_10.py","code":"\"\"\"\nTests inheritance rules for dataclasses.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#inheritance\n\nfrom dataclasses import dataclass\nfrom typing import Any, ClassVar\n\n\n@dataclass\nclass DC1:\n a: int\n b: str = \"\"\n\n\n@dataclass\nclass DC2(DC1):\n b: str = \"\"\n a: int = 1\n\n\ndc2_1 = DC2(1, \"\")\n\ndc2_2 = DC2()\n\n\n@dataclass\nclass DC3:\n x: float = 15.0\n y: str = \"\"\n\n\n@dataclass\nclass DC4(DC3):\n z: tuple[int] = (10,)\n x: float = 15\n\n\ndc4_1 = DC4(0.0, \"\", (1,))\n\n\n@dataclass\nclass DC5:\n # While this generates an error at runtime for the stdlib dataclass,\n # other libraries that use dataclass_transform don't have similar\n # restrictions. It is therefore not required that a type checker\n # report an error here.\n x: list[int] = [] # E?\n\n\n@dataclass\nclass DC6:\n x: int\n y: ClassVar[int] = 1\n\n\n@dataclass\nclass DC7(DC6):\n # This should generate an error because a ClassVar cannot override\n # an instance variable of the same name.\n x: ClassVar[int] # E\n\n # This should generate an error because an instance variable cannot\n # override a class variable of the same name.\n y: int # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_11.py","code":"\"\"\"\nTests the keyword-only feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY, field\n\n\n@dataclass\nclass DC1:\n a: str\n _: KW_ONLY\n b: int = 0\n\n\nDC1(\"hi\")\nDC1(a=\"hi\")\nDC1(a=\"hi\", b=1)\nDC1(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC1(\"hi\", 1) # E\n\n\n@dataclass\nclass DC2:\n b: int = field(kw_only=True, default=3)\n a: str\n\n\nDC2(\"hi\")\nDC2(a=\"hi\")\nDC2(a=\"hi\", b=1)\nDC2(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC2(\"hi\", 1) # E\n\n\n@dataclass(kw_only=True)\nclass DC3:\n a: str = field(kw_only=False)\n b: int = 0\n\n\nDC3(\"hi\")\nDC3(a=\"hi\")\nDC3(a=\"hi\", b=1)\nDC3(\"hi\", b=1)\n\n# This should generate an error because \"b\" is keyword-only.\nDC3(\"hi\", 1) # E\n\n\n@dataclass\nclass DC4(DC3):\n c: float\n\n\nDC4(\"\", 0.2, b=3)\nDC4(a=\"\", b=3, c=0.2)\n","source":"typing_tests","origin":"conformance/tests/dataclasses_kwonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_12.py","code":"\"\"\"\nTests the match_args feature of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass, KW_ONLY\nfrom typing import assert_type, Literal\n\n# If true, the __match_args__ tuple will be created from the list of non keyword-only parameters to the generated __init__() method\n\n@dataclass(match_args=True)\nclass DC1:\n x: int\n _: KW_ONLY\n y: str\n\nassert_type(DC1.__match_args__, tuple[Literal['x']])\n\n# The match_args default is True\n\n@dataclass\nclass DC2:\n x: int\n\nassert_type(DC2.__match_args__, tuple[Literal['x']])\n\n# __match_args__ is created even if __init__() is not generated\n\n@dataclass(match_args=True, init=False)\nclass DC3:\n x: int = 0\n\nassert_type(DC3.__match_args__, tuple[Literal['x']])\n\n# If false, or if __match_args__ is already defined in the class, then __match_args__ will not be generated.\n\n@dataclass(match_args=False)\nclass DC4:\n x: int\n\nDC4.__match_args__ # E\n\n@dataclass(match_args=True)\nclass DC5:\n __match_args__ = ()\n x: int\n\nassert_type(DC5.__match_args__, tuple[()])\n","source":"typing_tests","origin":"conformance/tests/dataclasses_match_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_13.py","code":"\"\"\"\nTests the synthesized comparison methods for dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\n\n@dataclass(order=True)\nclass DC1:\n a: str\n b: int\n\n\n@dataclass(order=True)\nclass DC2:\n a: str\n b: int\n\n\ndc1_1 = DC1(\"\", 0)\ndc1_2 = DC1(\"\", 0)\n\nif dc1_1 < dc1_2:\n pass\n\nif dc1_1 <= dc1_2:\n pass\n\nif dc1_1 > dc1_2:\n pass\n\nif dc1_1 >= dc1_2:\n pass\n\nif dc1_1 == dc1_2:\n pass\n\nif dc1_1 != dc1_2:\n pass\n\nif dc1_1 == None:\n pass\n\nif dc1_1 != None:\n pass\n\ndc2_1 = DC2(\"hi\", 2)\n\n# This should generate an error because the types are\n# incompatible.\nif dc1_1 < dc2_1: # E:\n pass\n\nif dc1_1 != dc2_1:\n pass\n","source":"typing_tests","origin":"conformance/tests/dataclasses_order.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_14.py","code":"\"\"\"\nTests type checking of the __post_init__ method in a dataclass.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0557/#post-init-processing\n\nfrom dataclasses import InitVar, dataclass, field, replace\nfrom typing import assert_type\n\n\n@dataclass\nclass DC1:\n a: int\n b: int\n x: InitVar[int]\n c: int\n y: InitVar[str]\n\n def __post_init__(self, x: int, y: int) -> None: # E: wrong type for y\n pass\n\n\ndc1 = DC1(1, 2, 3, 4, \"\")\n\nassert_type(dc1.a, int)\nassert_type(dc1.b, int)\nassert_type(dc1.c, int)\nprint(dc1.x) # E: cannot access InitVar\nprint(dc1.y) # E: cannot access InitVar\n\n@dataclass\nclass DC2:\n x: InitVar[int]\n y: InitVar[str]\n\n def __post_init__(self, x: int) -> None: # E: missing y\n pass\n\n\n@dataclass\nclass DC3:\n _name: InitVar[str] = field()\n name: str = field(init=False)\n\n def __post_init__(self, _name: str):\n ...\n\n\n@dataclass\nclass DC4(DC3):\n _age: InitVar[int] = field()\n age: int = field(init=False)\n\n def __post_init__(self, _name: str, _age: int):\n ...\n","source":"typing_tests","origin":"conformance/tests/dataclasses_postinit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_15.py","code":"\"\"\"\nTests the slots functionality of dataclass added in Python 3.10.\n\"\"\"\n\n# Specification: https://docs.python.org/3/library/dataclasses.html#module-contents\n\nfrom dataclasses import dataclass\n\n# This should generate an error because __slots__ is already defined.\n@dataclass(slots=True) # E[DC1]\nclass DC1: # E[DC1]\n x: int\n\n __slots__ = ()\n\n\n@dataclass(slots=True)\nclass DC2:\n x: int\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass(slots=False)\nclass DC3:\n x: int\n\n __slots__ = (\"x\",)\n\n def __init__(self):\n self.x = 3\n\n # This should generate an error because \"y\" is not in slots.\n self.y = 3 # E\n\n\n@dataclass\nclass DC4:\n __slots__ = (\"y\", \"x\")\n x: int\n y: str\n\n\nDC4(1, \"bar\")\n\n\n@dataclass(slots=True)\nclass DC5:\n a: int\n\n\nDC5.__slots__\nDC5(1).__slots__\n\n\n@dataclass\nclass DC6:\n a: int\n\n\n# This should generate an error because __slots__ is not defined.\nDC6.__slots__ # E\n\n# This should generate an error because __slots__ is not defined.\nDC6(1).__slots__ # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_slots.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_16.py","code":"\"\"\"\nTests basic handling of the dataclass factory.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html\n# Also, see https://peps.python.org/pep-0557/\n\nfrom dataclasses import InitVar, dataclass, field\nfrom typing import Any, Callable, ClassVar, Generic, Protocol, TypeVar, assert_type\nimport sys\n\nT = TypeVar(\"T\")\n\n\n@dataclass(order=True)\nclass InventoryItem:\n x = 0\n name: str\n unit_price: float\n quantity_on_hand: int = 0\n\n def total_cost(self) -> float:\n return self.unit_price * self.quantity_on_hand\n\n\nv1 = InventoryItem(\"soap\", 2.3)\n\n\nclass InventoryItemInitProto(Protocol):\n def __call__(\n self, name: str, unit_price: float, quantity_on_hand: int = ...\n ) -> None: ...\n\n\n# Validate the type of the synthesized __init__ method.\nx1: InventoryItemInitProto = v1.__init__\n\n# Make sure the following additional methods were synthesized.\nprint(v1.__repr__)\nprint(v1.__eq__)\nprint(v1.__ne__)\nprint(v1.__lt__)\nprint(v1.__le__)\nprint(v1.__gt__)\nprint(v1.__ge__)\n\nassert_type(v1.name, str)\nassert_type(v1.unit_price, float)\nassert_type(v1.quantity_on_hand, int)\n\nv2 = InventoryItem(\"name\") # E: missing unit_price\nv3 = InventoryItem(\"name\", \"price\") # E: incorrect type for unit_price\nv4 = InventoryItem(\"name\", 3.1, 3, 4) # E: too many arguments\n\n\n# > TypeError will be raised if a field without a default value follows a\n# > field with a default value. This is true either when this occurs in a\n# > single class, or as a result of class inheritance.\n@dataclass # E[DC1]\nclass DC1:\n a: int = 0 # E[DC1]: field with default should follow a field with no default.\n b: int # E[DC1]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC2]\nclass DC2:\n a: int = field(default=1) # E[DC2]: field with default should follow a field with no default.\n b: int # E[DC2]: field with no default cannot follow field with default.\n\n\n@dataclass # E[DC3]\nclass DC3:\n a: InitVar[int] = 0 # E[DC3]: field with default should follow a field with no default.\n b: int # E[DC3]: field with no default cannot follow field with default.\n\n\n@dataclass\nclass DC4:\n a: int = field(init=False)\n b: int\n\n\nv5 = DC4(0)\nv6 = DC4(0, 1) # E: too many parameters\n\n\n@dataclass\nclass DC5:\n a: int = field(default_factory=str) # E: type mismatch\n\n\ndef f(s: str) -> int:\n return int(s)\n\n\n@dataclass\nclass DC6:\n a: ClassVar[int] = 0\n b: str\n c: Callable[[str], int] = f\n\n\ndc6 = DC6(\"\")\nassert_type(dc6.a, int)\nassert_type(DC6.a, int)\nassert_type(dc6.b, str)\nassert_type(dc6.c, Callable[[str], int])\n\n\n@dataclass\nclass DC7:\n x: int\n\n\n@dataclass(init=False)\nclass DC8(DC7):\n y: int\n\n def __init__(self, a: DC7, y: int):\n self.__dict__ = a.__dict__\n self.y = y\n\n\na = DC7(3)\nb = DC8(a, 5)\n\n# This should generate an error because there is an extra parameter\nDC7(3, 4) # E\n\n# This should generate an error because there is one too few parameters\nDC8(a) # E\n\n\n@dataclass\nclass DC9:\n a: str = field(init=False, default=\"s\")\n b: bool = field()\n\n\n@dataclass\nclass DC10(DC9):\n a: str = field()\n b: bool = field()\n\n\n@dataclass(init=False)\nclass DC11:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC11(3)\n\n\n@dataclass(init=True)\nclass DC12:\n x: int\n x_squared: int\n\n def __init__(self, x: int):\n self.x = x\n self.x_squared = x * x\n\n\nDC12(3)\n\n\n@dataclass(init=False)\nclass DC13:\n x: int\n x_squared: int\n\n\n# This should generate an error because there is no matching\n# override __init__ method and no synthesized __init__.\nDC13(3) # E\n\n\n@dataclass\nclass DC14:\n prop_1: str = field(init=False)\n prop_2: str = field(default=\"hello\")\n prop_3: str = field(default_factory=lambda: \"hello\")\n\n\n@dataclass\nclass DC15(DC14):\n prop_2: str = \"\"\n\n\ndc15 = DC15(prop_2=\"test\")\n\nassert_type(dc15.prop_1, str)\nassert_type(dc15.prop_2, str)\nassert_type(dc15.prop_3, str)\n\n\nclass DataclassProto(Protocol):\n __dataclass_fields__: ClassVar[dict[str, Any]]\n\n\nv7: DataclassProto = dc15\n\n\n@dataclass\nclass DC16(Generic[T]):\n value: T\n\n\nassert_type(DC16(1), DC16[int])\n\n\nclass DC17(DC16[str]):\n pass\n\n\nassert_type(DC17(\"\"), DC17)\n\n\n@dataclass\nclass DC18:\n x: int = field()\n # This may generate a type checker error because an unannotated field\n # will result in a runtime exception.\n y = field() # E?\n\n\n# > Dataclass fields may be conditional, via checks of the same\n# > statically-known conditions that a type-checker understands elsewhere,\n# > such as Python version:\n\n@dataclass\nclass DC19:\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nDC19(1, 2)\nDC19(1, 2, 3) # E\n","source":"typing_tests","origin":"conformance/tests/dataclasses_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"deprecated-decorator","pep":"702","introduced_in":"3.13","form":"modern","file":"deprecated-decorator/modern_01.py","code":"\"\"\"\nTests the warnings.deprecated function.\n\"\"\"\n\n# pyright: reportDeprecated=true\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#deprecated\n# See also https://peps.python.org/pep-0702/\n\nfrom typing import Protocol, override\nfrom typing_extensions import deprecated\n\n# > Type checkers should produce a diagnostic whenever they encounter a usage of an object\n# > marked as deprecated. [...] For deprecated classes and functions, this includes:\n\n# > * `from` imports\n\nfrom _directives_deprecated_library import Ham # E: Use of deprecated class Ham\nimport _directives_deprecated_library as library\n\n\n# > * References through module, class, or instance attributes\n\nlibrary.norwegian_blue(1) # E: Use of deprecated function norwegian_blue\nmap(library.norwegian_blue, [1, 2, 3]) # E: Use of deprecated function norwegian_blue\n\n\n# > For deprecated overloads, this includes all calls that resolve to the deprecated overload.\n\nlibrary.foo(1) # E: Use of deprecated overload for foo\nlibrary.foo(\"x\") # OK\n\n\nham = Ham() # E?: OK (already reported above)\n\n\n# > * Any syntax that indirectly triggers a call to the function.\n\nspam = library.Spam()\n\n_ = spam + 1 # E: Use of deprecated method Spam.__add__\nspam += 1 # E: Use of deprecated method Spam.__add__\n\nspam.greasy # E: Use of deprecated property Spam.greasy\nspam.shape # OK\n\nspam.shape = \"cube\" # E: Use of deprecated property setter Spam.shape\nspam.shape += \"cube\" # E: Use of deprecated property setter Spam.shape\n\n\nclass Invocable:\n @deprecated(\"Deprecated\")\n def __call__(self) -> None:\n ...\n\n\ninvocable = Invocable()\ninvocable() # E: Use of deprecated method __call__\n\n\n# > * Any usage of deprecated objects in their defining module\n\n\n@deprecated(\"Deprecated\")\ndef lorem() -> None:\n ...\n\n\nlorem() # E: Use of deprecated function lorem\n\n\n# > There are additional scenarios where deprecations could come into play.\n# > For example, an object may implement a `typing.Protocol`,\n# > but one of the methods required for protocol compliance is deprecated.\n# > As scenarios such as this one appear complex and relatively unlikely to come up in practice,\n# > this PEP does not mandate that type checkers detect them.\n\n\nclass SupportsFoo1(Protocol):\n @deprecated(\"Deprecated\")\n def foo(self) -> None:\n ...\n\n def bar(self) -> None:\n ...\n\n\nclass FooConcrete1(SupportsFoo1):\n @override\n def foo(self) -> None: # E?: Implementation of deprecated method foo\n ...\n\n def bar(self) -> None:\n ...\n\n\ndef foo_it(f: SupportsFoo1) -> None:\n f.foo() # E: Use of deprecated method foo\n f.bar()\n\n\nclass SupportsFoo2(Protocol):\n def foo(self) -> None:\n ...\n\n\nclass FooConcrete2:\n @deprecated(\"Deprecated\")\n def foo(self) -> None:\n ...\n\n\ndef takes_foo(f: SupportsFoo2) -> None:\n ...\n\n\ndef caller(c: FooConcrete2) -> None:\n takes_foo(\n c\n ) # E?: FooConcrete2 is a SupportsFoo2, but only because of a deprecated method\n","source":"typing_tests","origin":"conformance/tests/directives_deprecated.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"disjoint-base","pep":"800","introduced_in":"3.15","form":"modern","file":"disjoint-base/modern_01.py","code":"\"\"\"\nTests the typing.disjoint_base decorator introduced in PEP 800.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#disjoint-base\n# See also https://peps.python.org/pep-0800/\n\nfrom typing import NamedTuple, Protocol, TypedDict, assert_never\nfrom typing_extensions import disjoint_base\n\n\n# > It may only be used on nominal classes, including ``NamedTuple``\n# > definitions\n\n\n@disjoint_base\nclass Left:\n pass\n\n\n@disjoint_base\nclass Right:\n pass\n\n\n@disjoint_base\nclass LeftChild(Left):\n pass\n\n\n@disjoint_base\nclass Record(NamedTuple):\n value: int\n\n\nclass Plain:\n pass\n\n\n# > If the candidate set contains a single disjoint base, that is the\n# > class's disjoint base.\n\n\nclass OtherLeftChild(Left):\n pass\n\n\n# > If there are multiple candidates, but one of them is a subclass of\n# > all other candidates, that class is the disjoint base.\n\n\nclass LeftAndPlain(Left, Plain):\n pass\n\n\nclass LeftChildAndLeft(LeftChild, Left):\n pass\n\n\nclass PlainRecord(Plain, Record):\n pass\n\n\n# > Type checkers must check for a valid disjoint base when checking class definitions,\n# > and emit a diagnostic if they encounter a class\n# > definition that lacks a valid disjoint base.\n\n\nclass LeftAndRight(Left, Right): # E: incompatible disjoint bases\n pass\n\n\nclass LeftChildAndRight(LeftChild, Right): # E: incompatible disjoint bases\n pass\n\n\nclass LeftAndRightViaChild(LeftAndPlain, Right): # E: incompatible disjoint bases\n pass\n\n\nclass LeftRecord(Left, Record): # E: incompatible disjoint bases\n pass\n\n\n# > A nominal class is a disjoint base if it [...] contains a non-empty\n# > `__slots__` definition.\n\n\nclass SlotBase1:\n __slots__ = (\"x\",)\n\n\nclass SlotBase2:\n __slots__ = (\"y\",)\n\n\nclass EmptySlots:\n __slots__ = ()\n\n\nclass SlotAndEmptySlots(SlotBase1, EmptySlots):\n pass\n\n\nclass IncompatibleSlots(SlotBase1, SlotBase2): # E: incompatible disjoint bases\n pass\n\n\n# > it is a type checker error to use the decorator on a function,\n# > ``TypedDict`` definition, or ``Protocol`` definition.\n\n\n@disjoint_base # E: disjoint_base cannot be applied to a function\ndef func() -> None:\n pass\n\n\n@disjoint_base # E: disjoint_base cannot be applied to a TypedDict\nclass Movie(TypedDict):\n name: str\n\n\n@disjoint_base # E: disjoint_base cannot be applied to a Protocol\nclass SupportsClose(Protocol):\n def close(self) -> None:\n ...\n\n\n# > Type checkers may use disjoint bases to determine that two classes cannot\n# > have a common subclass.\n\n\ndef narrow(obj: Left) -> None:\n if isinstance(obj, Right): # E?: may be treated as unreachable\n assert_never(obj) # E?: may not be narrowed to Never\n","source":"typing_tests","origin":"conformance/tests/directives_disjoint_base.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_01.py","code":"\"\"\"\nTests the handling of ClassVar and Final in dataclasses.\n\"\"\"\n\nfrom dataclasses import dataclass\nfrom typing import assert_type, ClassVar, Final\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/dataclasses.html#dataclass-semantics\n\n# > A final class variable on a dataclass must be explicitly annotated as\n# e.g. x: ClassVar[Final[int]] = 3.\n\n\n@dataclass\nclass D:\n final_no_default: Final[int]\n final_with_default: Final[str] = \"foo\"\n final_classvar: ClassVar[Final[int]] = 4\n # we don't require support for Final[ClassVar[...]] because the dataclasses\n # runtime implementation won't recognize it as a ClassVar either\n\n\n# An explicitly marked ClassVar can be accessed on the class:\nassert_type(D.final_classvar, int)\n\n# ...but not assigned to, because it's Final:\nD.final_classvar = 10 # E: can't assign to final attribute\n\n# A non-ClassVar attribute (with or without default) is a dataclass field:\nd = D(final_no_default=1, final_with_default=\"bar\")\nassert_type(d.final_no_default, int)\nassert_type(d.final_with_default, str)\n\n# ... but can't be assigned to (on the class or on an instance):\nd.final_no_default = 10 # E: can't assign to final attribute\nd.final_with_default = \"baz\" # E: can't assign to final attribute\nD.final_no_default = 10 # E: can't assign to final attribute\nD.final_with_default = \"baz\" # E: can't assign to final attribute\n","source":"typing_tests","origin":"conformance/tests/dataclasses_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_02.py","code":"\"\"\"\nTests the typing.Final special form.\n\"\"\"\n\nfrom typing import ClassVar, Final, Literal, NamedTuple, TypedDict, assert_type\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#id1\n\nID1: Final[int] = 1\n\nID2: Final = 1\nassert_type(ID2, Literal[1])\n\n# > If the right hand side is omitted, there must be an explicit type argument to Final.\n\nBAD1: Final # E: missing assignment\n\nBAD2: Final[str, int] = \"\" # E: only one type argument allowed\n\n# > There can be at most one final declaration per module or class for a given\n# > attribute.\n\n# > As self.id: Final = 1 (also optionally with a type in square brackets).\n# > This is allowed only in __init__ methods, so that the final instance\n# > attribute is assigned only once when an instance is created.\n\n\nclass ClassA:\n ID1: Final = 1\n\n # > In class bodies and stub files you can omit the right hand side and just\n # > write ID: Final[float]. If the right hand side is omitted, there must be\n # > an explicit type argument to Final.\n ID2: Final # E: missing initialization\n\n # > A final attribute declared in a class body without an initializer must\n # > be initialized in the __init__ method (except in stub files):\n ID3: Final[int] # E: missing initialization\n\n ID4: Final[int] # OK because initialized in __init__\n\n ID5: Final[int] = 0\n\n ID6: Final[int]\n\n ID7: Final[int] = 0\n\n def __init__(self, cond: bool) -> None:\n self.id1: Final = 1\n self.id2: Final[int] = 1\n\n self.ID4 = 1\n\n self.ID5 = 0 # E: Already initialized\n\n if cond:\n self.ID6 = 1\n else:\n self.ID6 = 2\n\n def method1(self) -> None:\n self.id3: Final = 1 # E: not allowed outside of __init__ method.\n self.id4: Final[int] = 1 # E: not allowed outside of __init__ method.\n\n self.ID7 = 0 # E: cannot modify Final value\n\n self.ID7 += 1 # E: cannot modify Final value\n\n\nRATE: Final = 3000\nRATE = 300 # E: Cannot redefine Final value\n\n# > There can’t be separate class-level and instance-level constants\n# > with the same name.\n\n\nclass ClassB:\n DEFAULT_ID: Final = 0\n\n\nClassB.DEFAULT_ID = 0 # E: Cannot redefined value\n\n\n# > A type checker should prevent final attributes from being overridden in a subclass:\n\n\nclass ClassC:\n BORDER_WIDTH: Final = 2.5\n\n __private: Final = 0\n\n\nclass ClassCChild(ClassC):\n BORDER_WIDTH = 2.5 # E: Cannot override Final value\n\n __private = 0 # OK\n\n\n# > Type checkers should infer a final attribute that is initialized in a class\n# > body as being a class variable. Variables should not be annotated with both\n# > ClassVar and Final. (Except in a dataclass; see dataclasses_final.py.)\n\n\nclass ClassD:\n VALUE1: Final = 1\n\n VALUE2: ClassVar[Final] = 1 # E: Final cannot be used with ClassVar\n VALUE3: Final[ClassVar] = 1 # E: Final cannot be used with ClassVar\n\n\nClassD.VALUE1 # OK\n\n\n# > Final may only be used as the outermost type in assignments or variable\n# > annotations. Using it in any other position is an error. In particular,\n# > Final can’t be used in annotations for function arguments.\n\nx: list[Final[int]] = [] # E\n\n\ndef func1(x: Final[list[int]]) -> None: # E\n ...\n\n\n# > ``Final`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithFinal(TypedDict):\n a: int\n b: Final[int] # E: Final not allowed in a TypedDict\n\n\nclass NTWithFinal(NamedTuple):\n a: int\n b: Final[int] # E: Final not allowed in a NamedTuple\n\n\n# > Type checkers should treat uses of a final name that was initialized with\n# > a literal as if it was replaced by the literal. For example, the following\n# > should be allowed:\n\nX: Final = \"x\"\nY: Final = \"y\"\nN = NamedTuple(\"N\", [(X, int), (Y, int)])\n\nN(x=3, y=4) # OK\nN(a=1) # E\nN(x=\"\", y=\"\") # E\n\n\ndef func2() -> None:\n global ID1\n\n ID1 = 2 # E: cannot modify Final value\n\n x: Final = 3\n\n x += 1 # E: cannot modify Final value\n\n a = (x := 4) # E: cannot modify Final value\n\n for x in [1, 2, 3]: # E: cannot modify Final value\n pass\n\n with open(\"FileName\") as x: # E: cannot modify Final value\n pass\n\n (a, x) = (1, 2) # E: cannot modify Final value\n\n\n# > If a module declares a ``Final`` variable and another module imports that\n# > variable in an import statement by name or wildcard, the imported symbol\n# > inherits the ``Final`` type qualifier. Any attempt to assign a different value\n# > to this symbol should be flagged as an error by a type checker.\n\n\nfrom _qualifiers_final_annotation_1 import TEN\n\nTEN = 9 # E: Cannot redefine Final value\n\nfrom _qualifiers_final_annotation_2 import *\n\nPI = 3.14159 # E: Cannot redefine Final value\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_03.py","code":"\"\"\"\nTests the @final decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/qualifiers.html#final\n\nfrom typing import final, overload\nfrom _qualifiers_final_decorator import Base3, Base4\n\n# > A type checker should prohibit any class decorated with @final from being\n# > subclassed and any method decorated with @final from being overridden in a\n# > subclass. The method decorator version may be used with all of instance\n# > methods, class methods, static methods, and properties.\n\n\n@final\nclass Base1:\n ...\n\n\nclass Derived1(Base1): # E: Cannot inherit from final class \"Base\"\n ...\n\n\nclass Base2:\n @final\n def method1(self) -> None:\n pass\n\n @final\n @classmethod\n def method2(cls) -> None:\n pass\n\n @final\n @staticmethod\n def method3() -> None:\n pass\n\n # > For overloaded methods, @final should be placed on the implementation.\n\n @overload\n def method4(self, x: int) -> int:\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @final\n def method4(self, x: int | str) -> int | str:\n return 0\n\n\nclass Derived2(Base2):\n def method1(self) -> None: # E\n pass\n\n @classmethod # E[method2]\n def method2(cls) -> None: # E[method2]\n pass\n\n @staticmethod # E[method3]\n def method3() -> None: # E[method3]\n pass\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n def method4(self, x: int | str) -> int | str: # E[method4]\n return 0\n\n\nclass Derived3(Base3):\n @overload # E[Derived3]\n def method(self, x: int) -> int: # E[Derived3]\n ...\n\n @overload # E[Derived3-2]\n @final # E[Derived3-2]: should be applied only to implementation\n def method(self, x: str) -> str: # E[Derived3-2]\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived3]\n return 0\n\n\nclass Derived4(Base4):\n @overload # E[Derived4]\n def method(self, x: int) -> int: # E[Derived4]\n ...\n\n @overload\n def method(self, x: str) -> str:\n ...\n\n def method(self, x: int | str) -> int | str: # E[Derived4]\n return 0\n\n\nclass Base5_1:\n ...\n\n\nclass Base5_2:\n @final\n def method(self, v: int) -> None:\n ...\n\n\n# Test multiple inheritance case.\nclass Derived5(Base5_1, Base5_2):\n def method(self) -> None: # E\n ...\n\n\n# > It is an error to use @final on a non-method function.\n\n\n@final # E[func]: not allowed on non-method function.\ndef func1() -> int: # E[func]\n return 0\n","source":"typing_tests","origin":"conformance/tests/qualifiers_final_decorator.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"final-qualifier","pep":"591","introduced_in":"3.8","form":"modern","file":"final-qualifier/modern_04.py","code":"\"\"\"\nTests the use of Final values when used with TypedDicts.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#use-of-final-values-and-literal-types\n\nfrom typing import Final, Literal, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\n# > Type checkers should allow final names (PEP 591) with string values to be\n# > used instead of string literals in operations on TypedDict objects.\nYEAR: Final = \"year\"\n\nm: Movie = {\"name\": \"Alien\", \"year\": 1979}\nyears_since_epoch = m[YEAR] - 1970\n\n\n# > An expression with a suitable literal type (PEP 586) can be used instead of\n# > a literal value.\ndef get_value(movie: Movie, key: Literal[\"year\", \"name\"]) -> int | str:\n return movie[key]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_final.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"literal-string","pep":"675","introduced_in":"3.11","form":"modern","file":"literal-string/modern_01.py","code":"\"\"\"\nTests handling of the LiteralString special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#literalstring\n\n\nfrom typing import (\n Any,\n Generic,\n Literal,\n LiteralString,\n Sequence,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nvariable_annotation: LiteralString\n\n\ndef my_function(literal_string: LiteralString) -> LiteralString:\n raise NotImplementedError\n\n\nclass Foo:\n my_attribute: LiteralString = \"\"\n\n\ntype_argument: list[LiteralString]\n\nT = TypeVar(\"T\", bound=LiteralString)\n\n\nbad_union: Literal[\"hello\", LiteralString] # E\nbad_nesting: Literal[LiteralString] # E\n\n\ndef func1(a: Literal[\"one\"], b: Literal[\"two\"]):\n x1: LiteralString = a\n\n x2: Literal[\"\"] = b # E\n\n\ndef func2(a: LiteralString, b: LiteralString, non_literal: str):\n # > Addition: x + y is of type LiteralString if both x and y are compatible with LiteralString.\n assert_type(a + b, LiteralString)\n\n # > Joining: sep.join(xs) is of type LiteralString if sep’s type is\n # > compatible with LiteralString and xs’s type is compatible with Iterable[LiteralString].\n assert_type(\",\".join((a, b)), LiteralString)\n assert_type(\",\".join((a, non_literal)), str)\n\n # > In-place addition: If s has type LiteralString and x has type compatible with\n # > LiteralString, then s += x preserves s’s type as LiteralString.\n a += \"hello\"\n b += a\n\n # > String formatting: An f-string has type LiteralString if and only if its constituent\n # > expressions are literal strings. s.format(...) has type LiteralString if and only if\n # > s and the arguments have types compatible with LiteralString.\n assert_type(f\"{a} {b}\", LiteralString)\n\n x1: LiteralString = f\"{a} {non_literal}\" # E\n\n assert_type(a + non_literal, str)\n\n # > LiteralString is compatible with the type str\n x2: str = a\n\n # > Other literal types, such as literal integers, are not compatible with LiteralString.\n x3: LiteralString = 3 # E\n x4: LiteralString = b\"test\" # E\n\n\n# > Conditional statements and expressions work as expected.\ndef condition1() -> bool:\n raise NotImplementedError\n\n\ndef return_literal_string() -> LiteralString:\n return \"foo\" if condition1() else \"bar\" # OK\n\n\ndef return_literal_str2(literal_string: LiteralString) -> LiteralString:\n return \"foo\" if condition1() else literal_string # OK\n\n\ndef return_literal_str3() -> LiteralString:\n result: LiteralString\n if condition1():\n result = \"foo\"\n else:\n result = \"bar\"\n\n return result # OK\n\n\n# > TypeVars can be bound to LiteralString.\nTLiteral = TypeVar(\"TLiteral\", bound=LiteralString)\n\n\ndef literal_identity(s: TLiteral) -> TLiteral:\n return s\n\n\ndef func3(s: Literal[\"hello\"]):\n y = literal_identity(s)\n assert_type(y, Literal[\"hello\"])\n\n\ndef func4(s: LiteralString):\n y2 = literal_identity(s)\n assert_type(y2, LiteralString)\n\n\ndef func5(s: str):\n literal_identity(s) # E\n\n\n# > LiteralString can be used as a type argument for generic classes.\nclass Container(Generic[T]):\n def __init__(self, value: T) -> None:\n self.value = value\n\n\ndef func6(s: LiteralString):\n x: Container[LiteralString] = Container(s) # OK\n\n\ndef func7(s: str):\n x_error: Container[LiteralString] = Container(s) # E\n\n\n# > Standard containers like List work as expected.\nxs: list[LiteralString] = [\"foo\", \"bar\", \"baz\"]\n\n\nclass A: pass\nclass B(A): pass\nclass C(B): pass\n\n\n@overload\ndef func8(x: Literal[\"foo\"]) -> C:\n ...\n\n\n@overload\ndef func8(x: LiteralString) -> B:\n ...\n\n\n@overload\ndef func8(x: str) -> A:\n ...\n\n\ndef func8(x: Any) -> Any:\n raise NotImplementedError\n\n\ndef call_func8(x: str) -> None:\n assert_type(func8(\"foo\"), C) # First overload\n assert_type(func8(\"bar\"), B) # Second overload\n assert_type(func8(x), A) # Third overload\n\n\ndef func9(val: list[LiteralString]):\n x1: list[str] = val # E\n\n\ndef func10(val: Sequence[LiteralString]):\n x1: Sequence[str] = val # OK\n","source":"typing_tests","origin":"conformance/tests/literals_literalstring.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_04.py","code":"\"\"\"\nTests interactions between Literal types and other typing features.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/literal.html#interactions-with-other-types-and-features\nfrom enum import Enum\nfrom typing import IO, Any, Final, Generic, Literal, TypeVar, LiteralString, assert_type, overload\n\n\ndef func1(v: tuple[int, str, list[bool]], a: Literal[0], b: Literal[5], c: Literal[-5]):\n assert_type(v[a], int)\n assert_type(v[2], list[bool])\n\n v[b] # E: index out of range\n v[c] # E: index out of range\n v[4] # E: index out of range\n v[-4] # E: index out of range\n\n\n_PathType = str | bytes | int\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"r\", \"w\", \"a\", \"x\", \"r+\", \"w+\", \"a+\", \"x+\"],\n) -> IO[str]:\n ...\n\n\n@overload\ndef open(\n path: _PathType,\n mode: Literal[\"rb\", \"wb\", \"ab\", \"xb\", \"r+b\", \"w+b\", \"a+b\", \"x+b\"],\n) -> IO[bytes]:\n ...\n\n\n@overload\ndef open(path: _PathType, mode: str) -> IO[Any]:\n ...\n\n\ndef open(path: _PathType, mode: Any) -> Any:\n raise NotImplementedError\n\n\nassert_type(open(\"path\", \"r\"), IO[str])\nassert_type(open(\"path\", \"wb\"), IO[bytes])\nassert_type(open(\"path\", \"other\"), IO[Any])\n\n\nA = TypeVar(\"A\", bound=int)\nB = TypeVar(\"B\", bound=int)\nC = TypeVar(\"C\", bound=int)\n\n\nclass Matrix(Generic[A, B]):\n def __add__(self, other: \"Matrix[A, B]\") -> \"Matrix[A, B]\":\n raise NotImplementedError\n\n def __matmul__(self, other: \"Matrix[B, C]\") -> \"Matrix[A, C]\":\n raise NotImplementedError\n\n def transpose(self) -> \"Matrix[B, A]\":\n raise NotImplementedError\n\n\ndef func2(a: Matrix[Literal[2], Literal[3]], b: Matrix[Literal[3], Literal[7]]):\n c = a @ b\n assert_type(c, Matrix[Literal[2], Literal[7]])\n\n\nT = TypeVar(\"T\", Literal[\"a\"], Literal[\"b\"], Literal[\"c\"])\nS = TypeVar(\"S\", bound=Literal[\"foo\"])\n\n\nclass Status(Enum):\n SUCCESS = 0\n INVALID_DATA = 1\n FATAL_ERROR = 2\n\n\ndef parse_status1(s: str | Status) -> None:\n if s is Status.SUCCESS:\n assert_type(s, Literal[Status.SUCCESS])\n elif s is Status.INVALID_DATA:\n assert_type(s, Literal[Status.INVALID_DATA])\n elif s is Status.FATAL_ERROR:\n assert_type(s, Literal[Status.FATAL_ERROR])\n else:\n assert_type(s, str)\n\n\n# > Type checkers may optionally perform additional analysis for both\n# > enum and non-enum Literal types beyond what is described in the section above.\n#\n# > For example, it may be useful to perform narrowing based on things\n# > like containment or equality checks:\n\ndef expects_bad_status(status: Literal[\"MALFORMED\", \"ABORTED\"]):\n ...\n\n\ndef expects_pending_status(status: Literal[\"PENDING\"]):\n ...\n\n\ndef parse_status2(status: LiteralString) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is sound, but optional per the spec\n\n\n# Narrowing `str` to `Literal` strings is unsound given the possiblity of\n# user-defined `str` subclasses that could have custom equality semantics,\n# but is explicitly listed by the spec as optional analysis that type checkers\n# may perform.\ndef parse_status3(status: str) -> None:\n if status == \"MALFORMED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n elif status == \"ABORTED\":\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status in (\"MALFORMED\", \"ABORTED\"):\n expects_bad_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n if status == \"PENDING\":\n expects_pending_status(status) # E? narrowing the type here is unsound, but allowed per the spec\n\n\nfinal_val1: Final = 3\nassert_type(final_val1, Literal[3])\n\nfinal_val2: Final = True\nassert_type(final_val2, Literal[True])\n","source":"typing_tests","origin":"conformance/tests/literals_interactions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_05.py","code":"\"\"\"\nTests legal and illegal parameterizations of Literal.\n\"\"\"\n\n# > Literal must be parameterized with at least one type.\n\nfrom typing import Any, Literal, TypeVar\nfrom enum import Enum\n\n\nclass Color(Enum):\n RED = 0\n GREEN = 1\n BLUE = 2\n\n\ngood1: Literal[26]\ngood2: Literal[0x1A]\ngood3: Literal[-4]\ngood4: Literal[+5]\ngood5: Literal[\"hello world\"]\ngood6: Literal[b\"hello world\"]\ngood7: Literal[\"hello world\"]\ngood8: Literal[True]\ngood9: Literal[Color.RED]\ngood10: Literal[None]\n\nReadOnlyMode = Literal[\"r\", \"r+\"]\nWriteAndTruncateMode = Literal[\"w\", \"w+\", \"wt\", \"w+t\"]\nWriteNoTruncateMode = Literal[\"r+\", \"r+t\"]\nAppendMode = Literal[\"a\", \"a+\", \"at\", \"a+t\"]\n\nAllModes = Literal[ReadOnlyMode, WriteAndTruncateMode, WriteNoTruncateMode, AppendMode]\n\ngood11: Literal[Literal[Literal[1, 2, 3], \"foo\"], 5, None]\n\nvariable = 3\nT = TypeVar(\"T\")\n\n# > Arbitrary expressions [are illegal]\nbad1: Literal[3 + 4] # E\nbad2: Literal[\"foo\".replace(\"o\", \"b\")] # E\nbad3: Literal[4 + 3j] # E\nbad4: Literal[~5] # E\nbad5: Literal[not False] # E\nbad6: Literal[(1, \"foo\", \"bar\")] # E\nbad7: Literal[{\"a\": \"b\", \"c\": \"d\"}] # E\nbad8: Literal[int] # E\nbad9: Literal[variable] # E\nbad10: Literal[T] # E\nbad11: Literal[3.14] # E\nbad12: Literal[Any] # E\nbad13: Literal[...] # E\n\n\ndef my_function(x: Literal[1 + 2]) -> int: # E\n return x * 3\n\n\nx: Literal # E\ny: Literal[my_function] = my_function # E\n\n\ndef func2(a: Literal[Color.RED]):\n x1: Literal[\"Color.RED\"] = a # E\n\n x2: \"Literal[Color.RED]\" = a # OK\n","source":"typing_tests","origin":"conformance/tests/literals_parameterizations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"literal-types","pep":"586","introduced_in":"3.8","form":"modern","file":"literal-types/modern_06.py","code":"\"\"\"\nTests the semantics of the Literal special form.\n\"\"\"\n\nfrom typing import Literal\nfrom typing import Literal as L\n\n\nv1: Literal[3] = 3\nv2: Literal[3] = 4 # E\n\nv3: L[-3] = -3\n\n\n# > Literal[20] and Literal[0x14] are equivalent\ndef func1(a: Literal[20], b: Literal[0x14], c: Literal[0b10100]):\n x1: Literal[0x14] = a\n x2: Literal[0x14] = b\n x3: Literal[0x14] = c\n\n\n# > Literal[0] and Literal[False] are not equivalent\ndef func2(a: Literal[0], b: Literal[False]):\n x1: Literal[False] = a # E\n x2: Literal[0] = b # E\n\n\n# > Given some value v that is a member of type T, the type Literal[v] shall\n# > be treated as a subtype of T. For example, Literal[3] is a subtype of int.\ndef func3(a: L[3, 4, 5]):\n b = a.__add__(3)\n c = a + 3\n a += 3 # E\n\n\n# > When a Literal is parameterized with more than one value, it’s treated\n# > as exactly equivalent to the union of those types.\ndef func4(a: L[None, 3] | L[3, \"foo\", b\"bar\", True]):\n x1: Literal[3, b\"bar\", True, \"foo\", None] = a\n a = x1\n","source":"typing_tests","origin":"conformance/tests/literals_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"override-decorator","pep":"698","introduced_in":"3.12","form":"modern","file":"override-decorator/modern_01.py","code":"\"\"\"\nTests the typing.override decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#override\n\nfrom typing import Any, Callable, overload, override\n\n\ndef wrapper(func: Callable[..., Any], /) -> Any:\n def wrapped(*args: Any, **kwargs: Any) -> Any:\n raise NotImplementedError\n\n return wrapped\n\n\nclass ParentA:\n def method1(self) -> int:\n return 1\n\n @overload\n def method2(self, x: int) -> int:\n ...\n\n @overload\n def method2(self, x: str) -> str:\n ...\n\n def method2(self, x: int | str) -> int | str:\n return 0\n\n def method5(self):\n pass\n\n\nclass ChildA(ParentA):\n @override\n def method1(self) -> int: # OK\n return 2\n\n @overload\n def method2(self, x: int) -> int:\n ...\n\n @overload\n def method2(self, x: str) -> str:\n ...\n\n def method2(self, x: int | str) -> int | str: # OK\n return 0\n\n @override # E[method3]\n def method3(self) -> int: # E[method3]: no matching signature in ancestor\n return 1\n\n @overload # E[method4]\n def method4(self, x: int) -> int: # E[method4]\n ...\n\n @overload\n def method4(self, x: str) -> str:\n ...\n\n @override # E[method4]\n def method4(self, x: int | str) -> int | str: # E[method4]: no matching signature in ancestor\n return 0\n\n @override\n @wrapper\n def method5(self): # OK\n pass\n\n # > The @override decorator should be permitted anywhere a type checker\n # > considers a method to be a valid override, which typically includes not\n # > only normal methods but also @property, @staticmethod, and @classmethod.\n\n @staticmethod\n @override # E[static_method1]\n def static_method1() -> int: # E[static_method1]: no matching signature in ancestor\n return 1\n\n @classmethod\n @override # E[class_method1]\n def class_method1(cls) -> int: # E[class_method1]: no matching signature in ancestor\n return 1\n\n @property\n @override # E[property1]\n def property1(self) -> int: # E[property1]: no matching signature in ancestor\n return 1\n\n\n# Test the case where the parent derives from Any\n\nclass ParentB(Any):\n pass\n\n\nclass ChildB(ParentB):\n @override\n def method1(self) -> None: # OK\n pass\n\n\n# > When type checkers encounter a method decorated with @typing.override they\n# > should treat it as a type error unless that method is overriding a method or\n# > attribute in some ancestor class, and the type of the overriding method is\n# > assignable to the type of the overridden method.\n\n# ``__init__`` and ``__new__`` are normally exempt from override compatibility\n# checks, since constructors are not subject to the Liskov substitution\n# principle. However, when they are explicitly decorated with ``@override`` the\n# decorator's assignability check should still be honored.\n# See https://github.com/python/typing/issues/2222\n\n\nclass ParentC:\n def __init__(self, x: int) -> None: ...\n\n def __new__(cls, x: int) -> \"ParentC\":\n raise NotImplementedError\n\n\nclass ChildC1(ParentC):\n @override\n def __init__(self, x: int) -> None: ... # OK\n\n @override\n def __new__(cls, x: int) -> \"ChildC1\": # OK\n raise NotImplementedError\n\n\nclass ChildC2(ParentC):\n @override # E[init]\n def __init__(self, x: str) -> None: ... # E[init]: not assignable to \"ParentC.__init__\"\n\n @override # E[new]\n def __new__(cls, x: str) -> \"ChildC2\": # E[new]: not assignable to \"ParentC.__new__\"\n raise NotImplementedError\n\n\n# Without ``@override`` an incompatible constructor signature is allowed, since\n# ``__init__`` and ``__new__`` are exempt from the usual override checks.\n\n\nclass ChildC3(ParentC):\n def __init__(self, x: str) -> None: ... # OK\n\n def __new__(cls, x: str) -> \"ChildC3\": # OK\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/classes_override.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_01.py","code":"\"\"\"\nTests basic usage of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#paramspec-variables\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeAlias\n\nP = ParamSpec(\"P\") # OK\nWrongName = ParamSpec(\"NotIt\") # E: name inconsistency\n\n\n# > Valid use locations\n\nTA1: TypeAlias = P # E\n\nTA2: TypeAlias = Callable[P, None] # OK\nTA3: TypeAlias = Callable[Concatenate[int, P], None] # OK\nTA4: TypeAlias = Callable[..., None] # OK\nTA5: TypeAlias = Callable[..., None] # OK\n\n\ndef func1(x: P) -> P: # E\n raise NotImplementedError\n\n\ndef func2(x: Concatenate[int, P]) -> int: # E\n raise NotImplementedError\n\n\ndef func3(x: list[P]) -> None: # E\n ...\n\n\ndef func4(x: Callable[[int, str], P]) -> None: # E\n ...\n\n\ndef func5(*args: P, **kwargs: P) -> None: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_02.py","code":"\"\"\"\nTests the usage of a ParamSpec and its components (P.args, P.kwargs).\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#the-components-of-a-paramspec\n\n\nfrom typing import Any, Callable, Concatenate, ParamSpec, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef puts_p_into_scope1(f: Callable[P, int]) -> None:\n def inner(*args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def mixed_up(*args: P.kwargs, **kwargs: P.args) -> None: # E\n pass\n\n def misplaced1(x: P.args) -> None: # E\n pass\n\n def bad_kwargs1(*args: P.args, **kwargs: P.args) -> None: # E\n pass\n\n def bad_kwargs2(*args: P.args, **kwargs: Any) -> None: # E\n pass\n\n\ndef out_of_scope(*args: P.args, **kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef puts_p_into_scope2(f: Callable[P, int]) -> None:\n stored_args: P.args # E\n stored_kwargs: P.kwargs # E\n\n def just_args(*args: P.args) -> None: # E\n pass\n\n def just_kwargs(**kwargs: P.kwargs) -> None: # E\n pass\n\n\ndef decorator(f: Callable[P, int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n assert_type(f(*args, **kwargs), int) # OK\n\n f(*kwargs, **args) # E\n\n f(1, *args, **kwargs) # E\n\n return foo # OK\n\n\ndef add(f: Callable[P, int]) -> Callable[Concatenate[str, P], None]:\n def foo(s: str, *args: P.args, **kwargs: P.kwargs) -> None: # OK\n pass\n\n def bar(*args: P.args, s: str, **kwargs: P.kwargs) -> None: # E\n pass\n\n return foo # OK\n\n\ndef remove(f: Callable[Concatenate[int, P], int]) -> Callable[P, None]:\n def foo(*args: P.args, **kwargs: P.kwargs) -> None:\n f(1, *args, **kwargs) # OK\n\n f(*args, 1, **kwargs) # E\n\n f(*args, **kwargs) # E\n\n return foo # OK\n\n\ndef outer(f: Callable[P, None]) -> Callable[P, None]:\n def foo(x: int, *args: P.args, **kwargs: P.kwargs) -> None:\n f(*args, **kwargs)\n\n def bar(*args: P.args, **kwargs: P.kwargs) -> None:\n foo(1, *args, **kwargs) # OK\n foo(x=1, *args, **kwargs) # E\n\n return bar\n\n\ndef twice(f: Callable[P, int], *args: P.args, **kwargs: P.kwargs) -> int:\n return f(*args, **kwargs) + f(*args, **kwargs)\n\n\ndef a_int_b_str(a: int, b: str) -> int:\n return 0\n\n\ntwice(a_int_b_str, 1, \"A\") # OK\ntwice(a_int_b_str, b=\"A\", a=1) # OK\ntwice(a_int_b_str, \"A\", 1) # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_components.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_03.py","code":"\"\"\"\nTests semantics of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#semantics\n\n\nfrom typing import Callable, Concatenate, Generic, ParamSpec, TypeVar, assert_type\n\nP = ParamSpec(\"P\")\n\n\ndef changes_return_type_to_str(x: Callable[P, int]) -> Callable[P, str]:\n raise NotImplementedError\n\n\ndef returns_int(a: str, b: bool, /) -> int:\n raise NotImplementedError\n\n\nf1 = changes_return_type_to_str(returns_int)\nassert_type(f1, Callable[[str, bool], str])\n\nv1 = f1(\"A\", True) # OK\nassert_type(v1, str)\nf1(a=\"A\", b=True) # E: positional-only\nf1(\"A\", \"A\") # E: wrong type\n\n\ndef func1(x: Callable[P, int], y: Callable[P, int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\ndef x_y(x: int, y: str) -> int:\n raise NotImplementedError\n\n\ndef y_x(y: int, x: str) -> int:\n raise NotImplementedError\n\n\nf2 = func1(x_y, x_y)\nassert_type(f2(1, \"\"), bool)\nassert_type(f2(y=\"\", x=1), bool)\n\nf3 = func1(x_y, y_x) # E?: Could return (a: int, b: str, /) -> bool\n# (a callable with two positional-only parameters)\n# This works because both callables have types that are\n# behavioral subtypes of Callable[[int, str], int]\n# Also OK for type checkers to reject this.\n\n\ndef keyword_only_x(*, x: int) -> int:\n raise NotImplementedError\n\n\ndef keyword_only_y(*, y: int) -> int:\n raise NotImplementedError\n\n\nfunc1(keyword_only_x, keyword_only_y) # E\n\n\nU = TypeVar(\"U\")\n\n\nclass Y(Generic[U, P]):\n f: Callable[P, str]\n prop: U\n\n def __init__(self, f: Callable[P, str], prop: U) -> None:\n self.f = f\n self.prop = prop\n\n\ndef callback_a(q: int, /) -> str:\n raise NotImplementedError\n\n\ndef func(x: int) -> None:\n y1 = Y(callback_a, x)\n assert_type(y1, Y[int, [int]])\n y2 = y1.f\n assert_type(y2, Callable[[int], str])\n\n\ndef bar(x: int, *args: bool) -> int:\n raise NotImplementedError\n\n\ndef add(x: Callable[P, int]) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\na1 = add(bar) # Should return (a: str, /, x: int, *args: bool) -> bool\nassert_type(a1(\"\", 1, False, True), bool)\nassert_type(a1(\"\", x=1), bool)\na1(1, x=1) # E\n\n\ndef remove(x: Callable[Concatenate[int, P], int]) -> Callable[P, bool]:\n raise NotImplementedError\n\n\nr1 = remove(bar) # Should return (*args: bool) -> bool\nassert_type(r1(False, True, True), bool)\nassert_type(r1(), bool)\nr1(1) # E\n\n\ndef transform(\n x: Callable[Concatenate[int, P], int]\n) -> Callable[Concatenate[str, P], bool]:\n raise NotImplementedError\n\n\nt1 = transform(bar) # Should return (a: str, /, *args: bool) -> bool\nassert_type(t1(\"\", True, False, True), bool)\nassert_type(t1(\"\"), bool)\nt1(1) # E\n\n\ndef expects_int_first(x: Callable[Concatenate[int, P], int]) -> None:\n ...\n\n\n@expects_int_first # E\ndef one(x: str) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef two(*, x: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # E\ndef three(**kwargs: int) -> int:\n raise NotImplementedError\n\n\n@expects_int_first # OK\ndef four(*args: int) -> int:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_semantics.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_04.py","code":"\"\"\"\nTests the handling of a ParamSpec specialization.\n\"\"\"\n\nfrom typing import Any, Callable, Concatenate, Generic, ParamSpec, TypeVar, cast\n\n\nT = TypeVar(\"T\")\nP1 = ParamSpec(\"P1\")\nP2 = ParamSpec(\"P2\")\n\n\nclass ClassA(Generic[T, P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\nclass ClassB(ClassA[T, P1], Generic[T, P1, P2]):\n f1: Callable[P1, int] = cast(Any, \"\")\n f2: Callable[P2, int] = cast(Any, \"\")\n x: T = cast(Any, \"\")\n\n\ndef func20(x: ClassA[int, P2]) -> str: # OK\n return \"\"\n\n\ndef func21(x: ClassA[int, Concatenate[int, P2]]) -> str: # OK\n return \"\"\n\n\ndef func22(x: ClassB[int, [int, bool], ...]) -> str: # OK\n return \"\"\n\n\ndef func23(x: ClassA[int, ...]) -> str: # OK\n return \"\"\n\n\ndef func24(x: ClassB[int, [], []]) -> str: # OK\n return \"\"\n\n\ndef func25(x: ClassA[int, int]) -> str: # E\n return \"\"\n\n\nclass ClassC(Generic[P1]):\n f: Callable[P1, int] = cast(Any, \"\")\n\n\ndef func30(x: ClassC[[int, str, bool]]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n\n\ndef func31(x: ClassC[int, str, bool]) -> None: # OK\n x.f(0, \"\", True) # OK\n x.f(\"\", \"\", True) # E\n x.f(0, \"\", \"\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"param-spec","pep":"612","introduced_in":"3.10","form":"modern","file":"param-spec/modern_05.py","code":"\"\"\"\nTests variance of ParamSpec.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance-inference\n\n\nfrom typing import Callable, Generic, ParamSpec\n\n\nclass InvariantParamSpec[**InOutP]:\n a: Callable[InOutP, None]\n\nin_out_obj: InvariantParamSpec[object] = InvariantParamSpec[int]() # E\nin_out_int: InvariantParamSpec[int] = InvariantParamSpec[object]() # E\n\n\nclass ContravariantParamSpec[**InP]:\n def f(self, *args: InP.args, **kwargs: InP.kwargs): ...\n\nin_obj: ContravariantParamSpec[object] = ContravariantParamSpec[int]() # E\nin_int: ContravariantParamSpec[int] = ContravariantParamSpec[object]() # OK\n\n\nclass CovariantParamSpec[**OutP]:\n def f(self, fn: Callable[OutP, None]) -> None:\n raise NotImplementedError\n\n\nout_int: CovariantParamSpec[int] = CovariantParamSpec[object]() # E\nout_obj: CovariantParamSpec[object] = CovariantParamSpec[int]() # OK\n\n# cases involving keyword-only, positional-only parameters, parameter names, defaults and differing callable arities\nclass Box[T]:\n t: T\n\n def __init__(self, t: T): ...\n\n\ndef f(a: int): ...\ndef kw(*, a: int): ...\ndef pos(a: int, /): ...\ndef names(b: int): ...\ndef default(a: int = 1): ...\ndef arity(a: int, b: str): ...\n\n\nclass InitP[**P]: # contravariant\n def __init__(self, fn: Callable[P, None]): ...\n\n def usage(self) -> Callable[P, None]:\n \"\"\"infer contravariance\"\"\"\n raise NotImplementedError\n\n\n# `InitP` produces a `Callable[P, None]`, so a replacement is only safe if it\n# accepts every call form that `InitP[(a: int)]` accepts.\nin_box = Box(InitP(f))\n\nin_kw_p = InitP(kw)\nin_box.t = in_kw_p # E\nin_pos_p = InitP(pos)\nin_box.t = in_pos_p # E\nin_names_p = InitP(names)\nin_box.t = in_names_p # E\nin_default_p = InitP(default)\nin_box.t = in_default_p # OK\nin_arity_p = InitP(arity)\nin_box.t = in_arity_p # E\n\n\nclass OutitP[**P]: # covariant\n def __init__(self, fn: Callable[P, None]): ...\n\n def usage(self, fn: Callable[P, None]):\n \"\"\"infer covariance\"\"\"\n\n\n# `OutitP` consumes a `Callable[P, None]`, so the safe direction is reversed: a\n# replacement is only safe if `Callable[(a: int), None]` can be passed to it.\nout_box = Box(OutitP(f))\n\nout_kw_p = OutitP(kw)\nout_box.t = out_kw_p # OK\nout_pos_p = OutitP(pos)\nout_box.t = out_pos_p # OK\nout_names_p = OutitP(names)\nout_box.t = out_names_p # E\nout_default_p = OutitP(default)\nout_box.t = out_default_p # E\nout_arity_p = OutitP(arity)\nout_box.t = out_arity_p # E\n\n\n# old style\nP = ParamSpec(\"P\") # OK\nInP = ParamSpec(\"InP\", contravariant=True) # OK\nOutP = ParamSpec(\"OutP\", covariant=True) # OK\nInferP = ParamSpec(\"InferP\", infer_variance=True) # OK\nInvP1 = ParamSpec(\"InvP1\", covariant=True, contravariant=True) # E\nInvP2 = ParamSpec(\"InvP2\", covariant=True, infer_variance=True) # E\nInvP3 = ParamSpec(\"InvP3\", contravariant=True, infer_variance=True) # E\n\nclass InvariantParamSpecOld(Generic[P]):\n def f(self, fn: Callable[P, None]) -> Callable[P, None]: # OK\n raise NotImplementedError\n\nin_out_old: InvariantParamSpecOld[int]\nin_out_old = InvariantParamSpecOld[int]() # OK\nin_out_old = InvariantParamSpecOld[bool]() # E\nin_out_old = InvariantParamSpecOld[object]() # E\n\nclass ContravariantParamSpecOld(Generic[InP]):\n def in_f(self) -> Callable[InP, None]: # OK\n raise NotImplementedError\n\n def out_f(self, fn: Callable[InP, None]) -> None: # E\n raise NotImplementedError\n\n\nin_obj_old: ContravariantParamSpecOld[object] = ContravariantParamSpecOld[int]() # E\nin_int_old: ContravariantParamSpecOld[int] = ContravariantParamSpecOld[object]() # OK\n\n\nclass CovariantParamSpecOld(Generic[OutP]):\n def in_f(self) -> Callable[OutP, None]: # E\n raise NotImplementedError\n def out_f(self, fn: Callable[OutP, None]) -> None: # OK\n raise NotImplementedError\n\n\nout_int_old: CovariantParamSpecOld[int] = CovariantParamSpecOld[object]() # E\nout_obj_old: CovariantParamSpecOld[object] = CovariantParamSpecOld[int]() # OK\n\n\n# `infer_variance=True` on a traditional `ParamSpec`\nclass InferredContravariantParamSpecOld(Generic[InferP]):\n def in_f(self) -> Callable[InferP, None]: # OK\n raise NotImplementedError\n\n\ninfer_in_obj_old: InferredContravariantParamSpecOld[object] = InferredContravariantParamSpecOld[int]() # E\ninfer_in_int_old: InferredContravariantParamSpecOld[int] = InferredContravariantParamSpecOld[object]() # OK\n\n\nclass InferredCovariantParamSpecOld(Generic[InferP]):\n def out_f(self, fn: Callable[InferP, None]) -> None: # OK\n raise NotImplementedError\n\n\ninfer_out_int_old: InferredCovariantParamSpecOld[int] = InferredCovariantParamSpecOld[object]() # E\ninfer_out_obj_old: InferredCovariantParamSpecOld[object] = InferredCovariantParamSpecOld[int]() # OK\n","source":"typing_tests","origin":"conformance/tests/generics_paramspec_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_01.py","code":"\"\"\"\nTests handling of callback protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#callback-protocols\n\nfrom typing import Any, Callable, ParamSpec, Protocol, TypeVar, cast, overload\n\nInputT = TypeVar(\"InputT\", contravariant=True)\nOutputT = TypeVar(\"OutputT\", covariant=True)\n\n\nclass Proto1(Protocol):\n def __call__(self, *vals: bytes, max_len: int | None = None) -> list[bytes]:\n ...\n\n\ndef cb1_good1(*vals: bytes, max_len: int | None = None) -> list[bytes]:\n return []\n\n\ndef cb1_bad1(*vals: bytes, max_items: int | None) -> list[bytes]:\n return []\n\n\ndef cb1_bad2(*vals: bytes) -> list[bytes]:\n return []\n\n\ndef cb1_bad3(*vals: bytes, max_len: str | None) -> list[bytes]:\n return []\n\n\ncb1: Proto1 = cb1_good1 # OK\ncb1 = cb1_bad1 # E: different names\ncb1 = cb1_bad2 # E: parameter types\ncb1 = cb1_bad3 # E: default argument\n\n\nclass Proto2(Protocol):\n def __call__(self, *vals: bytes, **kwargs: str) -> None:\n pass\n\n\ndef cb2_good1(*a: bytes, **b: str):\n pass\n\n\ndef cb2_bad1(*a: bytes):\n pass\n\n\ndef cb2_bad2(*a: str, **b: str):\n pass\n\n\ndef cb2_bad3(*a: bytes, **b: bytes):\n pass\n\n\ndef cb2_bad4(**b: str):\n pass\n\n\ncb2: Proto2 = cb2_good1 # OK\n\ncb2 = cb2_bad1 # E: missing **kwargs\ncb2 = cb2_bad2 # E: parameter type\ncb2 = cb2_bad3 # E: parameter type\ncb2 = cb2_bad4 # E: missing parameter\n\n\nclass Proto3(Protocol):\n def __call__(self) -> None:\n pass\n\n\ncb3: Proto3 = cb2_good1 # OK\ncb3 = cb2_bad1 # OK\ncb3 = cb2_bad2 # OK\ncb3 = cb2_bad3 # OK\ncb3 = cb2_bad4 # OK\n\n\n# A callback protocol with other attributes.\nclass Proto4(Protocol):\n other_attribute: int\n\n def __call__(self, x: int) -> None:\n pass\n\n\ndef cb4_bad1(x: int) -> None:\n pass\n\n\nvar4: Proto4 = cb4_bad1 # E: missing attribute\n\n\nclass Proto5(Protocol):\n def __call__(self, *, a: int, b: str) -> int:\n ...\n\n\ndef cb5_good1(a: int, b: str) -> int:\n return 0\n\n\ncb5: Proto5 = cb5_good1 # OK\n\n\nclass NotProto6:\n def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]:\n return []\n\n\ndef cb6_bad1(*vals: bytes, max_len: int | None = None) -> list[bytes]:\n return []\n\n\ncb6: NotProto6 = cb6_bad1 # E: NotProto6 isn't a protocol class\n\n\nclass Proto7(Protocol[InputT, OutputT]):\n def __call__(self, inputs: InputT) -> OutputT:\n ...\n\n\nclass Class7_1:\n # Test for unannotated parameter.\n def __call__(self, inputs) -> int:\n return 5\n\n\ncb7_1: Proto7[int, int] = Class7_1() # OK\n\n\nclass Class7_2:\n # Test for parameter with type Any.\n def __call__(self, inputs: Any) -> int:\n return 5\n\n\ncb7_2: Proto7[int, int] = Class7_2() # OK\n\n\nclass Proto8(Protocol):\n @overload\n def __call__(self, x: int) -> int:\n ...\n\n @overload\n def __call__(self, x: str) -> str:\n ...\n\n def __call__(self, x: Any) -> Any:\n ...\n\n\ndef cb8_good1(x: Any) -> Any:\n return x\n\n\ndef cb8_bad1(x: int) -> Any:\n return x\n\n\ncb8: Proto8 = cb8_good1 # OK\ncb8 = cb8_bad1 # E: parameter type\n\n\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\", covariant=True)\n\n\nclass Proto9[**P, R](Protocol):\n other_attribute: int\n\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\ndef decorator1(f: Callable[P, R]) -> Proto9[P, R]:\n converted = cast(Proto9[P, R], f)\n converted.other_attribute = 1\n converted.other_attribute = \"str\" # E: incompatible type\n converted.xxx = 3 # E: unknown attribute\n return converted\n\n\n@decorator1\ndef cb9_good(x: int) -> str:\n return \"\"\n\n\nprint(cb9_good.other_attribute) # OK\nprint(cb9_good.other_attribute2) # E: unknown attribute\n\ncb9_good(x=3)\n\n\nclass Proto10(Protocol):\n __name__: str\n __module__: str\n __qualname__: str\n __annotations__: dict[str, Any]\n\n def __call__(self) -> None:\n ...\n\n\ndef cb10_good() -> None:\n pass\n\n\ncb10: Proto10 = cb10_good # OK\n\n\nclass Proto11(Protocol):\n def __call__(self, x: int, /, y: str) -> Any:\n ...\n\n\ndef cb11_good1(x: int, /, y: str, z: None = None) -> Any:\n raise NotImplementedError\n\n\ndef cb11_good2(x: int, y: str, z: None = None) -> Any:\n raise NotImplementedError\n\n\ndef cb11_bad1(x: int, y: str, /) -> Any:\n raise NotImplementedError\n\n\ncb11: Proto11 = cb11_good1 # OK\ncb11 = cb11_good2 # OK\ncb11 = cb11_bad1 # E: y is position-only\n\n\nclass Proto12(Protocol):\n def __call__(self, *args: Any, kwarg0: Any, kwarg1: Any) -> None:\n ...\n\n\ndef cb12_good1(*args: Any, kwarg0: Any, kwarg1: Any) -> None:\n pass\n\n\ndef cb12_good2(*args: Any, **kwargs: Any) -> None:\n pass\n\n\ndef cb12_bad1(*args: Any, kwarg0: Any) -> None:\n pass\n\n\ncb12: Proto12 = cb12_good1 # OK\ncb12 = cb12_good2 # OK\ncb12 = cb12_bad1 # E: missing kwarg1\n\n\nclass Proto13_Default(Protocol):\n # Callback with positional parameter with default arg value\n def __call__(self, path: str = ...) -> str:\n ...\n\n\nclass Proto13_NoDefault(Protocol):\n # Callback with positional parameter but no default arg value\n def __call__(self, path: str) -> str:\n ...\n\n\ndef cb13_default(path: str = \"\") -> str:\n return \"\"\n\n\ndef cb13_no_default(path: str) -> str:\n return \"\"\n\n\ncb13_1: Proto13_Default = cb13_default # OK\ncb13_2: Proto13_Default = cb13_no_default # E: no default\n\ncb13_3: Proto13_NoDefault = cb13_default # OK\ncb13_4: Proto13_NoDefault = cb13_no_default # OK\n\n\nclass Proto14_Default(Protocol):\n # Callback with keyword parameter with default arg value\n def __call__(self, *, path: str = ...) -> str:\n ...\n\n\nclass Proto14_NoDefault(Protocol):\n # Callback with keyword parameter with no default arg value\n def __call__(self, *, path: str) -> str:\n ...\n\n\ndef cb14_default(*, path: str = \"\") -> str:\n return \"\"\n\n\ndef cb14_no_default(*, path: str) -> str:\n return \"\"\n\n\ncb14_1: Proto14_Default = cb14_default # OK\ncb14_2: Proto14_Default = cb14_no_default # E: no default\ncb14_3: Proto14_NoDefault = cb14_default # OK\ncb14_4: Proto14_NoDefault = cb14_no_default # OK\n","source":"typing_tests","origin":"conformance/tests/callables_protocol.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_02.py","code":"\"\"\"\nTests the handling of class objects as implementations of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#type-and-class-objects-vs-protocols\n\n# > Variables and parameters annotated with Type[Proto] accept only concrete\n# (non-protocol) subtypes of Proto.\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Protocol\n\n\nclass Proto(Protocol):\n @abstractmethod\n def meth(self) -> int:\n ...\n\n\nclass Concrete:\n def meth(self) -> int:\n return 42\n\n\ndef fun(cls: type[Proto]) -> int:\n return cls().meth() # OK\n\n\nfun(Proto) # E\nfun(Concrete) # OK\n\n\nvar: type[Proto]\nvar = Proto # E\nvar = Concrete # OK\nvar().meth() # OK\n\n\n# > A class object is considered an implementation of a protocol if accessing\n# > all members on it results in types compatible with the protocol members.\n\n\nclass ProtoA1(Protocol):\n def method1(self, x: int) -> int:\n ...\n\n\nclass ProtoA2(Protocol):\n def method1(_self, self: Any, x: int) -> int:\n ...\n\n\nclass ConcreteA:\n def method1(self, x: int) -> int:\n return 0\n\n\npa1: ProtoA1 = ConcreteA # E: signatures don't match\npa2: ProtoA2 = ConcreteA # OK\n\n\nclass ProtoB1(Protocol):\n @property\n def prop1(self) -> int:\n ...\n\n\nclass ConcreteB:\n @property\n def prop1(self) -> int:\n return 0\n\n\npb1: ProtoB1 = ConcreteB # E\n\n\nclass ProtoC1(Protocol):\n attr1: ClassVar[int]\n\n\nclass ProtoC2(Protocol):\n attr1: int\n\n\nclass ConcreteC1:\n attr1: ClassVar[int] = 1\n\n\nclass ConcreteC2:\n attr1: int = 1\n\n\nclass CMeta(type):\n attr1: int\n\n def __init__(self, *args, **kwargs) -> None:\n self.attr1: int = 1\n\n\nclass ConcreteC3(metaclass=CMeta):\n pass\n\n\npc1: ProtoC1 = ConcreteC1 # E\npc2: ProtoC2 = ConcreteC1 # OK\npc3: ProtoC1 = ConcreteC2 # E\npc4: ProtoC2 = ConcreteC2 # E\npc5: ProtoC1 = ConcreteC3 # E?: Explicit ClassVar matching is unspecified\npc6: ProtoC2 = ConcreteC3 # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_class_objects.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_03.py","code":"\"\"\"\nTests the basic definition rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#defining-a-protocol\n\nfrom abc import abstractmethod\nfrom typing import Any, ClassVar, Iterable, NamedTuple, Protocol, Sequence\nfrom dataclasses import dataclass\n\n\nclass SupportsClose(Protocol):\n def close(self) -> None:\n ...\n\n\nclass Resource:\n def close(self) -> None:\n pass\n\n\ndef close_all(things: Iterable[SupportsClose]) -> None:\n for t in things:\n t.close()\n\n\nf = open(\"foo.txt\")\nr = Resource()\nclose_all([f, r]) # OK\nclose_all([1]) # E: 'int' has no 'close' method\n\n\nclass Example(Protocol):\n def first(self) -> int: # This is a protocol member\n return 42\n\n @abstractmethod\n def second(self) -> int: # Method without a default implementation\n raise NotImplementedError\n\n # > Static methods, class methods, and properties are equally allowed in protocols.\n\n @staticmethod\n def third() -> int:\n ...\n\n @classmethod\n def fourth(cls) -> int:\n ...\n\n @property\n def fifth(self) -> int:\n ...\n\n\n# > To define a protocol variable, one can use PEP 526 variable annotations\n# > in the class body. Additional attributes only defined in the body of a\n# > method by assignment via self are not allowed.\n\n\nclass Template(Protocol):\n name: str # This is a protocol member\n value: int = 0 # This one too (with default)\n\n def method(self) -> None:\n self.name = \"name\" # OK\n self.temp: list[int] = [] # E: use of self variables not allowed\n\n\nclass Concrete:\n def __init__(self, name: str, value: int) -> None:\n self.name = name\n self.value = value\n\n def method(self) -> None:\n return\n\n\nvar: Template = Concrete(\"value\", 42) # OK\n\n\n# > To distinguish between protocol class variables and protocol instance\n# > variables, the special ClassVar annotation should be used as specified\n# > by PEP 526. By default, protocol variables as defined above are considered\n# > readable and writable. To define a read-only protocol variable, one can\n# > use an (abstract) property.\n\n\nclass Template2(Protocol):\n val1: ClassVar[Sequence[int]]\n\n\nclass Concrete2_Good1:\n val1: ClassVar[Sequence[int]] = [2]\n\n\nclass Concrete2_Bad1:\n ...\n\n\nclass Concrete2_Bad2:\n val1: Sequence[float] = [2]\n\n\nclass Concrete2_Bad3:\n val1: list[int] = [2]\n\n\nclass Concrete2_Bad4:\n val1: Sequence[int] = [2]\n\n\nv2_good1: Template2 = Concrete2_Good1() # OK\nv2_bad1: Template2 = Concrete2_Bad1() # E\nv2_bad2: Template2 = Concrete2_Bad2() # E\nv2_bad3: Template2 = Concrete2_Bad3() # E\nv2_bad4: Template2 = Concrete2_Bad4() # E?: Explicit ClassVar matching is unspecified\n\n\nclass Template3(Protocol):\n val1: Sequence[int]\n\n\nclass Concrete3_Good1:\n val1: Sequence[int] = [0]\n\n\nclass Concrete3_Good2:\n def __init__(self) -> None:\n self.val1: Sequence[int] = [0]\n\n\nclass Concrete3_Bad1:\n ...\n\n\nclass Concrete3_Bad2:\n val1: ClassVar[Sequence[int]] = [0]\n\n\nclass Concrete3_Bad3:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete3_Bad4:\n val1: Sequence[float] = [0]\n\n\nclass Concrete3_Bad5:\n val1: list[int] = [0]\n\n\nv3_good1: Template3 = Concrete3_Good1() # OK\nv3_bad1: Template3 = Concrete3_Bad1() # E\nv3_bad2: Template3 = Concrete3_Bad2() # E\nv3_bad3: Template3 = Concrete3_Bad3() # E\nv3_bad4: Template3 = Concrete3_Bad4() # E\nv3_bad5: Template3 = Concrete3_Bad5() # E\n\n\nclass Template4(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n\nclass Concrete4_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete4_Good2:\n @property\n def val1(self) -> Sequence[int]:\n return [0]\n\n\nclass Concrete4_Good3:\n val1: Sequence[float] = [0]\n\n\nclass Concrete4_Good4:\n val1: Sequence[int] = [0]\n\n\nclass Concrete4_Good5:\n val1: list[float] = [0]\n\n\nclass Concrete4_Good6(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete4_Good7:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete4_Bad1:\n def val1(self) -> Sequence[int]: # Not a property\n return [0]\n\n\nclass Concrete4_Bad2:\n ...\n\n\nv4_good1: Template4 = Concrete4_Good1() # OK\nv4_good2: Template4 = Concrete4_Good2() # OK\nv4_good3: Template4 = Concrete4_Good3() # OK\nv4_good4: Template4 = Concrete4_Good4() # OK\nv4_good5: Template4 = Concrete4_Good5() # OK\nv4_good6: Template4 = Concrete4_Good6() # OK\nv4_good7: Template4 = Concrete4_Good7() # OK\nv4_bad1: Template4 = Concrete4_Bad1() # E\nv4_bad2: Template4 = Concrete4_Bad2() # E\n\n\nclass Template5(Protocol):\n def method1(self, a: int, b: int) -> float:\n ...\n\n\nclass Concrete5_Good1:\n def method1(self, a: float, b: float) -> int:\n return 0\n\n\nclass Concrete5_Good2:\n def method1(self, *args: float, **kwargs: float) -> Any:\n return 0.0\n\n\nclass Concrete5_Good3:\n def method1(self, a, b) -> Any:\n return 0.0\n\n\nclass Concrete5_Good4:\n @classmethod\n def method1(cls, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Good5:\n @staticmethod\n def method1(a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad1:\n def method1(self, a, c) -> int:\n return 0\n\n\nclass Concrete5_Bad2:\n def method1(self, a: int, c: int) -> int:\n return 0\n\n\nclass Concrete5_Bad3:\n def method1(self, *, a: int, b: int) -> float:\n return 0\n\n\nclass Concrete5_Bad4:\n def method1(self, a: int, b: int, /) -> float:\n return 0\n\n\nclass Concrete5_Bad5:\n @staticmethod\n def method1(self, a: int, b: int) -> float:\n return 0\n\n\nv5_good1: Template5 = Concrete5_Good1() # OK\nv5_good2: Template5 = Concrete5_Good2() # OK\nv5_good3: Template5 = Concrete5_Good3() # OK\nv5_good4: Template5 = Concrete5_Good4() # OK\nv5_good5: Template5 = Concrete5_Good5() # OK\nv5_bad1: Template5 = Concrete5_Bad1() # E\nv5_bad2: Template5 = Concrete5_Bad2() # E\nv5_bad3: Template5 = Concrete5_Bad3() # E\nv5_bad4: Template5 = Concrete5_Bad4() # E\nv5_bad5: Template5 = Concrete5_Bad5() # E\n\n\nclass Template6(Protocol):\n @property\n def val1(self) -> Sequence[float]:\n ...\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n ...\n\n\nclass Concrete6_Good1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n @val1.setter\n def val1(self, val: Sequence[float]) -> None:\n pass\n\n\nclass Concrete6_Good2:\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=False)\nclass Concrete6_Good3:\n val1: Sequence[float] = (0,)\n\n\nclass Concrete6_Bad1:\n @property\n def val1(self) -> Sequence[float]:\n return [0]\n\n\nclass Concrete6_Bad2(NamedTuple):\n val1: Sequence[float] = [0]\n\n\n@dataclass(frozen=True)\nclass Concrete6_Bad3:\n val1: Sequence[float] = (0,)\n\n\nv6_good1: Template6 = Concrete6_Good1() # OK\nv6_good2: Template6 = Concrete6_Good2() # OK\nv6_good3: Template6 = Concrete6_Good3() # OK\nv6_bad1: Template6 = Concrete6_Bad1() # E\nv6_bad2: Template6 = Concrete6_Bad2() # E: named tuple is immutable\nv6_bad3: Template6 = Concrete6_Bad3() # E: dataclass is frozen\n\n\n# The specification leaves two possible interpretations of a ClassVar protocol\n# member. One interpretation requires the implementing attribute to be explicitly\n# declared with ClassVar. The other interpretation imposes only structural\n# requirements: the attribute must be readable and writable on the class object\n# and readable on instances of the class. Both interpretations therefore require\n# the following assignments to be rejected.\n\n\nclass Template7(Protocol):\n val1: ClassVar[int]\n\n\nclass Concrete7_Bad1:\n def __init__(self) -> None:\n self.val1: int = 42\n\n\nclass Concrete7Meta(type):\n val1: int = 42\n\n\nclass Concrete7_Bad2(metaclass=Concrete7Meta):\n pass\n\n\nv7_bad1: Template7 = Concrete7_Bad1() # E: val1 is not readable on the class object\nv7_bad2: Template7 = Concrete7_Bad2() # E: val1 is not readable on instances\n","source":"typing_tests","origin":"conformance/tests/protocols_definition.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_04.py","code":"\"\"\"\nTests the handling of explicit protocol classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#explicitly-declaring-implementation\n\nfrom abc import ABC, abstractmethod\nfrom typing import ClassVar, Protocol\n\n\nclass PColor(Protocol):\n @abstractmethod\n def draw(self) -> str:\n ...\n\n def complex_method(self) -> int:\n return 1\n\n\nclass NiceColor(PColor):\n def draw(self) -> str:\n return \"deep blue\"\n\n\nclass BadColor(PColor):\n def draw(self) -> str:\n return super().draw() # E: no default implementation\n\n\nclass ImplicitColor: # Note no 'PColor' base here\n def draw(self) -> str:\n return \"probably gray\"\n\n def complex_method(self) -> int:\n return 0\n\n\nv1: PColor = NiceColor() # OK\nv2: PColor = ImplicitColor() # OK\n\n\nclass RGB(Protocol):\n rgb: tuple[int, int, int]\n other: int\n\n @abstractmethod\n def intensity(self) -> int:\n return 1\n\n def transparency(self) -> int:\n ...\n\n\nclass Point(RGB):\n def __init__(self, red: int, green: int, blue: str) -> None:\n self.rgb = red, green, blue # E: 'blue' must be 'int'\n self.other = 0\n\n\np = Point(0, 0, \"\") # E: Cannot instantiate abstract class\n\n\nclass Proto1(Protocol):\n cm1: ClassVar[int]\n cm2: ClassVar[int] = 0\n\n im1: int\n im2: int = 2\n im3: int\n\n def __init__(self):\n self.im3 = 3\n\n\nclass Proto2(Protocol):\n cm10: int\n\n\nclass Proto3(Proto2, Protocol):\n cm11: int\n\n\nclass Concrete1(Proto1):\n def __init__(self):\n self.im1 = 1\n self.im3 = 3\n\n\nc1 = Concrete1() # E: cannot instantiate abstract class\n\n\nclass Concrete2(Proto1):\n cm1 = 3\n im1 = 0\n\n\nc2 = Concrete2()\n\n\nclass Concrete3(Proto1, Proto3):\n cm1 = 3\n\n def __init__(self):\n self.im1 = 0\n self.cm10 = 10\n self.cm11 = 11\n\n\nc3 = Concrete3()\n\n\nclass Concrete4(Proto1, Proto3):\n cm1 = 3\n cm10 = 3\n\n def __init__(self):\n self.im1 = 3\n self.im10 = 10\n self.cm11 = 3\n\n\nc4 = Concrete4()\n\n\nclass Proto5(Protocol):\n def method1(self) -> int:\n ...\n\n\nclass Concrete5(Proto5):\n pass\n\n\nc5 = Concrete5() # E: cannot instantiate abstract class\n\n\nclass Proto6(Protocol):\n x: int\n\n\nclass Mixin:\n x = 3\n\n\nclass Concrete6(Mixin, Proto6):\n pass\n\n\nclass Proto7(Protocol):\n @abstractmethod\n def method1(self):\n ...\n\n\nclass Mixin7(Proto7, ABC):\n def method1(self) -> None:\n pass\n\n\nclass Concrete7A(Proto7):\n pass\n\n\nc7a = Concrete7A() # E: cannot instantiate abstract class\n\n\nclass Concrete7B(Mixin7, Proto7):\n pass\n\n\nc7b = Concrete7B()\n","source":"typing_tests","origin":"conformance/tests/protocols_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_05.py","code":"\"\"\"\nTests the handling of generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\n\nfrom typing import Callable, Generic, Iterator, Protocol, Self, TypeVar, assert_type\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Iterable(Protocol[T_co]):\n def __iter__(self) -> Iterator[T_co]:\n ...\n\n\n# > Protocol[T, S, ...] is allowed as a shorthand for Protocol, Generic[T, S, ...].\n# In particular, the implicit order of type parameters is dictated by\n# the order in which they appear in the `Protocol` subscript.\n\n\nclass Proto1(Iterable[T_co], Protocol[S, T_co]):\n def method1(self, x: S) -> S:\n ...\n\n\nclass Concrete1:\n def __iter__(self) -> Iterator[int]:\n return (x for x in [1, 2, 3])\n\n def method1(self, x: str) -> str:\n return \"\"\n\n\np1: Proto1[str, int] = Concrete1() # OK\np2: Proto1[int, str] = Concrete1() # E: incompatible type\n\n\n# > It is an error to combine the shorthand with Generic[T, S, ...]\nclass Proto2(Protocol[T_co], Generic[T_co]): # E\n ...\n\n\n# > User-defined generic protocols support explicitly declared variance.\nclass Box(Protocol[T_co]):\n def content(self) -> T_co:\n ...\n\n\ndef func1(box_int: Box[int], box_float: Box[float]):\n v1: Box[float] = box_int # OK\n v2: Box[int] = box_float # E\n\n\nclass Sender(Protocol[T_contra]):\n def send(self, data: T_contra) -> int:\n return 0\n\n\ndef func2(sender_int: Sender[int], sender_float: Sender[float]):\n v1: Sender[int] = sender_float # OK\n v2: Sender[float] = sender_int # E\n\n\nclass AttrProto(Protocol[T]):\n attr: T\n\n\ndef func3(attr_int: AttrProto[int], attr_float: AttrProto[float]):\n v1: AttrProto[float] = attr_int # E\n v2: AttrProto[int] = attr_float # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n# > The self-types in protocols follow the rules for other methods.\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n# > In addition, the first argument in an instance method can be annotated\n# > with a type variable. In this case the return type may use the same\n# > type variable, thus making that method a generic function.\n\n\nT_bounded = TypeVar(\"T_bounded\", bound=\"HasParent\")\n\n\nclass HasParent(Protocol):\n def get_parent(self: T_bounded) -> T_bounded:\n ...\n\n\nGenericHasParent = TypeVar(\"GenericHasParent\", bound=HasParent)\n\n\ndef generic_get_parent(n: GenericHasParent) -> GenericHasParent:\n return n.get_parent()\n\n\nclass ConcreteHasParent:\n def get_parent(self) -> Self:\n return self\n\n\nparent = generic_get_parent(ConcreteHasParent()) # OK\nassert_type(parent, ConcreteHasParent)\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > `Self` is valid within Protocols, similar to its use in classes:\n\n\nclass HasParentProperty(Protocol):\n @property\n def parent(self) -> Self:\n ...\n\n\nclass ConcreteParentProperty:\n @property\n def parent(self) -> Self:\n return self\n\n\nclass InvalidParentProperty:\n @property\n def parent(self) -> HasParentProperty:\n return ConcreteParentProperty()\n\n\nhp1: HasParentProperty = ConcreteParentProperty() # OK\nhp2: HasParentProperty = InvalidParentProperty() # E\n\n\n\nclass HasMethod(Protocol):\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n ...\n\n\nclass ConcreteHasMethod:\n def m(self, item: T, callback: Callable[[T], str]) -> str:\n return \"\"\n\n\nclass InvalidHasMethod:\n def m(self, item: int, callback: Callable[[int], str]) -> str:\n return \"\"\n\n\nhm1: HasMethod = ConcreteHasMethod() # OK\nhm2: HasMethod = InvalidHasMethod() # E\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n# > Checking a class for assignability to a protocol: If a protocol uses `Self`\n# > in methods or attribute annotations, then a class `Foo` is assignable\n# > to the protocol if its corresponding methods and attribute annotations use\n# > either `Self` or `Foo` or any of `Foo`'s subclasses.\n\n\nclass HasGreaterThan(Protocol):\n def __gt__(self, other: Self) -> bool:\n ...\n\n\nclass ConcreteGreaterThan1:\n def __gt__(self, other: Self) -> bool:\n return False\n\n\nclass ConcreteGreaterThan2:\n def __gt__(self, other: \"ConcreteGreaterThan2\") -> bool:\n return False\n\n\nclass InvalidGreaterThan:\n def __gt__(self, other: int) -> bool:\n return False\n\n\nhg1: HasGreaterThan = ConcreteGreaterThan1() # OK\nhg2: HasGreaterThan = ConcreteGreaterThan2() # OK\nhg3: HasGreaterThan = InvalidGreaterThan() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_generic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_06.py","code":"\"\"\"\nTests merging and extending of protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#merging-and-extending-protocols\n\nfrom abc import abstractmethod\nfrom typing import Protocol\nfrom collections.abc import Sized\n\n\nclass SizedAndClosable1(Sized, Protocol):\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable2(Protocol):\n def __len__(self) -> int:\n ...\n\n def close(self) -> None:\n ...\n\n\nclass SizedAndClosable3(SizedAndClosable1): # Note: not a protocol\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete1:\n def __len__(self) -> int:\n return 0\n\n def close(self) -> None:\n pass\n\n\nclass SCConcrete2:\n def close(self) -> None:\n pass\n\n\ns1: SizedAndClosable1 = SCConcrete1() # OK\ns2: SizedAndClosable2 = SCConcrete1() # OK\ns3: SizedAndClosable1 = SizedAndClosable3() # OK\ns4: SizedAndClosable2 = SizedAndClosable3() # OK\ns5: Sized = SCConcrete1() # OK\n\ns6: SizedAndClosable1 = SCConcrete2() # E: doesn't implement `__len__`\ns7: SizedAndClosable2 = SCConcrete2() # E: doesn't implement `__len__`\ns8: SizedAndClosable3 = SCConcrete2() # E: SizedAndClosable3 is not a protocol\n\n\ndef func1(s1: SizedAndClosable1, s2: SizedAndClosable2):\n # > The two definitions of SizedAndClosable are equivalent.\n v1: SizedAndClosable2 = s1\n v2: SizedAndClosable1 = s2\n\n\n# > If Protocol is included in the base class list, all the other base classes\n# > must be protocols.\n\n\nclass BadProto(SizedAndClosable3, Protocol): # E: SizedAndClosable3 is not a protocol\n ...\n\n\n# > Without this base, the class is “downgraded” to a regular ABC that\n# > cannot be used with structural subtyping.\nclass SizedAndClosable4(SizedAndClosable1):\n def __len__(self) -> int:\n return 0\n\n @abstractmethod\n def close(self) -> None:\n raise NotImplementedError\n\n\nx = SizedAndClosable4() # E: cannot instantiate abstract class\ny: SizedAndClosable4 = SCConcrete1() # E\n","source":"typing_tests","origin":"conformance/tests/protocols_merging.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_07.py","code":"\"\"\"\nTests the handling of modules as the implementation of a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#modules-as-implementations-of-protocols\n\n# > A module object is accepted where a protocol is expected if the public\n# > interface of the given module is compatible with the expected protocol.\n\nimport _protocols_modules1\nimport _protocols_modules2\nfrom typing import Protocol\n\n\nclass Options1(Protocol):\n timeout: int\n one_flag: bool\n other_flag: bool\n\n\nclass Options2(Protocol):\n timeout: str\n\n\nop1: Options1 = _protocols_modules1 # OK\nop2: Options2 = _protocols_modules1 # E\n\n\nclass Reporter1(Protocol):\n def on_error(self, x: int) -> None:\n ...\n\n def on_success(self) -> None:\n ...\n\n\nclass Reporter2(Protocol):\n def on_error(self, x: int) -> int:\n ...\n\n\nclass Reporter3(Protocol):\n def not_implemented(self, x: int) -> int:\n ...\n\n\nrp1: Reporter1 = _protocols_modules2 # OK\nrp2: Reporter2 = _protocols_modules2 # E\nrp3: Reporter3 = _protocols_modules2 # E\n","source":"typing_tests","origin":"conformance/tests/protocols_modules.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_08.py","code":"\"\"\"\nTests the handling of recursive protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#recursive-protocols\n\n\nfrom typing import Generic, Iterable, Never, Protocol, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Traversable(Protocol):\n def leaves(self) -> Iterable[\"Traversable\"]:\n ...\n\n\nclass SimpleTree:\n def leaves(self) -> list[\"SimpleTree\"]:\n return []\n\n\nroot: Traversable = SimpleTree() # OK\n\n\nclass Tree(Generic[T]):\n def leaves(self) -> list[\"Tree[T]\"]:\n return []\n\n\ndef walk(graph: Traversable) -> None:\n pass\n\n\ntree: Tree[float] = Tree()\nwalk(tree) # OK\n\n\nclass ProtoA(Protocol[T_co, T_contra]):\n def method1(self) -> \"ProtoA[T_co, T_contra]\":\n ...\n\n @classmethod\n def method2(cls, value: T_contra) -> None:\n ...\n\n\nclass ProtoB(Protocol[T_co, T_contra]):\n def method3(self) -> ProtoA[T_co, T_contra]:\n ...\n\n\nclass ImplA:\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls, value: int) -> None:\n pass\n\n\nclass ImplB:\n def method3(self) -> ImplA:\n return ImplA()\n\n def method1(self) -> Self:\n return self\n\n @classmethod\n def method2(cls: type[ProtoB[object, T]], value: list[T]) -> None:\n pass\n\n\ndef func1(x: ProtoA[Never, T]) -> T:\n raise NotImplementedError\n\n\nv1 = func1(ImplB())\nassert_type(v1, list[int])\n","source":"typing_tests","origin":"conformance/tests/protocols_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_09.py","code":"\"\"\"\nTests the handling of the @runtime_checkable decorator for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#runtime-checkable-decorator-and-narrowing-types-by-isinstance\n\n# > A protocol can be used as a second argument in isinstance() and\n# > issubclass() only if it is explicitly opt-in by @runtime_checkable decorator.\n\nfrom typing import Any, Protocol, runtime_checkable\n\n\nclass Proto1(Protocol):\n name: str\n\n\n@runtime_checkable\nclass Proto2(Protocol):\n name: str\n\n\ndef func1(a: Any):\n if isinstance(a, Proto1): # E: not runtime_checkable\n return\n\n if isinstance(a, Proto2): # OK\n return\n\n\n# > isinstance() can be used with both data and non-data protocols, while\n# > issubclass() can be used only with non-data protocols.\n\n\n@runtime_checkable\nclass DataProtocol(Protocol):\n name: str\n\n def method1(self) -> int:\n ...\n\n\n@runtime_checkable\nclass NonDataProtocol(Protocol):\n def method1(self) -> int:\n ...\n\n\ndef func2(a: Any):\n if isinstance(a, DataProtocol): # OK\n return\n\n if isinstance(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, DataProtocol): # E\n return\n\n if issubclass(a, NonDataProtocol): # OK\n return\n\n if issubclass(a, (NonDataProtocol, DataProtocol)): # E\n return\n\n\n# > Type checkers should reject an isinstance() or issubclass() call if there\n# > is an unsafe overlap between the type of the first argument and the protocol.\n\n\n@runtime_checkable\nclass Proto3(Protocol):\n def method1(self, a: int) -> int:\n ...\n\n\nclass Concrete3A:\n def method1(self, a: str) -> None:\n pass\n\n\nclass Concrete3B:\n method1: int = 1\n\n\ndef func3():\n if isinstance(Concrete3A(), Proto2): # OK\n pass\n\n if isinstance(Concrete3A(), Proto3): # E: unsafe overlap\n pass\n\n if isinstance(Concrete3B(), (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n\n if issubclass(Concrete3A, (Proto3, NonDataProtocol)): # E: unsafe overlap\n pass\n","source":"typing_tests","origin":"conformance/tests/protocols_runtime_checkable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_10.py","code":"\"\"\"\nTests the handling of annotated \"self\" parameters in a protocol.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#self-types-in-protocols\n\nfrom typing import Generic, Protocol, Self, TypeVar\n\n\nC = TypeVar(\"C\", bound=\"Copyable\")\n\n\nclass Copyable(Protocol):\n def copy(self: C) -> C:\n return self\n\n\nclass One:\n def copy(self) -> \"One\":\n return One()\n\n\nT = TypeVar(\"T\", bound=\"Other\")\n\n\nclass Other:\n def copy(self: T) -> T:\n return self\n\n\nc: Copyable\nc = One() # OK\nc = Other() # OK\n\n\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT2_co = TypeVar(\"T2_co\", covariant=True)\n\n\nclass P1Parent(Protocol[T2_co]):\n def f0(self, /) -> Self:\n ...\n\n\nclass P1Child(P1Parent[T2_co], Protocol[T2_co]):\n ...\n\n\nclass C1(Generic[T1_co]):\n def f0(self, /) -> Self:\n return self\n\n\na1: P1Parent[str] = C1[str]()\nb1: P1Child[str] = C1[str]()\n\n\nclass P2Parent(Protocol[T1_co]):\n def f0(self, right: Self, /) -> \"P2Parent[T1_co]\":\n return right\n\n\nclass P2Child(P2Parent[T1_co], Protocol[T1_co]):\n ...\n\n\nclass C2(Generic[T2_co]):\n def f0(self, other: Self) -> \"C2[T2_co]\":\n return other\n\n\na2: P2Parent[str] = C2[str]() # OK\nb2: P2Child[str] = C2[str]() # OK\n","source":"typing_tests","origin":"conformance/tests/protocols_self.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_11.py","code":"\"\"\"\nTests subtyping rules for protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#subtyping-relationships-with-other-types\n\n# > Protocols cannot be instantiated.\n\nfrom typing import Hashable, Iterable, Protocol, Sequence, TypeVar\n\n\nclass Proto1(Protocol):\n pass\n\n\np1 = Proto1() # E: protocol cannot be instantiated\n\n\n# > A protocol is never a subtype of a concrete type.\n\n# > A concrete type X is a subtype of protocol P if and only if X implements\n# > all protocol members of P with compatible types. In other words, subtyping\n# > with respect to a protocol is always structural.\n\n\nclass Proto2(Protocol):\n def method1(self) -> None:\n ...\n\n\nclass Concrete2:\n def method1(self) -> None:\n pass\n\n\ndef func1(p2: Proto2, c2: Concrete2):\n v1: Proto2 = c2 # OK\n v2: Concrete2 = p2 # E\n\n\n# > A protocol P1 is a subtype of another protocol P2 if P1 defines all\n# > protocol members of P2 with compatible types.\n\n\nclass Proto3(Protocol):\n def method1(self) -> None:\n ...\n\n def method2(self) -> None:\n ...\n\n\ndef func2(p2: Proto2, p3: Proto3):\n v1: Proto2 = p3 # OK\n v2: Proto3 = p2 # E\n\n\n# > Generic protocols follow the rules for generic abstract classes, except\n# > for using structural compatibility instead of compatibility defined by\n# > inheritance relationships.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\n\n\nclass Proto4(Protocol[S, T]):\n def method1(self, a: S, b: T) -> tuple[S, T]:\n ...\n\n\nclass Proto5(Protocol[T]):\n def method1(self, a: T, b: T) -> tuple[T, T]:\n ...\n\n\ndef func3(p4_int: Proto4[int, int], p5_int: Proto5[int]):\n v1: Proto4[int, int] = p5_int # OK\n v2: Proto5[int] = p4_int # OK\n v3: Proto4[int, float] = p5_int # E\n v4: Proto5[float] = p4_int # E\n\n\nS_co = TypeVar(\"S_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass Proto6(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\nclass Proto7(Protocol[S_co, T_contra]):\n def method1(self, a: T_contra) -> Sequence[S_co]:\n ...\n\n\ndef func4(p6: Proto6[float, float]):\n v1: Proto7[object, int] = p6 # OK\n v2: Proto7[float, float] = p6 # OK\n v3: Proto7[complex, int] = p6 # OK\n\n v4: Proto7[int, float] = p6 # E\n v5: Proto7[float, object] = p6 # E\n\n\n# > Unions of protocol classes behaves the same way as for non-protocol classes.\n\n\nclass SupportsExit(Protocol):\n def exit(self) -> int:\n ...\n\n\nclass SupportsQuit(Protocol):\n def quit(self) -> int | None:\n ...\n\n\ndef finish(task: SupportsExit | SupportsQuit) -> int:\n return 0\n\n\nclass DefaultJob:\n def quit(self) -> int:\n return 0\n\n\nfinish(DefaultJob()) # OK\n\n\n# > One can use multiple inheritance to define an intersection of protocols.\n\n\nclass HashableFloats(Iterable[float], Hashable, Protocol):\n pass\n\n\ndef cached_func(args: HashableFloats) -> float:\n return 0.0\n\n\ncached_func((1, 2, 3)) # OK, tuple is both hashable and iterable\n","source":"typing_tests","origin":"conformance/tests/protocols_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"protocol","pep":"544","introduced_in":"3.8","form":"modern","file":"protocol/modern_12.py","code":"\"\"\"\nTests type variable variance inference for generic protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/protocol.html#generic-protocols\n\nfrom typing import Protocol, TypeVar\nfrom typing_extensions import ParamSpec\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\", bound=int)\nT3 = TypeVar(\"T3\", bytes, str)\nT1_co = TypeVar(\"T1_co\", covariant=True)\nT1_contra = TypeVar(\"T1_contra\", contravariant=True)\nP = ParamSpec(\"P\", contravariant=True)\nR = TypeVar(\"R\", covariant=True)\n\n# > Type checkers will warn if the inferred variance is different from the\n# > declared variance.\n\n\nclass AnotherBox(Protocol[T1]): # E: T should be covariant\n def content(self) -> T1:\n ...\n\n\nclass Protocol1(Protocol[T1, T2, T3]): # OK\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1 | T2:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n def m4(self) -> T3:\n ...\n\n\nclass Protocol2(Protocol[T1, T2, T3]): # E: T3 should be contravariant\n def m1(self, p0: T1, p1: T2, p2: T3) -> T1:\n ...\n\n def m2(self) -> T1:\n ...\n\n def m3(self) -> T2:\n ...\n\n\nclass Protocol3(Protocol[T1_co]):\n def m1(self) -> None:\n pass\n\n\nclass Protocol4(Protocol[T1]): # E: T1 should be contravariant\n def m1(self, p0: T1) -> None:\n ...\n\n\nclass Protocol5(Protocol[T1_co]): # E[covariant_in_input+]\n def m1(self, p0: T1_co) -> None: # E[covariant_in_input+]\n ...\n\n\nclass Protocol6(Protocol[T1]): # E: T1 should be covariant\n def m1(self) -> T1:\n ...\n\n\nclass Protocol7(Protocol[T1_contra]): # E[contravariant_in_output+]\n def m1(self) -> T1_contra: # E[contravariant_in_output+]\n ...\n\n\nclass Protocol8(Protocol[T1]): # OK\n def m1(self) -> T1:\n ...\n\n def m2(self, p1: T1) -> None:\n pass\n\n\nclass Callback(Protocol[P, R]): # OK\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> R:\n ...\n\n\nclass Protocol9(Protocol[T1_co]): # OK\n @property\n def prop1(self) -> T1_co:\n ...\n\n\nclass Protocol10(Protocol[T1_co]): # OK\n def m1(self) -> type[T1_co]:\n ...\n\n\nclass Protocol11(Protocol[T1]): # OK\n x: T1 | None\n\n\nclass Protocol12(Protocol[T1]): # E: T1 should be covariant\n # __init__ method is exempt from variance calculations.\n def __init__(self, x: T1) -> None:\n ...\n\n\nclass Protocol13(Protocol[T1_contra]): # OK\n def m1(self: \"Protocol13[T1_contra]\", x: T1_contra) -> None:\n ...\n\n @classmethod\n def m2(cls: \"type[Protocol13[T1_contra]]\") -> None:\n ...\n\n\nclass Protocol14(Protocol[T1]): # OK\n def m1(self) -> list[T1]:\n ...\n","source":"typing_tests","origin":"conformance/tests/protocols_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_01.py","code":"\"\"\"\nTests typing.ReadOnly qualifier introduced in PEP 705.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Annotated, NotRequired, Required, TypedDict\nfrom typing_extensions import ReadOnly\n\n\n# > The ``typing.ReadOnly`` type qualifier is used to indicate that an item\n# > declared in a ``TypedDict`` definition may not be mutated (added, modified,\n# > or removed).\n\n\nclass Band(TypedDict):\n name: str\n members: ReadOnly[list[str]]\n\n\nb1: Band = {\"name\": \"blur\", \"members\": []}\n\nb1[\"name\"] = \"Blur\" # OK\nb1[\"members\"] = [\"Damon Albarn\"] # E\nb1[\"members\"].append(\"Damon Albarn\") # OK\n\n\n# > The :pep:`alternative functional syntax <589#alternative-syntax>` for\n# > TypedDict also supports the new type qualifier.\n\nBand2 = TypedDict(\"Band2\", {\"name\": str, \"members\": ReadOnly[list[str]]})\n\nb2: Band2 = {\"name\": \"blur\", \"members\": []}\n\nb2[\"name\"] = \"Blur\" # OK\nb2[\"members\"] = [\"Damon Albarn\"] # E\nb2[\"members\"].append(\"Damon Albarn\") # OK\n\n\n# > ``ReadOnly[]`` can be used with ``Required[]``, ``NotRequired[]`` and\n# > ``Annotated[]``, in any nesting order.\n\n\nclass Movie1(TypedDict):\n title: ReadOnly[Required[str]] # OK\n year: ReadOnly[NotRequired[Annotated[int, \"\"]]] # OK\n\n\nm1: Movie1 = {\"title\": \"\", \"year\": 1991}\nm1[\"title\"] = \"\" # E\nm1[\"year\"] = 1992 # E\n\n\nclass Movie2(TypedDict):\n title: Required[ReadOnly[str]] # OK\n year: Annotated[NotRequired[ReadOnly[int]], \"\"] # OK\n\n\nm2: Movie2 = {\"title\": \"\", \"year\": 1991}\nm2[\"title\"] = \"\" # E\nm2[\"year\"] = 1992 # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_02.py","code":"\"\"\"\nTests type consistency rules for TypedDict with ReadOnly items.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Any, Collection, NotRequired, Required, TypedDict\nfrom typing_extensions import ReadOnly\n\n# > A TypedDict type ``A`` is consistent with TypedDict ``B`` if ``A`` is\n# > structurally compatible with ``B``. This is true if and only if all of\n# > the following are satisfied:\n\n# > For each item in ``B``, ``A`` has the corresponding key, unless the item\n# > in ``B`` is read-only, not required, and of top value type\n# > (``ReadOnly[NotRequired[object]]``).\n\n\nclass A1(TypedDict):\n x: Required[int]\n\n\nclass B1(TypedDict):\n x: Required[int]\n y: NotRequired[str]\n\n\nclass C1(TypedDict):\n x: Required[int]\n y: ReadOnly[NotRequired[str]]\n\n\ndef func1(a: A1, b: B1, c: C1):\n v1: A1 = b # OK\n v2: A1 = c # OK\n\n v3: B1 = a # E\n v4: B1 = c # E\n\n v5: C1 = a # E\n v6: C1 = b # OK\n\n\n# > For each item in ``B``, if ``A`` has the corresponding key, the\n# > corresponding value type in ``A`` is consistent with the value type in ``B``.\n\n# (This is the same rule that applies to TypedDicts without read-only items,\n# so we will skip this redundant test.)\n\n# > For each non-read-only item in ``B``, its value type is consistent with\n# > the corresponding value type in ``A``.\n\n# (This is the same rule that applies to TypedDicts without read-only items,\n# so we will skip this redundant test.)\n\n# > For each required key in ``B``, the corresponding key is required in ``A``.\n\n# (This is the same rule that applies to TypedDicts without read-only items,\n# so we will skip this redundant test.)\n\n# > For each non-required key in ``B``, if the item is not read-only in ``B``,\n# > the corresponding key is not required in ``A``.\n\n\nclass A2(TypedDict):\n x: NotRequired[ReadOnly[str]]\n\n\nclass B2(TypedDict):\n x: NotRequired[str]\n\n\nclass C2(TypedDict):\n x: Required[str]\n\n\ndef func2(a: A2, b: B2, c: C2):\n v1: A2 = b # OK\n v2: A2 = c # OK\n\n v3: B2 = a # E\n v4: B2 = c # E\n\n v5: C2 = a # E\n v6: C2 = b # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_03.py","code":"\"\"\"\nTests inheritance rules involving typing.ReadOnly.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Collection, NotRequired, Required, TypedDict\nfrom typing_extensions import ReadOnly\n\n# > Subclasses can redeclare read-only items as non-read-only, allowing them\n# > to be mutated.\n\n\nclass NamedDict(TypedDict):\n name: ReadOnly[str]\n\n\nclass Album1(NamedDict):\n name: str\n year: int\n\n\na1: Album1 = {\"name\": \"Flood\", \"year\": 1990}\na1[\"year\"] = 1973 # OK\na1[\"name\"] = \"Dark Side Of The Moon\" # OK\n\n\n# > If a read-only item is not redeclared, it remains read-only.\n\n\nclass Album2(NamedDict):\n year: int\n\n\na2: Album2 = {\"name\": \"Flood\", \"year\": 1990}\na2[\"name\"] = \"Dark Side Of The Moon\" # E\n\n\n# > Subclasses can narrow value types of read-only items.\n\n\nclass AlbumCollection(TypedDict):\n albums: ReadOnly[Collection[Album1]]\n alt: ReadOnly[list[str | int]]\n\n\nclass RecordShop(AlbumCollection):\n name: str\n albums: ReadOnly[list[Album1]] # OK\n alt: ReadOnly[list[str]] # E\n\n\n# > Subclasses can require items that are read-only but not required in the\n# > superclass.\n\n\nclass OptionalName(TypedDict):\n name: ReadOnly[NotRequired[str]]\n\n\nclass RequiredName(OptionalName):\n name: ReadOnly[Required[str]] # OK\n\n\nd: RequiredName = {} # E\n\n\n# > Subclasses can combine these rules.\n\n\nclass OptionalIdent(TypedDict):\n ident: ReadOnly[NotRequired[str | int]]\n\n\nclass User(OptionalIdent):\n ident: str # Required, mutable, and not an int\n\n\nu: User\nu = {\"ident\": \"\"} # OK\nu[\"ident\"] = \"\" # OK\nu[\"ident\"] = 3 # E\nu = {\"ident\": 3} # E\nu = {} # E\n\n\nclass F1(TypedDict):\n a: Required[int]\n b: ReadOnly[NotRequired[int]]\n c: ReadOnly[Required[int]]\n\n\nclass F3(F1):\n a: ReadOnly[int] # E\n\n\nclass F4(F1):\n a: NotRequired[int] # E\n\n\nclass F5(F1):\n b: ReadOnly[Required[int]] # OK\n\n\nclass F6(F1):\n c: ReadOnly[NotRequired[int]] # E\n\n\nclass TD_A1(TypedDict):\n x: int\n y: ReadOnly[int]\n\n\nclass TD_A2(TypedDict):\n x: float\n y: ReadOnly[float]\n\n\nclass TD_A(TD_A1, TD_A2): ... # E: x is incompatible\n\n\nclass TD_B1(TypedDict):\n x: ReadOnly[NotRequired[int]]\n y: ReadOnly[Required[int]]\n\n\nclass TD_B2(TypedDict):\n x: ReadOnly[Required[int]]\n y: ReadOnly[NotRequired[int]]\n\n\nclass TD_B(TD_B1, TD_B2): ... # E: x is incompatible\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_04.py","code":"\"\"\"\nTests the use of unpacked TypedDicts with read-only items when used to annotate\na **kwargs parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Protocol, TypedDict, Unpack\nfrom typing_extensions import ReadOnly\n\n# > :pep:`692` introduced ``Unpack`` to annotate ``**kwargs`` with a\n# > ``TypedDict``. Marking one or more of the items of a ``TypedDict`` used\n# > in this way as read-only will have no effect on the type signature of\n# > the method. However, it *will* prevent the item from being modified in\n# > the body of the function.\n\n\nclass Args(TypedDict):\n key1: int\n key2: str\n\n\nclass ReadOnlyArgs(TypedDict):\n key1: ReadOnly[int]\n key2: ReadOnly[str]\n\n\nclass Function(Protocol):\n def __call__(self, **kwargs: Unpack[Args]) -> None: ...\n\n\ndef impl(**kwargs: Unpack[ReadOnlyArgs]) -> None:\n kwargs[\"key1\"] = 3 # E\n\n\nfn: Function = impl # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"readonly-items","pep":"705","introduced_in":"3.13","form":"modern","file":"readonly-items/modern_05.py","code":"\"\"\"\nTests inheritance rules involving the update method for TypedDicts\nthat contain read-only items.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Never, NotRequired, TypedDict\nfrom typing_extensions import ReadOnly\n\n# > In addition to existing type checking rules, type checkers should error if\n# > a TypedDict with a read-only item is updated with another TypedDict that\n# > declares that key.\n\n\nclass A(TypedDict):\n x: ReadOnly[int]\n y: int\n\n\na1: A = {\"x\": 1, \"y\": 2}\na2: A = {\"x\": 3, \"y\": 4}\na1.update(a2) # E\n\n# > Unless the declared value is of bottom type (:data:`~typing.Never`).\n\n\nclass B(TypedDict):\n x: NotRequired[Never]\n y: ReadOnly[int]\n\n\ndef update_a(a: A, b: B) -> None:\n a.update(b) # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_update.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"required-notrequired","pep":"655","introduced_in":"3.11","form":"modern","file":"required-notrequired/modern_01.py","code":"\"\"\"\nTests the Required and NotRequired special forms.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#required-and-notrequired\n\nfrom typing import Annotated, NotRequired, Required, TypedDict\n\n\n# Required and NotRequired are valid only within a TypedDict.\nclass NotTypedDict:\n x: Required[int] # E: Required not allowed in this context\n\n\ndef func1(\n x: NotRequired[int], # E: NotRequired not allowed in this context\n) -> None:\n pass\n\n\nclass TD1(TypedDict, total=False):\n a: int\n\n\nclass TD2(TD1, total=True):\n b: int\n\n\nclass TD3(TypedDict):\n a: NotRequired[int]\n b: Required[int]\n\n\nclass TD4(TypedDict, total=False):\n a: int\n b: Required[int]\n\n\nclass TD5(TypedDict, total=True):\n a: NotRequired[int]\n b: int\n\n\ntd3: TD3 = {\"b\": 0}\ntd4: TD4 = {\"b\": 0}\ntd5: TD5 = {\"b\": 0}\n\n# These are all equivalent types, so they should be\n# bidirectionally type compatible.\ntd3 = td4\ntd3 = td5\ntd4 = td3\ntd4 = td5\ntd5 = td3\ntd5 = td4\n\n\nclass TD6(TypedDict):\n a: Required[Required[int]] # E: Nesting not allowed\n b: Required[NotRequired[int]] # E: Nesting not allowed\n\n\nclass TD7(TypedDict):\n # > Required[] and NotRequired[] can be used with Annotated[], in any nesting order.\n x: Annotated[Required[int], \"\"]\n y: Required[Annotated[int, \"\"]]\n z: Annotated[Required[Annotated[int, \"\"]], \"\"]\n\n\nRecursiveMovie = TypedDict(\n \"RecursiveMovie\", {\"title\": Required[str], \"predecessor\": NotRequired[\"RecursiveMovie\"]}\n)\n\nmovie: RecursiveMovie = {\"title\": \"Beethoven 3\", \"predecessor\": {\"title\": \"Beethoven 2\"}}\n","source":"typing_tests","origin":"conformance/tests/typeddicts_required.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_01.py","code":"\"\"\"\nTests for advanced or special-case usage of the typing.Self type.\n\"\"\"\n\nfrom typing import assert_type, Self\n\n\nclass ParentA:\n # Test for property that returns Self.\n @property\n def prop1(self) -> Self:\n raise NotImplementedError\n\nclass ChildA(ParentA):\n ...\n\n\nassert_type(ParentA().prop1, ParentA)\nassert_type(ChildA().prop1, ChildA)\n\n\n# Test for a child that accesses an attribute within a parent\n# whose type is annotated using Self.\nclass ParentB:\n a: list[Self]\n\n @classmethod\n def method1(cls) -> Self:\n raise NotImplementedError\n\nclass ChildB(ParentB):\n b: int = 0\n\n def method2(self) -> None:\n assert_type(self, Self)\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = self.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(self.method1(), Self)\n\n @classmethod\n def method3(cls) -> None:\n assert_type(cls, type[Self])\n # Allow type checkers to error here, since Self definitions on\n # non-final classes are unsound.\n a = cls.a # E?\n assert_type(a, list[Self])\n assert_type(a[0], Self)\n assert_type(cls.method1(), Self)\n","source":"typing_tests","origin":"conformance/tests/generics_self_advanced.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_02.py","code":"\"\"\"\nTests for usage of the typing.Self type with attributes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-attribute-annotations\n\nfrom typing import TypeVar, Generic, Self\nfrom dataclasses import dataclass\n\n\nT = TypeVar(\"T\")\n\n@dataclass\nclass LinkedList(Generic[T]):\n value: T\n next: Self | None = None\n\n\n@dataclass\nclass OrdinalLinkedList(LinkedList[int]):\n def ordinal_value(self) -> str:\n return str(self.value)\n\n\n# This should result in a type error.\nxs = OrdinalLinkedList(value=1, next=LinkedList[int](value=2)) # E\n\nif xs.next is not None:\n xs.next = OrdinalLinkedList(value=3, next=None) # OK\n\n # This should result in a type error.\n xs.next = LinkedList[int](value=3, next=None) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_attributes.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_03.py","code":"\"\"\"\nTests for basic usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#self.\n\nfrom typing import Callable, Generic, Self, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n\nclass Shape:\n def set_scale(self, scale: float) -> Self:\n assert_type(self, Self)\n self.scale = scale\n return self\n\n def method2(self) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n def method3(self) -> \"Shape\":\n return self\n\n @classmethod\n def from_config(cls, config: dict[str, float]) -> Self:\n assert_type(cls, type[Self])\n return cls()\n\n @classmethod\n def cls_method2(cls) -> Self:\n # This should result in a type error.\n return Shape() # E\n\n @classmethod\n def cls_method3(cls) -> \"Shape\":\n return cls()\n\n def difference(self, other: Self) -> float:\n assert_type(other, Self)\n return 0.0\n\n def apply(self, f: Callable[[Self], None]) -> None:\n return f(self)\n\n\nclass Circle(Shape):\n pass\n\n\nassert_type(Shape().set_scale(1.0), Shape)\nassert_type(Circle().set_scale(1.0), Circle)\n\nassert_type(Shape.from_config({}), Shape)\nassert_type(Circle.from_config({}), Circle)\n\n\nclass Container(Generic[T]):\n value: T\n\n def __init__(self, value: T) -> None:\n self.value = value\n\n def set_value(self, value: T) -> Self:\n raise NotImplementedError\n\n # This should generate an error because Self isn't subscriptable.\n def foo(self, other: Self[int]) -> None: # E\n pass\n\n\ndef object_with_concrete_type(\n int_container: Container[int], str_container: Container[str]\n) -> None:\n assert_type(int_container.set_value(42), Container[int])\n assert_type(str_container.set_value(\"hello\"), Container[str])\n\n\ndef object_with_generic_type(\n container: Container[T],\n value: T,\n) -> Container[T]:\n val = container.set_value(value)\n assert_type(val, Container[T])\n return val\n","source":"typing_tests","origin":"conformance/tests/generics_self_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_04.py","code":"\"\"\"\nTests for usage of the typing.Self type with protocols.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#use-in-protocols\n\nfrom typing import Protocol, Self, assert_type\n\n\nclass ShapeProtocol(Protocol):\n def set_scale(self, scale: float) -> Self:\n ...\n\n\nclass ReturnSelf:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> Self:\n self.scale = scale\n return self\n\n\nclass ReturnConcreteShape:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> \"ReturnConcreteShape\":\n self.scale = scale\n return self\n\n\nclass BadReturnType:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> int:\n self.scale = scale\n return 42\n\n\nclass ReturnDifferentClass:\n scale: float = 1.0\n\n def set_scale(self, scale: float) -> ReturnConcreteShape:\n return ReturnConcreteShape()\n\n\ndef accepts_shape(shape: ShapeProtocol) -> None:\n y = shape.set_scale(0.5)\n assert_type(y, ShapeProtocol)\n\n\ndef main(\n return_self_shape: ReturnSelf,\n return_concrete_shape: ReturnConcreteShape,\n bad_return_type: BadReturnType,\n return_different_class: ReturnDifferentClass,\n) -> None:\n accepts_shape(return_self_shape) # OK\n accepts_shape(return_concrete_shape) # OK\n\n # This should generate a type error.\n accepts_shape(bad_return_type) # E\n\n # Not OK because it returns a non-subclass.\n accepts_shape(return_different_class) # E\n","source":"typing_tests","origin":"conformance/tests/generics_self_protocols.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"self-type","pep":"673","introduced_in":"3.11","form":"modern","file":"self-type/modern_05.py","code":"\"\"\"\nTests for valid and invalid usage of the typing.Self type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#valid-locations-for-self\n\nfrom typing import Any, Callable, Generic, Self, TypeAlias, TypeVar\n\nclass ReturnsSelf:\n def foo(self) -> Self: # Accepted\n return self\n\n @classmethod\n def bar(cls) -> Self: # Accepted\n return cls(1)\n\n def __new__(cls, value: int) -> Self: # Accepted\n return cls(1)\n\n def explicitly_use_self(self: Self) -> Self: # Accepted\n return self\n\n # Accepted (Self can be nested within other types)\n def returns_list(self) -> list[Self]:\n return []\n\n # Accepted (Self can be nested within other types)\n @classmethod\n def return_cls(cls) -> type[Self]:\n return cls\n\nclass Child(ReturnsSelf):\n # Accepted (we can override a method that uses Self annotations)\n def foo(self) -> Self:\n return self\n\nclass TakesSelf:\n def foo(self, other: Self) -> bool: # Accepted\n return True\n\nclass Recursive:\n # Accepted (treated as an @property returning ``Self | None``)\n next: Self | None\n\nclass CallableAttribute:\n def foo(self) -> int:\n return 0\n\n # Accepted (treated as an @property returning the Callable type)\n bar: Callable[[Self], int] = foo\n\nclass HasNestedFunction:\n x: int = 42\n\n def foo(self) -> None:\n\n # Accepted (Self is bound to HasNestedFunction).\n def nested(z: int, inner_self: Self) -> Self:\n print(z)\n print(inner_self.x)\n return inner_self\n\n nested(42, self) # OK\n\n\nclass Outer:\n class Inner:\n def foo(self) -> Self: # Accepted (Self is bound to Inner)\n return self\n\n\n# This should generate an error.\ndef foo(bar: Self) -> Self: ... # E: not within a class\n\n# This should generate an error.\nbar: Self # E: not within a class\n\nTFoo2 = TypeVar(\"TFoo2\", bound=\"Foo2\")\n\nclass Foo2:\n # Rejected (Self is treated as unknown).\n def has_existing_self_annotation(self: TFoo2) -> Self: # E\n raise NotImplementedError\n\nclass Foo3:\n def return_concrete_type(self) -> Self:\n return Foo3() # E (see FooChild below for rationale)\n\nclass Foo3Child(Foo3):\n child_value: int = 42\n\n def child_method(self) -> None:\n y = self.return_concrete_type()\n y.child_value\n\nT = TypeVar(\"T\")\n\nclass Bar(Generic[T]):\n def bar(self) -> T:\n raise NotImplementedError\n\n# This should generate an error.\nclass Baz(Bar[Self]): ... # E\n\nclass Baz2(Self): ... # E\n\n# This should generate an error.\nTupleSelf: TypeAlias = tuple[Self] # E\n\nclass Base:\n @staticmethod\n # This should generate an error.\n def make() -> Self: # E\n raise NotImplementedError\n\n @staticmethod\n # This should generate an error.\n def return_parameter(foo: Self) -> Self: # E\n raise NotImplementedError\n\nclass MyMetaclass(type):\n # This should generate an error.\n def __new__(cls, *args: Any) -> Self: # E\n raise NotImplementedError\n\n # This should generate an error.\n def __mul__(cls, count: int) -> list[Self]: # E\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_self_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"sentinel","pep":"661","introduced_in":"3.15","form":"modern","file":"sentinel/modern_02.py","code":"from typing_extensions import Sentinel, assert_type\n\n# > Sentinel objects may be used in type annotations if they are defined using\n# > a simple assignment of the form ``NAME = sentinel('NAME')`` in the\n# > global scope or in a class body that is not within a function.\n\nMISSING = Sentinel(\"\") # name is not required to match the variable name\nSPECIAL = Sentinel(\"SPECIAL\")\n\nclass Cls:\n IN_CLASS = Sentinel(\"Cls.IN_CLASS\")\n\n\ndef func1(x: int = MISSING) -> None: # E: incompatible default\n pass\n\n# > Type checkers must support narrowing union types involving sentinels using the\n# > ``is`` and ``is not`` operators\n\ndef func2(x: int | MISSING | SPECIAL = MISSING) -> None:\n if x is MISSING:\n assert_type(x, MISSING)\n else:\n assert_type(x, int | SPECIAL)\n\ndef func3(x: int | Cls.IN_CLASS = Cls.IN_CLASS) -> None:\n if x is Cls.IN_CLASS:\n assert_type(x, Cls.IN_CLASS)\n else:\n assert_type(x, int)\n\n\nfunc2(1) # ok\nfunc2(MISSING) # ok\nfunc2(SPECIAL) # ok\nfunc2(Cls.IN_CLASS) # E: incompatible argument\n\nfunc3(1) # ok\nfunc3(MISSING) # E: incompatible argument\nfunc3(Cls.IN_CLASS) # ok\n","source":"typing_tests","origin":"conformance/tests/specialtypes_sentinels.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_01.py","code":"\"\"\"\nTests explicit type aliases defined with `TypeAlias`.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#typealias\n\nfrom typing import Any, Callable, Concatenate, Literal, ParamSpec, TypeVar, Union, assert_type\nfrom typing import TypeAlias as TA\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1: TA = Union[int, str]\nGoodTypeAlias2: TA = int | None\nGoodTypeAlias3: TA = list[GoodTypeAlias2]\nGoodTypeAlias4: TA = list[T]\nGoodTypeAlias5: TA = tuple[T, ...] | list[T]\nGoodTypeAlias6: TA = tuple[int, int, S, T]\nGoodTypeAlias7: TA = Callable[..., int]\nGoodTypeAlias8: TA = Callable[[int, T], T]\nGoodTypeAlias9: TA = Callable[Concatenate[int, P], R]\nGoodTypeAlias10: TA = Any\nGoodTypeAlias11: TA = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12: TA = Callable[P, None]\nGoodTypeAlias13: TA = \"int | str\"\nGoodTypeAlias14: TA = list[\"int | str\"]\nGoodTypeAlias15: TA = Literal[3, 4, 5, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12,\n p13: GoodTypeAlias13,\n p14: GoodTypeAlias14,\n p15: GoodTypeAlias15,\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, Callable[..., None])\n assert_type(p13, int | str)\n assert_type(p14, list[int | str])\n assert_type(p15, Literal[3, 4, 5, None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be allowed as type aliases.\nBadTypeAlias1: TA = eval(\"\".join(map(chr, [105, 110, 116]))) # E\nBadTypeAlias2: TA = [int, str] # E\nBadTypeAlias3: TA = ((int, str),) # E\nBadTypeAlias4: TA = [int for i in range(1)] # E\nBadTypeAlias5: TA = {\"a\": \"b\"} # E\nBadTypeAlias6: TA = (lambda: int)() # E\nBadTypeAlias7: TA = [int][0] # E\nBadTypeAlias8: TA = int if 1 < 3 else str # E\nBadTypeAlias9: TA = var1 # E\nBadTypeAlias10: TA = True # E\nBadTypeAlias11: TA = 1 # E\nBadTypeAlias12: TA = list or set # E\nBadTypeAlias13: TA = f\"{'int'}\" # E\n\n\nListAlias: TA = list\nListOrSetAlias: TA = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2: ListAlias[int] # E: already specialized\nx3 = ListOrSetAlias() # E: cannot instantiate union\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_explicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-alias","pep":"613","introduced_in":"3.10","form":"modern","file":"type-alias/modern_02.py","code":"\"\"\"\nTests recursive (self-referential) type aliases.\n\"\"\"\n\n# The typing specification doesn't mandate support for recursive\n# (self-referential) type aliases prior to PEP 695, but it also\n# doesn't indicates that they shouldn't work.\n# Most type checkers now support them, and many libraries and code\n# bases have started to rely on them.\n# PEP 695 formally mandates that recursive type aliases work.\n\nfrom typing import Mapping, TypeAlias, TypeVar, Union\n\nJson = Union[None, int, str, float, list[\"Json\"], dict[str, \"Json\"]]\n\nj1: Json = [1, {\"a\": 1}] # OK\nj2: Json = 3.4 # OK\nj3: Json = [1.2, None, [1.2, [\"\"]]] # OK\nj4: Json = {\"a\": 1, \"b\": 3j} # E: incompatible type\nj5: Json = [2, 3j] # E: incompatible type\n\n\n# This type alias should be equivalent to Json.\nJson2 = Union[None, int, str, float, list[\"Json2\"], dict[str, \"Json2\"]]\n\ndef func1(j1: Json) -> Json2:\n return j1\n\n\nRecursiveTuple = str | int | tuple[\"RecursiveTuple\", ...]\n\n\nt1: RecursiveTuple = (1, 1) # OK\nt2: RecursiveTuple = (1, \"1\") # OK\nt3: RecursiveTuple = (1, \"1\", 1, \"2\") # OK\nt4: RecursiveTuple = (1, (\"1\", 1), \"2\") # OK\nt5: RecursiveTuple = (1, (\"1\", 1), (1, (1, 2))) # OK\nt6: RecursiveTuple = (1, (\"1\", 1), (1, (1, [2]))) # E\nt7: RecursiveTuple = (1, [1]) # E\n\n\nRecursiveMapping = str | int | Mapping[str, \"RecursiveMapping\"]\n\nm1: RecursiveMapping = 1 # OK\nm2: RecursiveMapping = \"1\" # OK\nm3: RecursiveMapping = {\"1\": \"1\"} # OK\nm4: RecursiveMapping = {\"1\": \"1\", \"2\": 1} # OK\nm5: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {}} # OK\nm6: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": \"2\", \"2\": {}}} # OK\nm7: RecursiveMapping = {\"1\": [1]} # E\nm8: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": [1, 2]} # E\nm9: RecursiveMapping = {\"1\": \"1\", \"2\": 1, \"3\": {\"0\": \"0\", \"1\": 1, \"2\": [1, 2, 3]}} # E\n\n\nT1 = TypeVar(\"T1\", str, int)\nT2 = TypeVar(\"T2\")\n\nGenericTypeAlias1 = list[\"GenericTypeAlias1[T1]\" | T1]\nSpecializedTypeAlias1 = GenericTypeAlias1[str]\n\ng1: SpecializedTypeAlias1 = [\"hi\", [\"hi\", \"hi\"]] # OK\ng2: GenericTypeAlias1[str] = [\"hi\", \"bye\", [\"\"], [[\"hi\"]]] # OK\ng3: GenericTypeAlias1[str] = [\"hi\", [2.4]] # E\n\nGenericTypeAlias2 = list[\"GenericTypeAlias2[T1, T2]\" | T1 | T2]\n\ng4: GenericTypeAlias2[str, int] = [[3, [\"hi\"]], \"hi\"] # OK\ng5: GenericTypeAlias2[str, float] = [[3, [\"hi\", 3.4, [3.4]]], \"hi\"] # OK\ng6: GenericTypeAlias2[str, int] = [[3, [\"hi\", 3, [3.4]]], \"hi\"] # E\n\n\nRecursiveUnion: TypeAlias = Union[\"RecursiveUnion\", int] # E: cyclical reference\n\n# On one line because different type checkers report the error on different lines\nMutualReference1: TypeAlias = Union[\"MutualReference2\", int]; MutualReference2: TypeAlias = Union[\"MutualReference1\", str] # E: cyclical reference\n","source":"typing_tests","origin":"conformance/tests/aliases_recursive.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-form","pep":"747","introduced_in":"3.15","form":"modern","file":"type-form/modern_01.py","code":"\"\"\"\nTests TypeForm functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/type-forms.html#typeform\n\nimport types\nfrom typing import Annotated, Any, ClassVar, Final, Literal, Optional, Self, TypeVarTuple, Unpack, assert_type\nfrom typing_extensions import TypeForm\n\n\n# > ``TypeForm[T]`` describes the set of all type form objects that represent\n# > the type ``T`` or types that are assignable to ``T``.\n\nok1: TypeForm[str | None] = str | None # OK\nok2: TypeForm[str | None] = str # OK\nok3: TypeForm[str | None] = None # OK\nok4: TypeForm[str | None] = Literal[None] # OK\nok5: TypeForm[str | None] = Optional[str] # OK\nok6: TypeForm[str | None] = \"str | None\" # OK\nok7: TypeForm[str | None] = Any # OK\n\nerr1: TypeForm[str | None] = str | int # E\nerr2: TypeForm[str | None] = list[str | None] # E\n\n\n# > ``TypeForm[Any]`` is assignable both to and from any other ``TypeForm`` type.\n\nv_any: TypeForm[Any] = int | str\nv_str: TypeForm[str] = str\nassert_type(v_any, TypeForm[Any])\nassert_type(v_str, TypeForm[str])\n\nv_any = v_str # OK\nv_str = v_any # OK\n\n# > The type expression ``TypeForm``, with no type argument provided, is\n# > equivalent to ``TypeForm[Any]``.\n\ndef func1(x: TypeForm) -> None:\n assert_type(x, TypeForm[Any])\n\n\n# > Valid type expressions are assignable to ``TypeForm`` through implicit TypeForm evaluation.\n\nv1_actual: types.UnionType = str | None # OK\nv1_type_form: TypeForm[str | None] = str | None # OK\n\nv2_actual: types.GenericAlias = list[int] # OK\nv2_type_form: TypeForm = list[int] # OK\n\nv3: TypeForm[int | str] = Annotated[int | str, \"metadata\"] # OK\nv4: TypeForm[set[str]] = \"set[str]\" # OK\n\nfunc1(v3) # OK\nfunc1(v4) # OK\nfunc1(int) # OK\nfunc1(\"int\") # OK\nfunc1(\"not a type\") # E\n\n\n# > Expressions that are not valid type expressions should not evaluate to a ``TypeForm`` type.\n\nTs = TypeVarTuple(\"Ts\")\nvar = 1\n\nbad1: TypeForm = tuple() # E\nbad2: TypeForm = (1, 2) # E\nbad3: TypeForm = 1 # E\nbad4: TypeForm = Self # E\nbad5: TypeForm = ClassVar[int] # E\nbad6: TypeForm = Final[int] # E\nbad7: TypeForm = Unpack[Ts] # E\nbad8: TypeForm = Optional # E\nbad9: TypeForm = \"int + str\" # E\n\n\n# > ``TypeForm`` acts as a function that can be called with a single valid type expression.\n\nx1 = TypeForm(str | None)\nassert_type(x1, TypeForm[str | None])\n\nx2 = TypeForm(\"list[int]\")\nassert_type(x2, TypeForm[list[int]])\n\nx3 = TypeForm(\"type(1)\") # E\nx4 = type(1) # OK\nx5 = TypeForm(type(1)) # E\n\n\n# > ``TypeForm`` is covariant in its single type parameter.\n\ndef get_type_form() -> TypeForm[int]:\n return int\n\n\nt1: TypeForm[int | str] = get_type_form() # OK\nt2: TypeForm[str] = get_type_form() # E\n\n\n# > ``type[T]`` is a subtype of ``TypeForm[T]``.\n\ndef get_type() -> type[int]:\n return int\n\n\nt3: TypeForm[int | str] = get_type() # OK\nt4: TypeForm[str] = get_type() # E\n","source":"typing_tests","origin":"conformance/tests/typeforms_typeform.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-guard","pep":"647","introduced_in":"3.10","form":"modern","file":"type-guard/modern_01.py","code":"\"\"\"\nTests TypeGuard functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeguard\n\nfrom typing import Any, Callable, Protocol, Self, TypeGuard, TypeVar, assert_type\n\n\nT = TypeVar(\"T\")\n\ndef is_two_element_tuple(val: tuple[T, ...]) -> TypeGuard[tuple[T, T]]:\n return len(val) == 2\n\ndef func1(names: tuple[str, ...]):\n if is_two_element_tuple(names):\n assert_type(names, tuple[str, str])\n else:\n assert_type(names, tuple[str, ...])\n\n\ndef is_str_list(val: list[object], allow_empty: bool) -> TypeGuard[list[str]]:\n if len(val) == 0:\n return allow_empty\n return all(isinstance(x, str) for x in val)\n\ndef is_set_of(val: set[Any], type: type[T]) -> TypeGuard[set[T]]:\n return all(isinstance(x, type) for x in val)\n\ndef func2(val: set[object]):\n if is_set_of(val, int):\n assert_type(val, set[int])\n else:\n assert_type(val, set[object])\n\n\nT_A = TypeVar(\"T_A\", bound=\"A\")\n\nclass A:\n def tg_1(self, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @classmethod\n def tg_2(cls, val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n @staticmethod\n def tg_3(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n def tg4(self, val: object) -> TypeGuard[Self]:\n return isinstance(val, type(self))\n\n def tg5(self: T_A, val: object) -> TypeGuard[T_A]:\n return isinstance(val, type(self))\n\nclass B(A):\n pass\n\n# > Type checkers should assume that type narrowing should be applied to\n# > the expression that is passed as the first positional argument to a\n# > user-defined type guard. If the type guard function accepts more than\n# > one argument, no type narrowing is applied to those additional argument\n# > expressions.\n\ndef func3() -> None:\n val1 = object()\n if A().tg_1(val1):\n assert_type(val1, int)\n\n val2 = object()\n if A().tg_2(val2):\n assert_type(val2, int)\n\n val3 = object()\n if A.tg_2(val3):\n assert_type(val3, int)\n\n val4 = object()\n if A().tg_3(val4):\n assert_type(val4, int)\n\n val5 = object()\n if A.tg_3(val5):\n assert_type(val5, int)\n\n val6 = object()\n if B().tg4(val6):\n assert_type(val6, B)\n\n val7 = object()\n if B().tg4(val7):\n assert_type(val7, B)\n\n\n# > If a type guard function is implemented as an instance method or class\n# > method, the first positional argument maps to the second parameter\n# > (after “self” or “cls”).\n\nclass C:\n # Type checker should emit error here.\n def tg_1(self) -> TypeGuard[int]: # E\n return False\n\n @classmethod\n # Type checker should emit error here.\n def tg_2(cls) -> TypeGuard[int]: # E\n return False\n\n# > ``TypeGuard`` is also valid as the return type of a ``Callable`` type. In that\n# > context, it is treated as a subtype of bool. For example, ``Callable[..., TypeGuard[int]]``\n# > is assignable to ``Callable[..., bool]``.\n\n\ndef takes_callable_bool(f: Callable[[object], bool]) -> None:\n pass\n\n\ndef takes_callable_str(f: Callable[[object], str]) -> None:\n pass\n\n\ndef simple_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ntakes_callable_bool(simple_typeguard) # OK\ntakes_callable_str(simple_typeguard) # E\n\n\nclass CallableBoolProto(Protocol):\n def __call__(self, val: object) -> bool: ...\n\n\nclass CallableStrProto(Protocol):\n def __call__(self, val: object) -> str: ...\n\n\ndef takes_callable_bool_proto(f: CallableBoolProto) -> None:\n pass\n\n\ndef takes_callable_str_proto(f: CallableStrProto) -> None:\n pass\n\n\ntakes_callable_bool_proto(simple_typeguard) # OK\ntakes_callable_str_proto(simple_typeguard) # E\n\n# > Unlike ``TypeGuard``, ``TypeIs`` is invariant in its argument type:\n# > ``TypeIs[B]`` is not a subtype of ``TypeIs[A]``,\n# > even if ``B`` is a subtype of ``A``.\n\ndef takes_int_typeguard(f: Callable[[object], TypeGuard[int]]) -> None:\n pass\n\n\ndef int_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\n\ndef bool_typeguard(val: object) -> TypeGuard[bool]:\n return isinstance(val, bool)\n\n\ntakes_int_typeguard(int_typeguard) # OK\ntakes_int_typeguard(bool_typeguard) # OK\n","source":"typing_tests","origin":"conformance/tests/narrowing_typeguard.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_01.py","code":"\"\"\"\nTests traditional implicit type aliases.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html\n\nfrom collections.abc import Iterable\nfrom typing import Any, Callable, Concatenate, ParamSpec, TypeVar, Union, assert_type\n\nTFloat = TypeVar(\"TFloat\", bound=float)\nVector = Iterable[tuple[TFloat, TFloat]]\n\n\ndef in_product(v: Vector[TFloat]) -> Iterable[TFloat]:\n return [x for x, _ in v]\n\n\ndef dilate(v: Vector[float], scale: float) -> Vector[float]:\n return ((x * scale, y * scale) for x, y in v)\n\n\n# > Type aliases may be as complex as type hints in annotations – anything\n# > that is acceptable as a type hint is acceptable in a type alias.\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nP = ParamSpec(\"P\")\nR = TypeVar(\"R\")\n\nGoodTypeAlias1 = Union[int, str]\nGoodTypeAlias2 = int | None\nGoodTypeAlias3 = list[GoodTypeAlias2]\nGoodTypeAlias4 = list[T]\nGoodTypeAlias5 = tuple[T, ...] | list[T]\nGoodTypeAlias6 = tuple[int, int, S, T]\nGoodTypeAlias7 = Callable[..., int]\nGoodTypeAlias8 = Callable[[int, T], T]\nGoodTypeAlias9 = Callable[Concatenate[int, P], R]\nGoodTypeAlias10 = Any\nGoodTypeAlias11 = GoodTypeAlias1 | GoodTypeAlias2 | list[GoodTypeAlias4[int]]\nGoodTypeAlias12 = list[TFloat]\nGoodTypeAlias13 = Callable[P, None]\n\n\ndef good_type_aliases(\n p1: GoodTypeAlias1,\n p2: GoodTypeAlias2,\n p3: GoodTypeAlias3,\n p4: GoodTypeAlias4[int],\n p5: GoodTypeAlias5[str],\n p6: GoodTypeAlias6[int, str],\n p7: GoodTypeAlias7,\n p8: GoodTypeAlias8[str],\n p9: GoodTypeAlias9[[str, str], None],\n p10: GoodTypeAlias10,\n p11: GoodTypeAlias11,\n p12: GoodTypeAlias12[bool],\n p13: GoodTypeAlias13\n):\n assert_type(p1, int | str)\n assert_type(p2, int | None)\n assert_type(p3, list[int | None])\n assert_type(p4, list[int])\n assert_type(p5, tuple[str, ...] | list[str])\n assert_type(p6, tuple[int, int, int, str])\n assert_type(p7, Callable[..., int])\n assert_type(p8, Callable[[int, str], str])\n assert_type(p9, Callable[[int, str, str], None])\n assert_type(p10, Any)\n assert_type(p11, int | str | None | list[list[int]])\n assert_type(p12, list[bool])\n assert_type(p13, Callable[..., None])\n\n\ndef good_type_aliases_used_badly(\n p1: GoodTypeAlias2[int], # E: type alias is not generic\n p2: GoodTypeAlias3[int], # E: type alias is already specialized\n p3: GoodTypeAlias4[int, int], # E: too many type arguments\n p4: GoodTypeAlias8[int, int], # E: too many type arguments\n p5: GoodTypeAlias9[int, int], # E: bad type argument for ParamSpec\n p6: GoodTypeAlias12[str], # E: type argument doesn't match bound\n):\n pass\n\n\nvar1 = 3\n\n# The following should not be considered type aliases.\nBadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116])))\nBadTypeAlias2 = [int, str]\nBadTypeAlias3 = ((int, str),)\nBadTypeAlias4 = [int for i in range(1)]\nBadTypeAlias5 = {\"a\": \"b\"}\nBadTypeAlias6 = (lambda: int)()\nBadTypeAlias7 = [int][0]\nBadTypeAlias8 = int if 1 < 3 else str\nBadTypeAlias9 = var1\nBadTypeAlias10 = True\nBadTypeAlias11 = 1\nBadTypeAlias12 = list or set\nBadTypeAlias13 = f\"int\"\nBadTypeAlias14 = \"int | str\"\n\n\ndef bad_type_aliases(\n p1: BadTypeAlias1, # E: Invalid type annotation\n p2: BadTypeAlias2, # E: Invalid type annotation\n p3: BadTypeAlias3, # E: Invalid type annotation\n p4: BadTypeAlias4, # E: Invalid type annotation\n p5: BadTypeAlias5, # E: Invalid type annotation\n p6: BadTypeAlias6, # E: Invalid type annotation\n p7: BadTypeAlias7, # E: Invalid type annotation\n p8: BadTypeAlias8, # E: Invalid type annotation\n p9: BadTypeAlias9, # E: Invalid type annotation\n p10: BadTypeAlias10, # E: Invalid type annotation\n p11: BadTypeAlias11, # E: Invalid type annotation\n p12: BadTypeAlias12, # E: Invalid type annotation\n p13: BadTypeAlias13, # E: Invalid type annotation\n p14: BadTypeAlias14, # E: Invalid type annotation\n):\n pass\n\n\nListAlias = list\nListOrSetAlias = list | set\n\nx1: list[str] = ListAlias() # OK\nassert_type(x1, list[str])\n\nx2 = ListAlias[int]() # OK\nassert_type(x2, list[int])\n\nx3 = ListOrSetAlias() # E: cannot instantiate union\n\nx4: ListOrSetAlias[int] # E: already specialized\n","source":"typing_tests","origin":"conformance/tests/aliases_implicit.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_02.py","code":"\"\"\"\nTests the `typing.NewType` type constructor.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/aliases.html#newtype\n\nfrom typing import Any, Hashable, Literal, NewType, TypeVar, TypedDict, assert_type\n\nUserId = NewType(\"UserId\", int)\n\nUserId(\"user\") # E: incorrect type\nu1: UserId = 42 # E: incorrect type\nu2: UserId = UserId(42) # OK\n\nassert_type(UserId(5) + 1, int)\n\n# > NewType('Derived', Base) returns a dummy object\n_: type = UserId # E: `NewType()` does not return an instance of `type`\n\n# > Both ``isinstance`` and ``issubclass``, as well as subclassing will fail\n# > for ``NewType('Derived', Base)``, since the object returned by a call to\n# > ``NewType`` is not a class.\nisinstance(u2, UserId) # E: not allowed in isinstance call\n\n\nclass UserIdDerived(UserId): # E: subclassing not allowed\n pass\n\n\n# > NewType accepts exactly two arguments: a name for the new unique type,\n# > and a base class. The latter should be a proper class (i.e., not a type\n# > construct like Union, etc.), or another unique type created by\n# > calling NewType.\n\nGoodName = NewType(\"BadName\", int) # E: assigned name does not match\n\nGoodNewType1 = NewType(\"GoodNewType1\", list) # OK\n\nGoodNewType2 = NewType(\"GoodNewType2\", GoodNewType1) # OK\n\nnt1: GoodNewType1[int] # E: NewType cannot be generic\n\nTypeAlias1 = dict[str, str]\nGoodNewType3 = NewType(\"GoodNewType3\", TypeAlias1)\n\n\nBadNewType1 = NewType(\"BadNewType1\", int | str) # E: cannot be generic\n\nT = TypeVar(\"T\")\nBadNewType2 = NewType(\"BadNewType2\", list[T]) # E: cannot be generic\n\nBadNewType3 = NewType(\"BadNewType3\", Hashable) # E: cannot be protocol\n\nBadNewType4 = NewType(\"BadNewType4\", Literal[7]) # E: literal not allowed\n\n\nclass TD1(TypedDict):\n a: int\n\n\nBadNewType5 = NewType(\"BadNewType5\", TD1) # E: cannot be TypedDict\n\nBadNewType6 = NewType(\"BadNewType6\", int, int) # E: too many arguments\n\nBadNewType7 = NewType(\"BadNewType7\", Any) # E: cannot be Any\n","source":"typing_tests","origin":"conformance/tests/aliases_newtype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_03.py","code":"\"\"\"\nTests for annotating coroutines.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# > Coroutines introduced in PEP 492 are annotated with the same syntax as\n# > ordinary functions. However, the return type annotation corresponds to\n# > the type of await expression, not to the coroutine type.\n\n\nfrom typing import Any, Callable, Coroutine, assert_type\n\n\nasync def func1(ignored: int, /) -> str:\n return \"spam\"\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[int], Coroutine[Any, Any, str]] = func1\n\n\nasync def func2() -> None:\n x = await func1(42)\n assert_type(x, str)\n","source":"typing_tests","origin":"conformance/tests/annotations_coroutines.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_04.py","code":"\"\"\"\nTests for annotating generators.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-generator-functions-and-coroutines\n\n# The return type of generator functions can be annotated by the generic type\n# Generator[yield_type, send_type, return_type] provided by typing.py module.\n\nimport asyncio\nfrom typing import (\n Any,\n AsyncGenerator,\n AsyncIterable,\n AsyncIterator,\n Awaitable,\n Callable,\n Coroutine,\n Generator,\n Iterable,\n Iterator,\n Protocol,\n TypeVar,\n assert_type,\n)\n\nT = TypeVar(\"T\")\n\n\nclass A:\n pass\n\n\nclass B:\n def should_continue(self) -> bool:\n return True\n\n\nclass C:\n pass\n\n\ndef generator1() -> Generator[A, B, C]:\n cont = B()\n while cont.should_continue():\n yield A()\n\n return C()\n\n\ndef generator2() -> Generator[A, B, C]: # E: missing return\n cont = B()\n if cont.should_continue():\n return False # E: incompatible return type\n\n while cont.should_continue():\n yield 3 # E: incompatible yield type\n\n\ndef generator3() -> Generator[A, int, Any]:\n cont = B()\n if cont.should_continue():\n return 3\n\n while cont.should_continue():\n yield 3 # E: Incompatible yield type\n\n\ndef generator4() -> Iterable[A]:\n yield A()\n return True # E?: No return value expected\n\n\ndef generator5() -> Iterator[A]:\n yield B() # E: incompatible yield type\n\n\ndef generator6() -> Generator[None, None, None]:\n yield\n\n\ndef generator7() -> Iterator[dict[str, int]]:\n yield {\"\": 0} # OK\n\n\ndef generator8() -> int: # E: incompatible return type\n yield None # E?\n return 0\n\n\nasync def generator9() -> int: # E: incompatible return type\n yield None # E?\n\n\nclass IntIterator(Protocol):\n def __next__(self, /) -> int:\n ...\n\n\ndef generator15() -> IntIterator: # OK\n yield 0\n\n\nclass AsyncIntIterator(Protocol):\n def __anext__(self, /) -> Awaitable[int]:\n ...\n\n\nasync def generator16() -> AsyncIntIterator: # OK\n yield 0\n\n\ndef generator17() -> Iterator[A]: # OK\n yield from generator17()\n\n\ndef generator18() -> Iterator[B]:\n yield from generator17() # E: incompatible generator type\n yield from [1] # E: incompatible generator type\n\n\ndef generator19() -> Generator[None, float, None]: # OK\n x: float = yield\n\n\ndef generator20() -> Generator[None, int, None]: # OK\n yield from generator19()\n\n\ndef generator21() -> Generator[None, int, None]:\n x: float = yield\n\n\ndef generator22() -> Generator[None, str, None]:\n yield from generator21() # E: incompatible send type\n\n\ndef generator23() -> Iterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\nasync def generator24() -> AsyncIterable[str]: # OK\n return\n yield \"\" # Unreachable\n\n\ndef generator25(ints1: list[int], ints2: list[int]) -> Generator[int, None, None]: # OK\n yield from ints1\n yield from ints2\n\n\nasync def get_data() -> list[int]:\n await asyncio.sleep(1)\n return [1, 2, 3]\n\n\nasync def generator26(nums: list[int]) -> AsyncGenerator[str, None]:\n for n in nums:\n await asyncio.sleep(1)\n yield f\"The number is {n}\"\n\n\nasync def generator27() -> AsyncGenerator[str, None]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator28() -> AsyncIterator[str]:\n data = await get_data()\n v1 = generator26(data)\n assert_type(v1, AsyncGenerator[str, None])\n return v1\n\n\nasync def generator29() -> AsyncIterator[int]:\n raise NotImplementedError\n\n\n# Don't use assert_type here because some type checkers infer\n# the narrower type types.CoroutineType rather than typing.Coroutine\n# in this case.\nv1: Callable[[], Coroutine[Any, Any, AsyncIterator[int]]] = generator29\n\n\nasync def generator30() -> AsyncIterator[int]:\n raise NotImplementedError\n yield 1\n\n\nasync def uses_generator30() -> None:\n async for x in generator30():\n assert_type(x, int)\n","source":"typing_tests","origin":"conformance/tests/annotations_generators.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_05.py","code":"\"\"\"\nTests for annotating instance and class methods.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/annotations.html#annotating-instance-and-class-methods\n\nfrom typing import TypeVar, assert_type\n\n\nT = TypeVar(\"T\", bound=\"A\")\n\n\nclass A:\n def copy(self: T) -> T:\n return self\n\n @classmethod\n def factory(cls: type[T]) -> T:\n return cls()\n\n @staticmethod\n def static_method(val: type[T]) -> T:\n return val()\n\n\nclass B(A):\n ...\n\n\nassert_type(A().copy(), A)\nassert_type(A.factory(), A)\nassert_type(A.copy(A()), A)\nassert_type(B.copy(B()), B)\n\nassert_type(B().copy(), B)\nassert_type(B.factory(), B)\n\n# This case is ambiguous in the spec, which does not indicate when\n# type binding should be performed. Currently, pyright evaluates\n# A here, but mypy evaluates B. Since the spec is not clear, both\n# of these are currently acceptable answers.\nassert_type(A.copy(B()), A) # E?\n\n# Similarly, this case is ambiguous in the spec. Pyright currently\n# generates a type error here, but mypy accepts this.\nB.copy(A()) # E?\n\nassert_type(A.static_method(A), A)\nassert_type(A.static_method(B), B)\nassert_type(B.static_method(B), B)\nassert_type(B.static_method(A), A)\n","source":"typing_tests","origin":"conformance/tests/annotations_methods.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_06.py","code":"\"\"\"\nTest for type expressions used in annotations.\n\"\"\"\n\nimport abc\nimport abc\nimport types\nimport types\nfrom typing import Any, Callable, Tuple, Union, assert_type\n\n# https://typing.readthedocs.io/en/latest/spec/annotations.html#valid-type-expression-forms\n\n\ndef greeting(name: str) -> str:\n return \"Hello \" + name\n\n\nassert_type(greeting(\"Monty\"), str)\n\n\n# > Expressions whose type is a subtype of a specific argument type are also accepted for that argument.\nclass StrSub(str):\n ...\n\n\nassert_type(greeting(StrSub(\"Monty\")), str)\n\n\n# > Type hints may be built-in classes (including those defined in standard library or third-party\n# > extension modules), abstract base classes, types available in the types module, and user-defined\n# > classes (including those defined in the standard library or third-party modules).\n\n\nclass UserDefinedClass:\n ...\n\n\nclass AbstractBaseClass(abc.ABC):\n @abc.abstractmethod\n def abstract_method(self):\n ...\n\n\n# The following parameter annotations should all be considered\n# valid and not generate errors.\ndef valid_annotations(\n p1: int,\n p2: str,\n p3: bytes,\n p4: bytearray,\n p5: memoryview,\n p6: complex,\n p7: float,\n p8: bool,\n p9: object,\n p10: type,\n p11: types.ModuleType,\n p12: types.FunctionType,\n p13: types.BuiltinFunctionType,\n p14: UserDefinedClass,\n p15: AbstractBaseClass,\n p16: int,\n p17: Union[int, str],\n p18: None,\n p19: list,\n p20: list[int],\n p21: tuple,\n p22: Tuple[int, ...],\n p23: Tuple[int, int, str],\n p24: Callable[..., int],\n p25: Callable[[int, str], None],\n p26: Any,\n):\n assert_type(p17, int | str)\n assert_type(p19, list[Any])\n assert_type(p20, list[int])\n assert_type(p21, tuple[Any, ...])\n\n\n# > Annotations should be kept simple or static analysis tools may not be able to interpret the values.\n\nvar1 = 3\n\n\n# The following parameter annotations should all be considered\n# invalid and generate errors.\ndef invalid_annotations(\n p1: eval(\"\".join(map(chr, [105, 110, 116]))), # E\n p2: [int, str], # E\n p3: (int, str), # E\n p4: [int for i in range(1)], # E\n p5: {}, # E\n p6: (lambda: int)(), # E\n p7: [int][0], # E\n p8: int if 1 < 3 else str, # E\n p9: var1, # E\n p10: True, # E\n p11: 1, # E\n p12: -1, # E\n p13: int or str, # E\n p14: f\"int\", # E\n p15: types, # E\n):\n pass\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef takes_None(x: None) -> None:\n ...\n\n\nassert_type(takes_None(None), None)\n","source":"typing_tests","origin":"conformance/tests/annotations_typeexpr.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_07.py","code":"\"\"\"\nTests Callable annotation and parameter annotations for \"def\" statements.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#callable\n\nfrom typing import (\n Any,\n Callable,\n Concatenate,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n assert_type,\n)\n\nT_contra = TypeVar(\"T_contra\", contravariant=True)\nP = ParamSpec(\"P\")\n\n\ndef func1(cb: Callable[[int, str], list[str]]) -> None:\n assert_type(cb(1, \"\"), list[str])\n\n cb(1) # E\n cb(1, 2) # E\n cb(1, \"\", 1) # E\n # Mypy reports two errors, one for each kwarg.\n cb(a=1, b=\"\") # E: bad kwarg 'a'\n\n\ndef func2(cb: Callable[[], dict[str, str]]) -> None:\n assert_type(cb(), dict[str, str])\n\n cb(1) # E\n\n\n# https://typing.readthedocs.io/en/latest/spec/callables.html#meaning-of-in-callable\n\n\n# > The Callable special form supports the use of ... in place of the list of\n# > parameter types. This indicates that the type is consistent with any input\n# > signature.\ndef func3(cb: Callable[..., list[str]]):\n assert_type(cb(), list[str])\n assert_type(cb(\"\"), list[str])\n assert_type(cb(1, \"\"), list[str])\n\n\ndef func4(*args: int, **kwargs: int) -> None:\n assert_type(args, tuple[int, ...])\n assert_type(kwargs, dict[str, int])\n\n\nv1: Callable[int] # E\nv2: Callable[int, int] # E\nv3: Callable[[], [int]] # E\nv4: Callable[int, int, int] # E\nv5: Callable[[...], int] # E\n\n\ndef test_cb1(x: int) -> str:\n return \"\"\n\n\ndef test_cb2() -> str:\n return \"\"\n\n\ncb1: Callable[..., str]\ncb1 = test_cb1 # OK\ncb1 = test_cb2 # OK\n\ncb2: Callable[[], str] = cb1 # OK\n\n# > A ... can also be used with Concatenate. In this case, the parameters prior\n# > to the ... are required to be present in the input signature and be\n# > compatible in kind and type, but any additional parameters are permitted.\n\n\ndef test_cb3(a: int, b: int, c: int) -> str:\n return \"\"\n\n\ndef test_cb4(*, a: int) -> str:\n return \"\"\n\n\ncb3: Callable[Concatenate[int, ...], str]\ncb3 = test_cb1 # OK\ncb3 = test_cb2 # E\ncb3 = test_cb3 # OK\ncb3 = test_cb4 # E\n\n# > If the input signature in a function definition includes both a *args and\n# > **kwargs parameter and both are typed as Any (explicitly or implicitly\n# > because it has no annotation), a type checker should treat this as the\n# > equivalent of `...`. Any other parameters in the signature are unaffected\n# > and are retained as part of the signature.\n\n\nclass Proto1(Protocol):\n def __call__(self, *args: Any, **kwargs: Any) -> None: ...\n\n\nclass Proto2(Protocol):\n def __call__(self, a: int, /, *args, **kwargs) -> None: ...\n\n\nclass Proto3(Protocol):\n def __call__(self, a: int, *args: Any, **kwargs: Any) -> None: ...\n\n\nclass Proto4[**P](Protocol):\n def __call__(self, a: int, *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n\nclass Proto5(Protocol[T_contra]):\n def __call__(self, *args: T_contra, **kwargs: T_contra) -> None: ...\n\n\nclass Proto6(Protocol):\n def __call__(self, a: int, /, *args: Any, k: str, **kwargs: Any) -> None:\n pass\n\n\nclass Proto7(Protocol):\n def __call__(self, a: float, /, b: int, *, k: str, m: str) -> None:\n pass\n\n\nclass Proto8(Protocol):\n def __call__(self) -> None: ...\n\n\ndef func5(\n p1: Proto1,\n p2: Proto2,\n p3: Proto3,\n p4: Proto4[...],\n p5: Proto5[Any],\n p7: Proto7,\n p8: Proto8,\n c1: Callable[..., None],\n c2: Callable[Concatenate[int, ...], None],\n):\n ok1: Callable[..., None] = p1 # OK\n ok2: Proto1 = c1 # OK\n ok3: Callable[..., None] = p5 # OK\n ok4: Proto5[Any] = c1 # OK\n ok5: Callable[Concatenate[int, ...], None] = p2 # OK\n ok6: Proto2 = c2 # OK\n ok7: Callable[..., None] = p3 # OK\n ok8: Proto3 = c1 # OK\n ok9: Proto4[...] = p3 # OK\n ok10: Proto3 = p4 # OK\n ok11: Proto6 = p7 # OK\n\n err1: Proto5[Any] = p8 # E\n\n\n# > The ... syntax can also be used to provide a specialized value for a\n# > ParamSpec in a generic class or type alias.\n\n\nCallback1: TypeAlias = Callable[P, str]\nCallback2: TypeAlias = Callable[Concatenate[int, P], str]\n\n\ndef func6(cb1: Callable[[], str], cb2: Callable[[int], str]) -> None:\n f1: Callback1[...] = cb1 # OK\n f2: Callback2[...] = cb1 # E\n\n f3: Callback1[...] = cb2 # OK\n f4: Callback2[...] = cb2 # OK\n\n\n# > If ... is used with signature concatenation, the ... portion continues\n# > to mean “any conceivable set of parameters that could be compatible”.\n\nCallbackWithInt: TypeAlias = Callable[Concatenate[int, P], str]\nCallbackWithStr: TypeAlias = Callable[Concatenate[str, P], str]\n\n\ndef func7(cb: Callable[[int, str], str]) -> None:\n f1: Callable[Concatenate[int, ...], str] = cb # OK\n f2: Callable[Concatenate[str, ...], str] = cb # E\n f3: CallbackWithInt[...] = cb # OK\n f4: CallbackWithStr[...] = cb # E\n","source":"typing_tests","origin":"conformance/tests/callables_annotation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_08.py","code":"\"\"\"\nTests subtyping rules for callables.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#subtyping-rules-for-callables\n\nfrom typing import Callable, ParamSpec, Protocol, TypeAlias, overload\n\nP = ParamSpec(\"P\")\n\n# > Callable types are covariant with respect to their return types but\n# > contravariant with respect to their parameter types.\n\n\ndef func1(\n cb1: Callable[[float], int],\n cb2: Callable[[float], float],\n cb3: Callable[[int], int],\n) -> None:\n f1: Callable[[int], float] = cb1 # OK\n f2: Callable[[int], float] = cb2 # OK\n f3: Callable[[int], float] = cb3 # OK\n\n f4: Callable[[float], float] = cb1 # OK\n f5: Callable[[float], float] = cb2 # OK\n f6: Callable[[float], float] = cb3 # E\n\n f7: Callable[[int], int] = cb1 # OK\n f8: Callable[[int], int] = cb2 # E\n f9: Callable[[int], int] = cb3 # OK\n\n\n# > Callable A is a subtype of callable B if all keyword-only parameters in B\n# > are present in A as either keyword-only parameters or standard (positional\n# > or keyword) parameters.\n\n\nclass PosOnly2(Protocol):\n def __call__(self, b: int, a: int, /) -> None: ...\n\n\nclass KwOnly2(Protocol):\n def __call__(self, *, b: int, a: int) -> None: ...\n\n\nclass Standard2(Protocol):\n def __call__(self, a: int, b: int) -> None: ...\n\n\ndef func2(standard: Standard2, pos_only: PosOnly2, kw_only: KwOnly2):\n f1: Standard2 = pos_only # E\n f2: Standard2 = kw_only # E\n\n f3: PosOnly2 = standard # OK\n f4: PosOnly2 = kw_only # E\n\n f5: KwOnly2 = standard # OK\n f6: KwOnly2 = pos_only # E\n\n\n# > If a callable B has a signature with a *args parameter, callable A\n# > must also have a *args parameter to be a subtype of B, and the type of\n# > B’s *args parameter must be a subtype of A’s *args parameter.\n\n\nclass NoArgs3(Protocol):\n def __call__(self) -> None: ...\n\n\nclass IntArgs3(Protocol):\n def __call__(self, *args: int) -> None: ...\n\n\nclass FloatArgs3(Protocol):\n def __call__(self, *args: float) -> None: ...\n\n\ndef func3(no_args: NoArgs3, int_args: IntArgs3, float_args: FloatArgs3):\n f1: NoArgs3 = int_args # OK\n f2: NoArgs3 = float_args # OK\n\n f3: IntArgs3 = no_args # E: missing *args parameter\n f4: IntArgs3 = float_args # OK\n\n f5: FloatArgs3 = no_args # E: missing *args parameter\n f6: FloatArgs3 = int_args # E: float is not subtype of int\n\n\n# > If a callable B has a signature with one or more positional-only parameters,\n# > a callable A is a subtype of B if A has an *args parameter whose type is a\n# > supertype of the types of any otherwise-unmatched positional-only parameters\n# > in B.\n\n\nclass PosOnly4(Protocol):\n def __call__(self, a: int, b: str, /) -> None: ...\n\n\nclass IntArgs4(Protocol):\n def __call__(self, *args: int) -> None: ...\n\n\nclass IntStrArgs4(Protocol):\n def __call__(self, *args: int | str) -> None: ...\n\n\nclass StrArgs4(Protocol):\n def __call__(self, a: int, /, *args: str) -> None: ...\n\n\nclass Standard4(Protocol):\n def __call__(self, a: int, b: str) -> None: ...\n\n\ndef func4(int_args: IntArgs4, int_str_args: IntStrArgs4, str_args: StrArgs4):\n f1: PosOnly4 = int_args # E: str is not subtype of int\n f2: PosOnly4 = int_str_args # OK\n f3: PosOnly4 = str_args # OK\n f4: IntStrArgs4 = str_args # E: int | str is not subtype of str\n f5: IntStrArgs4 = int_args # E: int | str is not subtype of int\n f6: StrArgs4 = int_str_args # OK\n f7: StrArgs4 = int_args # E: str is not subtype of int\n f8: IntArgs4 = int_str_args # OK\n f9: IntArgs4 = str_args # E: int is not subtype of str\n f10: Standard4 = int_str_args # E: keyword parameters a and b missing\n f11: Standard4 = str_args # E: keyword parameter b missing\n\n\n# > If a callable B has a signature with a **kwargs parameter (without an\n# > unpacked TypedDict type annotation), callable A must also have a **kwargs\n# > parameter to be a subtype of B, and the type of B’s **kwargs parameter\n# > must be a subtype of A’s **kwargs parameter.\n\n\nclass NoKwargs5(Protocol):\n def __call__(self) -> None: ...\n\n\nclass IntKwargs5(Protocol):\n def __call__(self, **kwargs: int) -> None: ...\n\n\nclass FloatKwargs5(Protocol):\n def __call__(self, **kwargs: float) -> None: ...\n\n\ndef func5(no_kwargs: NoKwargs5, int_kwargs: IntKwargs5, float_kwargs: FloatKwargs5):\n f1: NoKwargs5 = int_kwargs # OK\n f2: NoKwargs5 = float_kwargs # OK\n\n f3: IntKwargs5 = no_kwargs # E: missing **kwargs parameter\n f4: IntKwargs5 = float_kwargs # OK\n\n f5: FloatKwargs5 = no_kwargs # E: missing **kwargs parameter\n f6: FloatKwargs5 = int_kwargs # E: float is not subtype of int\n\n\n# > If a callable B has a signature with one or more keyword-only parameters,\n# > a callable A is a subtype of B if A has a **kwargs parameter whose type\n# > is a supertype of the types of any otherwise-unmatched keyword-only\n# > parameters in B.\n\n\nclass KwOnly6(Protocol):\n def __call__(self, *, a: int, b: str) -> None: ...\n\n\nclass IntKwargs6(Protocol):\n def __call__(self, **kwargs: int) -> None: ...\n\n\nclass IntStrKwargs6(Protocol):\n def __call__(self, **kwargs: int | str) -> None: ...\n\n\nclass StrKwargs6(Protocol):\n def __call__(self, *, a: int, **kwargs: str) -> None: ...\n\n\nclass Standard6(Protocol):\n def __call__(self, a: int, b: str) -> None: ...\n\n\ndef func6(\n int_kwargs: IntKwargs6, int_str_kwargs: IntStrKwargs6, str_kwargs: StrKwargs6\n):\n f1: KwOnly6 = int_kwargs # E: str is not subtype of int\n f2: KwOnly6 = int_str_kwargs # OK\n f3: KwOnly6 = str_kwargs # OK\n f4: IntStrKwargs6 = str_kwargs # E: int | str is not subtype of str\n f5: IntStrKwargs6 = int_kwargs # E: int | str is not subtype of int\n f6: StrKwargs6 = int_str_kwargs # OK\n f7: StrKwargs6 = int_kwargs # E: str is not subtype of int\n f8: IntKwargs6 = int_str_kwargs # OK\n f9: IntKwargs6 = str_kwargs # E: int is not subtype of str\n f10: Standard6 = int_str_kwargs # E: Does not accept positional arguments\n f11: Standard6 = str_kwargs # E: Does not accept positional arguments\n\n\n# > A signature that includes *args: P.args, **kwargs: P.kwargs is equivalent\n# > to a Callable parameterized by P.\n\n\nclass ProtocolWithP[**P](Protocol):\n def __call__(self, *args: P.args, **kwargs: P.kwargs) -> None: ...\n\n\nTypeAliasWithP: TypeAlias = Callable[P, None]\n\n\ndef func7(proto: ProtocolWithP[P], ta: TypeAliasWithP[P]):\n # These two types are equivalent\n f1: TypeAliasWithP[P] = proto # OK\n f2: ProtocolWithP[P] = ta # OK\n\n\n# > If a callable A has a parameter x with a default argument value and B is\n# > the same as A except that x has no default argument, then A is a subtype\n# > of B. A is also a subtype of C if C is the same as A with parameter x\n# > removed.\n\n\nclass DefaultArg8(Protocol):\n def __call__(self, x: int = 0) -> None: ...\n\n\nclass NoDefaultArg8(Protocol):\n def __call__(self, x: int) -> None: ...\n\n\nclass NoX8(Protocol):\n def __call__(self) -> None: ...\n\n\ndef func8(default_arg: DefaultArg8, no_default_arg: NoDefaultArg8, no_x: NoX8):\n f1: DefaultArg8 = no_default_arg # E\n f2: DefaultArg8 = no_x # E\n\n f3: NoDefaultArg8 = default_arg # OK\n f4: NoDefaultArg8 = no_x # E\n\n f5: NoX8 = default_arg # OK\n f6: NoX8 = no_default_arg # E\n\n\n# > If a callable A is overloaded with two or more signatures, it is a subtype\n# > of callable B if at least one of the overloaded signatures in A is a\n# > subtype of B.\n\n\nclass Overloaded9(Protocol):\n @overload\n def __call__(self, x: int) -> int: ...\n @overload\n def __call__(self, x: str) -> str: ...\n\n\nclass IntArg9(Protocol):\n def __call__(self, x: int) -> int: ...\n\n\nclass StrArg9(Protocol):\n def __call__(self, x: str) -> str: ...\n\n\nclass FloatArg9(Protocol):\n def __call__(self, x: float) -> float: ...\n\n\ndef func9(overloaded: Overloaded9):\n f1: IntArg9 = overloaded # OK\n f2: StrArg9 = overloaded # OK\n f3: FloatArg9 = overloaded # E\n\n\n# > If a callable B is overloaded with two or more signatures, callable A is\n# > a subtype of B if A is a subtype of all of the signatures in B.\n\n\nclass Overloaded10(Protocol):\n @overload\n def __call__(self, x: int, y: str) -> float: ...\n @overload\n def __call__(self, x: str) -> complex: ...\n\n\nclass StrArg10(Protocol):\n def __call__(self, x: str) -> complex: ...\n\n\nclass IntStrArg10(Protocol):\n def __call__(self, x: int | str, y: str = \"\") -> int: ...\n\n\ndef func10(int_str_arg: IntStrArg10, str_arg: StrArg10):\n f1: Overloaded10 = int_str_arg # OK\n f2: Overloaded10 = str_arg # E\n","source":"typing_tests","origin":"conformance/tests/callables_subtyping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_09.py","code":"\"\"\"\nTests the typing.ClassVar special form.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/class-compat.html#classvar\n\nfrom typing import (\n Annotated,\n Any,\n Callable,\n ClassVar,\n Final,\n Generic,\n NamedTuple,\n ParamSpec,\n Protocol,\n TypeAlias,\n TypeVar,\n TypeVarTuple,\n TypedDict,\n assert_type,\n cast,\n)\nfrom typing import ClassVar as CV\n\n\nvar1 = 3\n\nP = ParamSpec(\"P\")\nT = TypeVar(\"T\")\nTs = TypeVarTuple(\"Ts\")\n\n# This is currently commented out because it causes mypy to crash.\n# class ClassA(Generic[T, P, Unpack[Ts]]):\n\n\nclass ClassA(Generic[T, P]):\n # > ClassVar accepts only a single argument that should be a valid type\n\n bad1: ClassVar[int, str] = cast(Any, 0) # E: too many arguments\n bad2: CV[3] = cast(Any, 0) # E: invalid type\n bad3: CV[var] = cast(Any, 0) # E: invalid type\n\n # > Note that a ClassVar parameter cannot include any type variables,\n # > regardless of the level of nesting.\n\n bad4: ClassVar[T] = cast(Any, 0) # E: cannot use TypeVar\n bad5: ClassVar[list[T]] = cast(Any, 0) # E: cannot use TypeVar\n bad6: ClassVar[Callable[P, Any]] = cast(Any, 0) # E: cannot use ParamSpec\n\n # This is currently commented out because it causes mypy to crash.\n # bad7: ClassVar[tuple[*Ts]] # E: cannot use TypeVarTuple\n\n bad8: ClassVar[list[str]] = {} # E: type violation in initialization\n\n bad9: Final[ClassVar[int]] = 3 # E: ClassVar cannot be nested with Final\n bad10: list[ClassVar[int]] = [] # E: ClassVar cannot be nested\n\n good1: CV[int] = 1\n good2: ClassVar[list[str]] = []\n good3: ClassVar[Any] = 1\n # > If an assigned value is available, the type should be inferred as some type\n # > to which this value is assignable.\n # Here, type checkers could infer good4 as `float` or `Any`, for example.\n good4: ClassVar = 3.1\n # > If the `ClassVar` qualifier is used without any assigned value, the type\n # > should be inferred as `Any`:\n good5: ClassVar # E?: Type checkers may error on uninitialized ClassVar\n good6: Annotated[ClassVar[list[int]], \"\"] = []\n\n def method1(self, a: ClassVar[int]): # E: ClassVar not allowed here\n x: ClassVar[str] = \"\" # E: ClassVar not allowed here\n self.xx: ClassVar[str] = \"\" # E: ClassVar not allowed here\n\n def method2(self) -> ClassVar[int]: # E: ClassVar not allowed here\n return 3\n\n\nbad11: ClassVar[int] = 3 # E: ClassVar not allowed here\nbad12: TypeAlias = ClassVar[str] # E: ClassVar not allowed here\n\n\n# > ``ClassVar`` cannot be used as a qualifier for a TypedDict item or a\n# > NamedTuple field. Such usage also generates an error at runtime.\n\n\nclass TDWithClassVar(TypedDict):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a TypedDict\n\n\nclass NTWithClassVar(NamedTuple):\n a: int\n b: ClassVar[int] # E: ClassVar not allowed in a NamedTuple\n\n\nassert_type(ClassA.good1, int)\nassert_type(ClassA.good2, list[str])\nassert_type(ClassA.good3, Any)\nassert_type(ClassA.good5, Any)\n\n\nclass BasicStarship:\n captain: str = \"Picard\" # Instance variable with default\n damage: int # Instance variable without default\n stats: ClassVar[dict[str, int]] = {} # Class variable\n\n def __init__(self, damage: int) -> None:\n self.damage = damage\n\n\nclass Starship:\n captain: str = \"Picard\"\n damage: int\n stats: ClassVar[dict[str, int]] = {}\n\n def __init__(self, damage: int, captain: str | None = None):\n self.damage = damage\n if captain:\n self.captain = captain\n\n def hit(self):\n Starship.stats[\"hits\"] = Starship.stats.get(\"hits\", 0) + 1\n\n\nenterprise_d = Starship(3000)\nenterprise_d.stats = {} # E: cannot access via instance\nStarship.stats = {} # OK\n\n\n# > As a matter of convenience (and convention), instance variables can be\n# > annotated in __init__ or other methods, rather than in the class.\n\n\nclass Box(Generic[T]):\n def __init__(self, content) -> None:\n self.content: T = content\n\n\n# Tests for ClassVar in Protocol\n\n\nclass ProtoA(Protocol):\n x: ClassVar[str]\n y: ClassVar[str]\n z: CV = [\"\"]\n\n\nclass ProtoAImpl:\n x = \"\"\n\n def __init__(self) -> None:\n self.y = \"\"\n\n\na: ProtoA = ProtoAImpl() # E: y is not a ClassVar\n\n\nclass ProtoB(Protocol):\n x: int = 3\n y: int\n z: ClassVar[int]\n\n @classmethod\n def method1(cls) -> None:\n return None\n\n @staticmethod\n def method2() -> None:\n return None\n\n\nclass ProtoBImpl(ProtoB):\n y = 0\n z = 0\n\n\nb_x: int = ProtoBImpl.x\nb_y: int = ProtoBImpl.y\nb_z: int = ProtoBImpl.z\n\nb_m1 = ProtoBImpl.method1\nb_m2 = ProtoBImpl.method2\n","source":"typing_tests","origin":"conformance/tests/classes_classvar.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_10.py","code":"\"\"\"\nTests the typing.cast call.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#cast\n\nfrom typing import cast\n\ndef find_first_str(a: list[object]) -> str:\n index = next(i for i, x in enumerate(a) if isinstance(x, str))\n return cast(str, a[index])\n\nx: int = cast(int, \"not an int\") # No type error\n\nbad1 = cast() # E: Too few arguments\nbad2 = cast(1, \"\") # E: Bad first argument type\nbad3 = cast(int, \"\", \"\") # E: Too many arguments\n","source":"typing_tests","origin":"conformance/tests/directives_cast.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_11.py","code":"\"\"\"\nTests the typing.no_type_check decorator.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#no-type-check\n# \"E?\" is used below because support is optional.\n\nfrom typing import no_type_check\n\n# > The behavior for the ``no_type_check`` decorator when applied to a class is\n# > left undefined by the typing spec at this time.\n\n@no_type_check\nclass ClassA:\n x: int = \"\" # E?: No error should be reported\n\n\n# > If a type checker supports the ``no_type_check`` decorator for functions, it\n# > should suppress all type errors for the ``def`` statement and its body including\n# > any nested functions or classes. It should also ignore all parameter\n# > and return type annotations and treat the function as if it were unannotated.\n\n@no_type_check\ndef func1(a: int, b: str) -> None:\n c = a + b # E?: No error should be reported\n return 1 # E?: No error should be reported\n\n\nfunc1(b\"invalid\", b\"arguments\") # E?: No error should be reported\n# This should still be an error because type checkers should ignore\n# annotations, but still check the argument count.\nfunc1() # E: incorrect arguments for parameters\n","source":"typing_tests","origin":"conformance/tests/directives_no_type_check.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_12.py","code":"\"\"\"\nTests the typing.TYPE_CHECKING constant.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/directives.html#type-checking\n\nfrom typing import TYPE_CHECKING, assert_type\n\n\nif not TYPE_CHECKING:\n a: int = \"\" # This should not generate an error\n\nif TYPE_CHECKING:\n b: list[int] = [1, 2, 3]\nelse:\n b: list[str] = [\"a\", \"b\", \"c\"]\n\nassert_type(b, list[int])\n","source":"typing_tests","origin":"conformance/tests/directives_type_checking.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_13.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#arbitrary-generic-types-as-base-classes\n\nfrom typing import Generic, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generic[T] is only valid as a base class – it’s not a proper type. However,\n# > user-defined generic types [...] and built-in generic types and ABCs such as\n# > list[T] and Iterable[T] are valid both as types and as base classes.\n\n\nclass Node: ...\n\n\nclass SymbolTable(dict[str, list[Node]]): ...\n\n\ndef takes_dict(x: dict): ...\ndef takes_dict_typed(x: dict[str, list[Node]]): ...\ndef takes_dict_incorrect(x: dict[str, list[object]]): ...\n\n\ndef test_symbol_table(s: SymbolTable):\n takes_dict(s) # OK\n takes_dict_typed(s) # OK\n takes_dict_incorrect(s) # E\n\n\ndef func1(y: Generic[T]): # E\n x: Generic # E\n\n\n# > If a generic base class has a type variable as a type argument, this makes\n# > the defined class generic.\n\n# Note that there is overlap in the spec and tests in generics_basic.py\n\nfrom collections.abc import Iterable, Container, Iterator\n\n\nclass LinkedList(Iterable[T], Container[T]): ...\n\n\ndef test_linked_list(l: LinkedList[int]):\n assert_type(iter(l), Iterator[int])\n assert_type(l.__contains__(1), bool)\n\n\nlinked_list_invalid: LinkedList[int, int] # E\n\nfrom collections.abc import Mapping\n\n\nclass MyDict(Mapping[str, T]): ...\n\n\ndef test_my_dict(d: MyDict[int]):\n assert_type(d[\"a\"], int)\n\n\nmy_dict_invalid: MyDict[int, int] # E\n\n# > Note that we can use T multiple times in the base class list,\n# > as long as we don’t use the same type variable T multiple times\n# > within Generic[...].\n\n\nclass BadClass1(Generic[T, T]): # E\n pass\n\n\nclass GoodClass1(dict[T, T]): # OK\n pass\n\n# > Type variables are applied to the defined class in the order in which\n# > they first appear in any generic base classes.\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nclass Parent1(Generic[T1, T2]): ...\nclass Parent2(Generic[T1, T2]): ...\nclass Child(Parent1[T1, T3], Parent2[T2, T3]): ...\n\ndef takes_parent1(x: Parent1[int, bytes]): ...\ndef takes_parent2(x: Parent2[str, bytes]): ...\n\nchild: Child[int, bytes, str] = Child()\ntakes_parent1(child) # OK\ntakes_parent2(child) # OK\n\n# > A type checker should report an error when the type variable order is\n# > inconsistent.\n\nclass Grandparent(Generic[T1, T2]): ...\nclass Parent(Grandparent[T1, T2]): ...\nclass BadChild(Parent[T1, T2], Grandparent[T2, T1]): ... # E\n","source":"typing_tests","origin":"conformance/tests/generics_base_class.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_14.py","code":"\"\"\"\nTests for basic usage of generics.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#introduction\n\nfrom __future__ import annotations\n\nfrom collections.abc import Sequence\nfrom typing import Any, Generic, Protocol, TypeVar, assert_type\n\nT = TypeVar(\"T\")\n\n# > Generics can be parameterized by using a factory available in\n# > ``typing`` called ``TypeVar``.\n\n\ndef first(l: Sequence[T]) -> T:\n return l[0]\n\n\ndef test_first(seq_int: Sequence[int], seq_str: Sequence[str]) -> None:\n assert_type(first(seq_int), int)\n assert_type(first(seq_str), str)\n\n\n# > ``TypeVar`` supports constraining parametric types to a fixed set of\n# > possible types\n\nAnyStr = TypeVar(\"AnyStr\", str, bytes)\n\n\ndef concat(x: AnyStr, y: AnyStr) -> AnyStr:\n return x + y\n\n\ndef test_concat(s: str, b: bytes, a: Any) -> None:\n concat(s, s) # OK\n concat(b, b) # OK\n concat(s, b) # E\n concat(b, s) # E\n\n concat(s, a) # OK\n concat(a, b) # OK\n\n\n# > Specifying a single constraint is disallowed.\n\nBadConstraint1 = TypeVar(\"BadConstraint1\", str) # E\n\n# > Note: those types cannot be parameterized by type variables\n\n\nclass Test(Generic[T]):\n BadConstraint2 = TypeVar(\"BadConstraint2\", str, list[T]) # E\n\n\n# > Subtypes of types constrained by a type variable should be treated\n# > as their respective explicitly listed base types in the context of the\n# > type variable.\n\n\nclass MyStr(str): ...\n\n\ndef test_concat_subtype(s: str, b: bytes, a: Any, m: MyStr) -> None:\n assert_type(concat(m, m), str)\n assert_type(concat(m, s), str)\n concat(m, b) # E\n\n # TODO: should these be str or Any?\n # reveal_type(concat(m, a))\n # reveal_type(concat(a, m))\n\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#user-defined-generic-classes\n\n# > You can include a ``Generic`` base class to define a user-defined class\n# > as generic.\n\nfrom logging import Logger\nfrom collections.abc import Iterable\n\n\nclass LoggedVar(Generic[T]):\n def __init__(self, value: T, name: str, logger: Logger) -> None:\n self.name = name\n self.logger = logger\n self.value = value\n\n def set(self, new: T) -> None:\n self.log(\"Set \" + repr(self.value))\n self.value = new\n\n def get(self) -> T:\n self.log(\"Get \" + repr(self.value))\n return self.value\n\n def log(self, message: str) -> None:\n self.logger.info(\"{}: {}\".format(self.name, message))\n\n\ndef zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:\n for var in vars:\n var.set(0)\n assert_type(var.get(), int)\n\n\n# > A generic type can have any number of type variables, and type variables\n# > may be constrained.\n\nS = TypeVar(\"S\")\n\n\nclass Pair1(Generic[T, S]): ...\n\n\n# > Each type variable argument to ``Generic`` must be distinct.\n\n\nclass Pair2(Generic[T, T]): # E\n ...\n\n\n# > The ``Generic[T]`` base class is redundant in simple cases where you\n# > subclass some other generic class and specify type variables for its\n# > parameters.\n\nfrom collections.abc import Iterator, Mapping\n\n\nclass MyIter1(Iterator[T]): ...\n\n\nclass MyIter2(Iterator[T], Generic[T]): ...\n\n\ndef test_my_iter(m1: MyIter1[int], m2: MyIter2[int]):\n assert_type(next(m1), int)\n assert_type(next(m2), int)\n\n\nK = TypeVar(\"K\")\nV = TypeVar(\"V\")\n\n\nclass MyMap1(Mapping[K, V], Generic[K, V]): ...\n\n\nclass MyMap2(Mapping[K, V], Generic[V, K]): ...\n\n\ndef test_my_map(m1: MyMap1[str, int], m2: MyMap2[int, str]):\n assert_type(m1[\"key\"], int)\n assert_type(m2[\"key\"], int)\n\n m1[0] # E\n m2[0] # E\n\n# > All arguments to ``Generic`` or ``Protocol`` must be type variables.\n\nclass Bad1(Generic[int]): ... # E\nclass Bad2(Protocol[int]): ... # E\n\n# > All type parameters for the class must appear within the ``Generic`` or\n# > ``Protocol`` type argument list.\n\nT_co = TypeVar(\"T_co\", covariant=True)\nS_co = TypeVar(\"S_co\", covariant=True)\n\nclass Bad3(Iterable[T_co], Generic[S_co]): ... # E\nclass Bad4(Iterable[T_co], Protocol[S_co]): ... # E\n\n# > The above rule does not apply to a bare ``Protocol`` base class.\n\nclass MyIterator(Iterator[T_co], Protocol): ... # OK\n\n# > You can use multiple inheritance with ``Generic``\n\nfrom collections.abc import Sized, Container\n\n\nclass LinkedList(Sized, Generic[T]): ...\n\n\nclass MyMapping(Iterable[tuple[K, V]], Container[tuple[K, V]], Generic[K, V]): ...\n\n\n# > Subclassing a generic class without specifying type parameters assumes\n# > ``Any`` for each position. In the following example, ``MyIterable``\n# > is not generic but implicitly inherits from ``Iterable[Any]``::\n\n\nclass MyIterableAny(Iterable): # Same as Iterable[Any]\n ...\n\n\ndef test_my_iterable_any(m: MyIterableAny):\n assert_type(iter(m), Iterator[Any])\n\n\n# > Generic metaclasses are not supported\n\n\nclass GenericMeta(type, Generic[T]): ...\n\n\nclass GenericMetaInstance(metaclass=GenericMeta[T]): # E\n ...\n\n\n# When a typevar appears in multiple parameters, we can (but are not required\n# to) infer a \"combined\" specialization that satisfies all of the corresponding\n# arguments. This is especially interesting for list literals, since `list` is\n# invariant in its typevar. We can use the surrounding context of the generic\n# function call to infer a wider type for the list literals that allows the call\n# to succeed.\n\ndef takes_two_lists(x: list[T], y: list[T]) -> T:\n return x[0]\n\n\ntakes_two_lists([1], \"not a list\") # E: no assignment of T makes the second argument valid\ntakes_two_lists([\"\"], [\"\"]) # T = str or T = Literal[\"\"]\ntakes_two_lists([1], [\"\"]) # E?: T = int | str is a potential solution\n\ndef test_specific_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[str] = [\"\"]\n assert_type(takes_two_lists(x, y), int)\n takes_two_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n\n\nT_int = TypeVar(\"T_int\", bound=int)\n\ndef takes_two_int_lists(x: list[T_int], y: list[T_int]) -> T_int:\n return x[0]\n\ntakes_two_int_lists([1], \"not a list\") # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [\"\"]) # E: no assignment of T_int makes the second argument valid\ntakes_two_int_lists([1], [1]) # T = int or T = Literal[1]\ntakes_two_int_lists([True], [True]) # T = bool or T = Literal[True]\ntakes_two_int_lists([1], [True]) # E?: T = int | bool = int is a potential solution\n\ndef test_specific_int_lists() -> None:\n x: list[int] = [1]\n y: list[int] = [1]\n z: list[bool] = [True]\n assert_type(takes_two_int_lists(x, y), int)\n takes_two_int_lists(x, z) # E: because lists are invariant, no assignment of T makes both arguments valid\n","source":"typing_tests","origin":"conformance/tests/generics_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_15.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#scoping-rules-for-type-variables\n\nfrom typing import TypeVar, Generic, Iterable, TypeAlias, assert_type, Literal\n\n# > A type variable used in a generic function could be inferred to represent\n# > different types in the same code block.\nT = TypeVar('T')\n\ndef fun_1(x: T) -> T: # T here\n return x\ndef fun_2(x: T) -> T: # and here could be different\n return x\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_1(1), int) # E[fun1]\nassert_type(fun_1(1), Literal[1]) # E[fun1]\n\n# One of these two should pass; either is acceptable:\nassert_type(fun_2(\"a\"), str) # E[fun2]\nassert_type(fun_2(\"a\"), Literal[\"a\"]) # E[fun2]\n\n# > A type variable used in a method of a generic class that coincides\n# > with one of the variables that parameterize this class is always bound\n# > to that variable.\n\nclass MyClass(Generic[T]):\n def meth_1(self, x: T) -> T: # T here\n return x\n def meth_2(self, x: T) -> T: # and here are always the same\n return x\n\na: MyClass[int] = MyClass()\na.meth_1(1) # OK\na.meth_2('a') # E\n\n# > A type variable used in a method that does not match any of the variables\n# > that parameterize the class makes this method a generic function in that\n# > variable.\n\nS = TypeVar(\"S\")\n\nclass Foo(Generic[T]):\n def method(self, x: T, y: S) -> S:\n return y\n\nx: Foo[int] = Foo()\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, \"abc\"), str) # E[method-str]\nassert_type(x.method(0, \"abc\"), Literal[\"abc\"]) # E[method-str]\n\n# Either of these is acceptable; one of the two should pass:\nassert_type(x.method(0, b\"abc\"), bytes) # E[method-bytes]\nassert_type(x.method(0, b\"abc\"), Literal[b\"abc\"]) # E[method-bytes]\n\n# > Unbound type variables should not appear in the bodies of generic functions,\n# > or in the class bodies apart from method definitions.\n\ndef fun_3(x: T) -> list[T]:\n y: list[T] = [] # OK\n z: list[S] = [] # E\n return y\n\nclass Bar(Generic[T]):\n an_attr: list[S] = [] # E\n\n def do_something(self, x: S) -> S: # OK\n return x\n\n# A generic class definition that appears inside a generic function\n# should not use type variables that parameterize the generic function.\n\ndef fun_4(x: T) -> list[T]:\n a_list: list[T] = [] # OK\n\n class MyGeneric(Generic[T]): # E\n ...\n\n return a_list\n\n# > A generic class nested in another generic class cannot use the same type\n# > variables. The scope of the type variables of the outer class\n# > doesn't cover the inner one\n\nclass Outer(Generic[T]):\n class Bad(Iterable[T]): # E\n ...\n class AlsoBad:\n x: list[T] # E\n\n def __init__(self, x: list[T]) -> None: # E?\n self.x = x\n\n class Inner(Iterable[S]): # OK\n ...\n attr: Inner[T] # OK\n\n alias: TypeAlias = list[T] # E\n\n def __init__(self, attr: Inner[T]) -> None:\n self.attr = attr\n\n\n# Test unbound type variables at global scope\nglobal_var1: T # E\nglobal_var2: list[T] = [] # E\nlist[T]() # E\n","source":"typing_tests","origin":"conformance/tests/generics_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_16.py","code":"# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#instantiating-generic-classes-and-type-erasure\n\nfrom typing import Any, TypeVar, Generic, assert_type\n\nT = TypeVar(\"T\")\n\n# > If the constructor (__init__ or __new__) uses T in its signature, and a\n# > corresponding argument value is passed, the type of the corresponding\n# > argument(s) is substituted. Otherwise, Any is assumed.\n\nclass Node(Generic[T]):\n label: T\n def __init__(self, label: T | None = None) -> None:\n if label is not None:\n self.label = label\n\nassert_type(Node(''), Node[str])\nassert_type(Node(0), Node[int])\nassert_type(Node(), Node[Any])\n\nassert_type(Node(0).label, int)\nassert_type(Node().label, Any)\n\n# > In case the inferred type uses [Any] but the intended type is more specific,\n# > you can use an annotation to force the type of the variable, e.g.:\n\nn1: Node[int] = Node()\nassert_type(n1, Node[int])\nn2: Node[str] = Node()\nassert_type(n2, Node[str])\n\nn3 = Node[int]()\nassert_type(n3, Node[int])\nn4 = Node[str]()\nassert_type(n4, Node[str])\n\nn5 = Node[int](0) # OK\nn6 = Node[int](\"\") # E\nn7 = Node[str](\"\") # OK\nn8 = Node[str](0) # E\n\nNode[int].label = 1 # E\nNode[int].label # E\nNode.label = 1 # E\nNode.label # E\ntype(n1).label # E?\nassert_type(n1.label, int)\nassert_type(Node[int]().label, int)\nn1.label = 1 # OK\n\n# > [...] generic versions of concrete collections can be instantiated:\n\nfrom typing import DefaultDict\n\ndata = DefaultDict[int, bytes]()\nassert_type(data[0], bytes)\n","source":"typing_tests","origin":"conformance/tests/generics_type_erasure.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_17.py","code":"\"\"\"\nTests TypeVars with upper bounds.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variables-with-an-upper-bound\n\nfrom typing import Collection, Generic, Sized, TypeVar, assert_type\n\n# > A type variable may specify an upper bound using bound=\n\nT_Good1 = TypeVar(\"T_Good1\", bound=int) # OK\nT_Good2 = TypeVar(\"T_Good2\", bound=\"ForwardRef | str\") # OK\n\n\nclass ForwardRef: ...\n\n\n# > itself cannot be parameterized by type variables.\n\nT = TypeVar(\"T\")\n\n\nclass Test(Generic[T]):\n T_Bad1 = TypeVar(\"T_Bad1\", bound=list[T]) # E\n\n\nST = TypeVar(\"ST\", bound=Sized)\n\n\ndef longer(x: ST, y: ST) -> ST:\n if len(x) > len(y):\n return x\n else:\n return y\n\n\ndef f(list1: list[int], list2: list[int], set1: set[int], set2: set[int]):\n assert_type(longer(list1, list2), list[int])\n assert_type(longer(set1, set2), set[int])\n\n # Either answer here is conformant with the spec;\n # exactly one should pass:\n assert_type(longer(list1, set1), list[int] | set[int]) # E[mixed-collections]\n assert_type(longer(list1, set1), Collection[int]) # E[mixed-collections]\n\n\ndef requires_collection(c: Collection[int]) -> None: ...\n\n\nrequires_collection(longer([1], [1, 2])) # OK\n\nlonger(3, 3) # E\n\n\n# > An upper bound cannot be combined with type constraints\n\nT_Bad2 = TypeVar(\"T_Bad2\", str, int, bound=\"int\") # E\n","source":"typing_tests","origin":"conformance/tests/generics_upper_bound.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_18.py","code":"\"\"\"\nTests the handling and enforcement of TypeVar variance.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance\n\nfrom typing import Sequence, TypeVar, Generic\nfrom collections.abc import Iterable, Iterator\n\n# > To facilitate the declaration of container types where covariant or\n# > contravariant type checking is acceptable, type variables accept\n# > keyword arguments covariant=True or contravariant=True. At most one of\n# > these may be passed.\nX1 = TypeVar(\"X1\", covariant=True, contravariant=True) # E\n\n\nT = TypeVar(\"T\")\nT_co = TypeVar(\"T_co\", covariant=True)\nT_contra = TypeVar(\"T_contra\", contravariant=True)\n\n\nclass ImmutableList(Generic[T_co]):\n def __init__(self, items: Iterable[T_co]) -> None:\n ...\n\n def __iter__(self) -> Iterator[T_co]:\n raise NotImplementedError\n\n\nclass Employee:\n ...\n\n\nclass Manager(Employee):\n ...\n\n\nmanagers: ImmutableList[Manager] = ImmutableList([Manager()])\nemployees: ImmutableList[Employee] = managers # OK\n\n\nE = TypeVar(\"E\", bound=Employee)\n\n\ndef dump_employee(e: E) -> E:\n return e\n\n\ndump_employee(Manager()) # OK\n\n\nB_co = TypeVar(\"B_co\", covariant=True)\n\n\n# > Variance has no meaning, and should therefore be ignored by type checkers,\n# > if a type variable is bound to a generic function or type alias.\ndef func(x: list[B_co]) -> B_co: # OK\n raise NotImplementedError\n\n\nclass Co(Generic[T_co]):\n ...\n\n\nclass Contra(Generic[T_contra]):\n ...\n\n\nclass Inv(Generic[T]):\n ...\n\n\nclass CoContra(Generic[T_co, T_contra]):\n ...\n\n\nclass Class1(Inv[T_co]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Class2(Inv[T_contra]): # E: Inv requires invariant TypeVar\n pass\n\n\nclass Co_Child1(Co[T_co]): # OK\n ...\n\n\nclass Co_Child2(Co[T]): # OK\n ...\n\n\nclass Co_Child3(Co[T_contra]): # E: Co requires covariant\n ...\n\n\nclass Contra_Child1(Contra[T_contra]): # OK\n ...\n\n\nclass Contra_Child2(Contra[T]): # OK\n ...\n\n\nclass Contra_Child3(Contra[T_co]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child4(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass Contra_Child5(Contra[Co[T_co]]): # E: Contra requires contravariant\n ...\n\n\nclass Contra_Child6(Contra[Co[T]]): # OK\n ...\n\n\nclass CoContra_Child1(CoContra[T_co, T_contra]): # OK\n ...\n\n\nclass CoContra_Child2( # E[CoContra_Child2]: Second type arg must be contravariant\n CoContra[T_co, T_co] # E[CoContra_Child2]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoContra_Child3( # E[CoContra_Child3]: First type arg must be covariant\n CoContra[T_contra, T_contra] # E[CoContra_Child3]: First type arg must be covariant\n):\n ...\n\n\nclass CoContra_Child4(CoContra[T, T]): # OK\n ...\n\n\nclass CoContra_Child5( # E[CoContra_Child5]: Second type arg must be contravariant\n CoContra[Co[T_co], Co[T_co]] # E[CoContra_Child5]: Second type arg must be contravariant\n):\n ...\n\n\nclass CoToContra(Contra[Co[T_contra]]): # OK\n ...\n\n\nclass ContraToContra(Contra[Contra[T_co]]): # OK\n ...\n\n\nclass CoToCo(Co[Co[T_co]]): # OK\n ...\n\n\nclass ContraToCo(Co[Contra[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra(Contra[Co[Contra[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra(Contra[Contra[Contra[T_co]]]): # E\n ...\n\n\nCo_TA = Co[T_co]\nContra_TA = Contra[T_contra]\n\n\nclass CoToContra_WithTA(Contra_TA[Co_TA[T_contra]]): # OK\n ...\n\n\nclass ContraToContra_WithTA(Contra_TA[Contra_TA[T_co]]): # OK\n ...\n\n\nclass CoToCo_WithTA(Co_TA[Co_TA[T_co]]): # OK\n ...\n\n\nclass ContraToCo_WithTA(Co_TA[Contra_TA[T_contra]]): # OK\n ...\n\n\nclass CoToContraToContra_WithTA(Contra_TA[Co_TA[Contra_TA[T_contra]]]): # E\n ...\n\n\nclass ContraToContraToContra_WithTA( # E[ContraToContraToContra_WithTA]\n Contra_TA[Contra_TA[Contra_TA[T_co]]] # E[ContraToContraToContra_WithTA]\n):\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_19.py","code":"\"\"\"\nTests the behavior of typing.overload.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/overload.html#overload\n\nfrom typing import (\n Any,\n Callable,\n Iterable,\n Iterator,\n TypeVar,\n assert_type,\n overload,\n)\n\n\nclass Bytes:\n ...\n\n @overload\n def __getitem__(self, __i: int) -> int:\n ...\n\n @overload\n def __getitem__(self, __s: slice) -> bytes:\n ...\n\n def __getitem__(self, __i_or_s: int | slice) -> int | bytes:\n if isinstance(__i_or_s, int):\n return 0\n else:\n return b\"\"\n\n\nb = Bytes()\nassert_type(b[0], int)\nassert_type(b[0:1], bytes)\nb[\"\"] # E: no matching overload\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nS = TypeVar(\"S\")\n\n\n@overload\ndef map(func: Callable[[T1], S], iter1: Iterable[T1]) -> Iterator[S]:\n ...\n\n\n@overload\ndef map(\n func: Callable[[T1, T2], S], iter1: Iterable[T1], iter2: Iterable[T2]\n) -> Iterator[S]:\n ...\n\n\ndef map(func: Any, iter1: Any, iter2: Any = ...) -> Any:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_20.py","code":"\"\"\"\nTests consistency of overloads with implementation.\n\"\"\"\n\nfrom typing import Callable, Coroutine, overload\nfrom types import CoroutineType\n\n# > If an overload implementation is defined, type checkers should validate\n# > that it is consistent with all of its associated overload signatures.\n# > The implementation should accept all potential sets of arguments\n# > that are accepted by the overloads and should produce all potential return\n# > types produced by the overloads. In typing terms, this means the input\n# > signature of the implementation should be :term:`assignable` to the input\n# > signatures of all overloads, and the return type of all overloads should be\n# > assignable to the return type of the implementation.\n\n# Return type of all overloads must be assignable to return type of\n# implementation:\n\n@overload\ndef return_type(x: int) -> int:\n ...\n\n@overload\ndef return_type(x: str) -> str: # E[return_type]\n ...\n\ndef return_type(x: int | str) -> int: # E[return_type] an overload returns `str`, not assignable to `int`\n return 1\n\n\n# Input signature of implementation must be assignable to signature of each\n# overload. We don't attempt a thorough testing of input signature\n# assignability here; see `callables_subtyping.py` for that:\n\n@overload\ndef parameter_type(x: int) -> int:\n ...\n\n@overload\ndef parameter_type(x: str) -> str: # E[parameter_type]\n ...\n\ndef parameter_type(x: int) -> int | str: # E[parameter_type] impl type of `x` must be assignable from overload types of `x`\n return 1\n\n\n# > Overloads are allowed to use a mixture of ``async def`` and ``def`` statements\n# > within the same overload definition. Type checkers should convert\n# > ``async def`` statements to a non-async signature (wrapping the return\n# > type in a ``Coroutine``) before testing for implementation consistency\n# > and overlapping overloads (described below).\n\n# ...and also...\n\n# > When a type checker checks the implementation for consistency with overloads,\n# > it should first apply any transforms that change the effective type of the\n# > implementation including the presence of a ``yield`` statement in the\n# > implementation body, the use of ``async def``, and the presence of additional\n# > decorators.\n\n# An overload can explicitly return `Coroutine`, while the implementation is an\n# `async def`:\n\n@overload\ndef returns_coroutine(x: int) -> CoroutineType[None, None, int]:\n ...\n\n@overload\nasync def returns_coroutine(x: str) -> str:\n ...\n\nasync def returns_coroutine(x: int | str) -> int | str:\n return 1\n\n\n# The implementation can explicitly return `Coroutine`, while overloads are\n# `async def`:\n\n@overload\nasync def returns_coroutine_2(x: int) -> int:\n ...\n\n@overload\nasync def returns_coroutine_2(x: str) -> str:\n ...\n\ndef returns_coroutine_2(x: int | str) -> Coroutine[None, None, int | str]:\n return _wrapped(x)\n\nasync def _wrapped(x: int | str) -> int | str:\n return 2\n\n# Decorator transforms are applied before checking overload consistency:\n\ndef _deco_1(f: Callable) -> Callable[[int], int]:\n def wrapped(_x: int, /) -> int:\n return 1\n return wrapped\n\ndef _deco_2(f: Callable) -> Callable[[int | str], int | str]:\n def wrapped(_x: int | str, /) -> int | str:\n return 1\n return wrapped\n\n@overload\n@_deco_1\ndef decorated() -> None:\n ...\n\n@overload\ndef decorated(x: str, /) -> str:\n ...\n\n@_deco_2\ndef decorated(y: bytes, z: bytes) -> bytes:\n return b\"\"\n","source":"typing_tests","origin":"conformance/tests/overloads_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_21.py","code":"\"\"\"\nTests valid/invalid definition of overloaded functions.\n\"\"\"\n\nfrom abc import ABC, abstractmethod\nfrom typing import (\n final,\n Protocol,\n overload,\n override,\n)\n\n\n# > At least two @overload-decorated definitions must be present.\n@overload # E[func1]\ndef func1() -> None: # E[func1]: At least two overloads must be present\n ...\n\n\ndef func1() -> None:\n pass\n\n\n# > The ``@overload``-decorated definitions must be followed by an overload\n# > implementation, which does not include an ``@overload`` decorator. Type\n# > checkers should report an error or warning if an implementation is missing.\n@overload # E[func2]\ndef func2(x: int) -> int: # E[func2]: no implementation\n ...\n\n\n@overload\ndef func2(x: str) -> str: ...\n\n\n# > Overload definitions within stub files, protocols, and on abstract methods\n# > within abstract base classes are exempt from this check.\nclass MyProto(Protocol):\n @overload\n def func3(self, x: int) -> int: ...\n\n @overload\n def func3(self, x: str) -> str: ...\n\n\nclass MyAbstractBase(ABC):\n @overload\n @abstractmethod\n def func4(self, x: int) -> int: ...\n\n @overload\n @abstractmethod\n def func4(self, x: str) -> str: ...\n\n # A non-abstract method in an abstract base class still requires an\n # implementation:\n\n @overload # E[not_abstract]\n def not_abstract(self, x: int) -> int: # E[not_abstract] no implementation\n ...\n\n @overload\n def not_abstract(self, x: str) -> str: ...\n\n\n# > If one overload signature is decorated with ``@staticmethod`` or\n# > ``@classmethod``, all overload signatures must be similarly decorated. The\n# > implementation, if present, must also have a consistent decorator. Type\n# > checkers should report an error if these conditions are not met.\nclass C:\n @overload # E[func5]\n @staticmethod\n def func5(x: int, /) -> int: # E[func5]\n ...\n\n @overload\n @staticmethod\n def func5(x: str, /) -> str: # E[func5]\n ...\n\n def func5(*args: object) -> int | str: # E[func5]\n return 1\n\n @overload # E[func6+]\n @classmethod\n def func6(cls, x: int, /) -> int: # E[func6+]\n ...\n\n @overload\n def func6(self, x: str, /) -> str: # E[func6+]\n ...\n\n @classmethod # E[func6+]\n def func6(cls, *args: int | str) -> int | str: # E[func6+]\n return 1\n\n\n# > If a ``@final`` or ``@override`` decorator is supplied for a function with\n# > overloads, the decorator should be applied only to the overload\n# > implementation if it is present. If an overload implementation isn't present\n# > (for example, in a stub file), the ``@final`` or ``@override`` decorator\n# > should be applied only to the first overload. Type checkers should enforce\n# > these rules and generate an error when they are violated. If a ``@final`` or\n# > ``@override`` decorator follows these rules, a type checker should treat the\n# > decorator as if it is present on all overloads.\nclass Base:\n # This is a good definition of an overloaded final method (@final decorator\n # on implementation only):\n\n @overload\n def final_method(self, x: int) -> int: ...\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n @final\n def final_method(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on one of the overloads:\n\n @overload # E[invalid_final] @final should be on implementation only\n @final # E[invalid_final]\n def invalid_final(self, x: int) -> int: # E[invalid_final]\n ...\n\n @overload\n def invalid_final(self, x: str) -> str: # E[invalid_final]\n ...\n\n def invalid_final(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # The @final decorator should not be on multiple overloads and\n # implementation:\n\n @overload # E[invalid_final_2+]: @final should be on implementation only\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: int) -> int: # E[invalid_final_2+]\n ...\n\n @overload\n @final # E[invalid_final_2+]\n def invalid_final_2(self, x: str) -> str: # E[invalid_final_2+]\n ...\n\n @final\n def invalid_final_2(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # These methods are just here for the @override test below. We use an\n # overload because mypy doesn't like overriding a non-overloaded method\n # with an overloaded one, even if LSP isn't violated. That could be its own\n # specification question, but it's not what we're trying to test here:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n @overload\n def to_override(self, x: int) -> int: ...\n\n @overload\n def to_override(self, x: str) -> str: ...\n\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n\nclass Child(Base): # E[override-final]\n # The correctly-decorated @final method `Base.final_method` should cause an\n # error if overridden in a child class (we use an overload here to avoid\n # questions of override LSP compatibility and focus only on the override):\n\n @overload # E[override-final]\n def final_method(self, x: int) -> int: ... # E[override-final]\n\n @overload\n def final_method(self, x: str) -> str: ...\n\n def final_method( # E[override-final] can't override final method\n self, x: int | str\n ) -> int | str: # E[override-final] can't override final method\n raise NotImplementedError\n\n # This is the right way to mark an overload as @override (decorate\n # implementation only), so the use of @override should cause an error\n # (because there's no `Base.bad_override` method):\n\n @overload # E[bad_override] marked as override but doesn't exist in base\n def bad_override(self, x: int) -> int: # E[bad_override]\n ...\n\n @overload\n def bad_override(self, x: str) -> str: ...\n\n @override # E[bad_override]\n def bad_override(self, x: int | str) -> int | str: # E[bad_override]\n raise NotImplementedError\n\n # This is also a correctly-decorated overloaded @override, which is\n # overriding a method that does exist in the base, so there should be no\n # error. We need both this test and the previous one, because in the\n # previous test, an incorrect error about the use of @override decorator\n # could appear on the same line as the expected error about overriding a\n # method that doesn't exist in base:\n\n @overload\n def good_override(self, x: int) -> int: ...\n\n @overload\n def good_override(self, x: str) -> str: ...\n\n @override\n def good_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n\n # This is the wrong way to use @override with an overloaded method, and\n # should emit an error:\n\n @overload # E[override_impl+]: @override should appear only on implementation\n @override # E[override_impl+]\n def to_override(self, x: int) -> int: ... # E[override_impl+]\n\n @overload\n @override # E[override_impl+]\n def to_override(self, x: str) -> str: ... # E[override_impl+]\n\n @override\n def to_override(self, x: int | str) -> int | str:\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/overloads_definitions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_22.py","code":"\"\"\"\nTests for evaluation of calls to overloaded functions.\n\"\"\"\n\nfrom enum import Enum\nfrom typing import Any, assert_type, Literal, overload, TypeVar\n\n# mypy: disable-error-code=overload-overlap\n\n\nT = TypeVar(\"T\")\n\n# > Step 1: Examine the argument list to determine the number of\n# > positional and keyword arguments. Use this information to eliminate any\n# > overload candidates that are not plausible based on their\n# > input signatures.\n\n# (There is no way to observe via conformance tests whether an implementation\n# performs this step separately from the argument-type-testing step 2 below, so\n# the separation of step 1 from step 2 is purely a presentation choice for the\n# algorithm, not a conformance requirement.)\n\n\n@overload\ndef example1_1(x: int, y: str) -> int: ...\n\n\n@overload\ndef example1_1(x: str) -> str: ...\n\n\ndef example1_1(x: int | str, y: str = \"\") -> int | str:\n return 1\n\n\n# > - If no candidate overloads remain, generate an error and stop.\n\nexample1_1() # E: no matching overload\n\n# > - If only one candidate overload remains, it is the winning match. Evaluate\n# > it as if it were a non-overloaded function call and stop.\n\nret1 = example1_1(1, \"\")\nassert_type(ret1, int)\n\nexample1_1(1, 1) # E: Literal[1] not assignable to str\n\nret3 = example1_1(\"\")\nassert_type(ret3, str)\n\nexample1_1(1) # E: Literal[1] not assignable to str\n\n\n@overload\ndef example1_2(b: Literal[True] = ...) -> int: ...\n\n\n@overload\ndef example1_2(b: bool) -> float: ...\n\n\ndef example1_2(b: bool = True) -> float:\n raise NotImplementedError\n\n\ndef check_example1_2() -> None:\n assert_type(example1_2(), int)\n\n\n# > Step 2: Evaluate each remaining overload as a regular (non-overloaded)\n# > call to determine whether it is compatible with the supplied\n# > argument list. Unlike step 1, this step considers the types of the parameters\n# > and arguments. During this step, do not generate any user-visible errors.\n# > Simply record which of the overloads result in evaluation errors.\n\n\n@overload\ndef example2(x: int, y: str, z: int) -> str: ...\n\n\n@overload\ndef example2(x: int, y: int, z: int) -> int: ...\n\n\ndef example2(x: int, y: int | str, z: int) -> int | str:\n return 1\n\n\n# > - If only one overload evaluates without error, it is the winning match.\n# > Evaluate it as if it were a non-overloaded function call and stop.\n\nret5 = example2(1, 2, 3)\nassert_type(ret5, int)\n\n# > Step 3: If step 2 produces errors for all overloads, perform\n# > \"argument type expansion\". Union types can be expanded\n# > into their constituent subtypes. For example, the type ``int | str`` can\n# > be expanded into ``int`` and ``str``.\n\n# > - If all argument lists evaluate successfully, combine their\n# > respective return types by union to determine the final return type\n# > for the call, and stop.\n\n\ndef check_expand_union(v: int | str) -> None:\n ret1 = example2(1, v, 1)\n assert_type(ret1, int | str)\n\n\n# > - If argument expansion has been applied to all arguments and one or\n# > more of the expanded argument lists cannot be evaluated successfully,\n# > generate an error and stop.\n\n\ndef check_expand_union_2(v: int | str) -> None:\n example2(v, v, 1) # E: no overload matches (str, ..., ...)\n\n\n# > 2. ``bool`` should be expanded into ``Literal[True]`` and ``Literal[False]``.\n\n\n@overload\ndef expand_bool(x: Literal[False]) -> Literal[0]: ...\n\n\n@overload\ndef expand_bool(x: Literal[True]) -> Literal[1]: ...\n\n\ndef expand_bool(x: bool) -> int:\n return int(x)\n\n\ndef check_expand_bool(v: bool) -> None:\n ret1 = expand_bool(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 3. ``Enum`` types (other than those that derive from ``enum.Flag``) should\n# > be expanded into their literal members.\n\n\nclass Color(Enum):\n RED = 1\n BLUE = 2\n\n\n@overload\ndef expand_enum(x: Literal[Color.RED]) -> Literal[0]: ...\n\n\n@overload\ndef expand_enum(x: Literal[Color.BLUE]) -> Literal[1]: ...\n\n\ndef expand_enum(x: Color) -> int:\n return x.value\n\n\ndef check_expand_enum(v: Color) -> None:\n ret1 = expand_enum(v)\n assert_type(ret1, Literal[0, 1])\n\n\n# > 4. ``type[A | B]`` should be expanded into ``type[A]`` and ``type[B]``.\n\n\n@overload\ndef expand_type_union(x: type[int]) -> int: ...\n\n\n@overload\ndef expand_type_union(x: type[str]) -> str: ...\n\n\ndef expand_type_union(x: type[int] | type[str]) -> int | str:\n return 1\n\n\ndef check_expand_type_union(v: type[int | str]) -> None:\n ret1 = expand_type_union(v)\n assert_type(ret1, int | str)\n\n\n# > 5. Tuples of known length that contain expandable types should be expanded\n# > into all possible combinations of their element types. For example, the type\n# > ``tuple[int | str, bool]`` should be expanded into ``(int, Literal[True])``,\n# > ``(int, Literal[False])``, ``(str, Literal[True])``, and\n# > ``(str, Literal[False])``.\n\n\n@overload\ndef expand_tuple(x: tuple[int, int]) -> int: ...\n\n\n@overload\ndef expand_tuple(x: tuple[int, str]) -> str: ...\n\n\ndef expand_tuple(x: tuple[int, int | str]) -> int | str:\n return 1\n\n\ndef check_expand_tuple(v: int | str) -> None:\n ret1 = expand_tuple((1, v))\n assert_type(ret1, int | str)\n\n\n# > Step 4: If the argument list is compatible with two or more overloads,\n# > determine whether one or more of the overloads has a variadic parameter\n# > (either ``*args`` or ``**kwargs``) that maps to a corresponding argument\n# > that supplies an indeterminate number of positional or keyword arguments.\n# > If so, eliminate overloads that do not have a variadic parameter.\n\n\n@overload\ndef variadic(x: int, /) -> str: ...\n\n\n@overload\ndef variadic(x: int, y: int, /, *args: int) -> int: ...\n\n\ndef variadic(*args: int) -> int | str:\n return 1\n\n\n# > - If this results in only one remaining candidate overload, it is\n# > the winning match. Evaluate it as if it were a non-overloaded function\n# > call and stop.\n\n\ndef check_variadic(v: list[int]) -> None:\n ret1 = variadic(*v)\n assert_type(ret1, int)\n\n\n# > Step 5: For all arguments, determine whether all possible\n# > :term:`materializations ` of the argument's type are assignable to\n# > the corresponding parameter type for each of the remaining overloads. If so,\n# > eliminate all of the subsequent remaining overloads.\n# >\n# > If the return types are not equivalent, overload matching is ambiguous. In\n# > this case, infer a return type that is :term:`assignable` to each of the\n# > remaining return types and permits operations supported by any of them without\n# > errors, then stop. A type checker may infer ``Any`` or a more precise gradual\n# > type that satisfies these requirements.\n\n\n@overload\ndef example4(x: list[int], y: int) -> list[int]: ...\n\n\n@overload\ndef example4(x: list[str], y: str) -> list[int]: ...\n\n\n@overload\ndef example4(x: int, y: int) -> list[str]: ...\n\n\ndef example4(x: list[int] | list[str] | int, y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example4(v1: list[Any], v2: Any) -> None:\n ret1 = example4(v1, v2)\n assert_type(ret1, list[int])\n\n ret2 = example4(v2, 1)\n int_list: list[int] = ret2\n str_list: list[str] = ret2\n\n\n@overload\ndef example5(obj: list[int]) -> list[int]: ...\n\n\n@overload\ndef example5(obj: list[str]) -> list[str]: ...\n\n\ndef example5(obj: Any) -> list[Any]:\n return []\n\n\ndef check_example5(b: list[Any]) -> None:\n ret = example5(b)\n int_list: list[int] = ret\n str_list: list[str] = ret\n\n\n@overload\ndef example6(a: int, b: Any) -> float: ...\n\n\n@overload\ndef example6(a: float, b: T) -> T: ...\n\n\ndef example6(a: float, b: T) -> T:\n raise NotImplementedError\n\n\ndef check_example6(a: list[Any], b: Any, c: str) -> None:\n m: list[int] = []\n\n # All possible materializations of list[Any] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v1 = example6(1, a)\n assert_type(v1, float)\n\n # All possible materializations of Any are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v2 = example6(1, b)\n assert_type(v2, float)\n\n # All possible materializations of list[int] are\n # assignable to Any, so this matches the first overload\n # and eliminates all subsequent overloads.\n v3 = example6(1, m)\n assert_type(v3, float)\n\n v4 = example6(1.0, c)\n assert_type(v4, str)\n\n v5 = example6(1.0, b)\n assert_type(v5, Any)\n\n v6 = example6(1.0, m)\n assert_type(v6, list[int])\n\n\n@overload\ndef example7(x: list[Any], y: int) -> list[int]: ...\n\n\n@overload\ndef example7(x: list[Any], y: str) -> list[str]: ...\n\n\ndef example7(x: list[Any], y: int | str) -> list[int] | list[str]:\n return []\n\n\ndef check_example7(v1: list[Any], v2: Any) -> None:\n ret1 = example7(v1, 1)\n assert_type(ret1, list[int])\n\n ret2 = example7(v1, \"\")\n assert_type(ret2, list[str])\n\n ret3 = example7(v1, v2)\n int_list: list[int] = ret3\n str_list: list[str] = ret3\n\n\n# The earlier ambiguity cases check assignability of list return types. This\n# checks distinct scalar return types and operations specific to each type.\n\n\ndef check_ambiguous_scalar_return(v: Any) -> None:\n ret = example2(1, v, 1)\n int_result: int = ret\n str_result: str = ret\n _ = ret + 1\n ret.upper()\n","source":"typing_tests","origin":"conformance/tests/overloads_evaluation.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_23.py","code":"\"\"\"\nTests the typing.Any special type.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#any\n\n# > Every type is consistent with Any.\n\nfrom typing import Any, Callable, assert_type\n\n\nval1: Any\nval1 = \"\" # OK\nval1 = 1 # OK\n\nval2: list[Any]\nval2 = [\"\"] # OK\nval2 = [1] # OK\n\n\ndef func1(val1: Any, val2: list[Any]) -> int:\n t1: int = val1 # OK\n t2: str = val1 # OK\n\n t3: list[str] = val2 # OK\n t4: list[int] = val2 # OK\n\n return val1 # OK\n\n\n# > A function parameter without an annotation is assumed to be annotated with Any.\n\n\ndef func2(val):\n assert_type(val, Any)\n\n t1: int = val # OK\n t2: str = val # OK\n\n return 1 # OK\n\n\n# > If a generic type is used without specifying type parameters, they are\n# > assumed to be Any.\n\n\ndef func3(val1: list, val2: dict) -> None:\n assert_type(val1, list[Any])\n assert_type(val2, dict[Any, Any])\n\n t1: list[str] = val1 # OK\n t2: list[int] = val1 # OK\n\n t3: dict[str, str] = val2 # OK\n\n\n# > This rule also applies to tuple, in annotation context it is equivalent\n# > to tuple[Any, ...].\n\n\ndef func4(val1: tuple) -> None:\n assert_type(val1, tuple[Any, ...])\n\n t1: tuple[str, ...] = val1 # OK\n t2: tuple[int, ...] = val1 # OK\n\n\n# > As well, a bare Callable in an annotation is equivalent to Callable[..., Any].\n\n\ndef func5(val1: Callable):\n assert_type(val1, Callable[..., Any])\n\n t1: Callable[[], Any] = val1 # OK\n t2: Callable[[int, str], None] = val1 # OK\n\n\n# > Any can also be used as a base class. This can be useful for avoiding type\n# > checker errors with classes that can duck type anywhere or are highly dynamic.\n\nclass ClassA(Any):\n def method1(self) -> int:\n return 1\n\na = ClassA()\nassert_type(a.method1(), int)\nassert_type(a.method2(), Any)\nassert_type(ClassA.method3(), Any)\n","source":"typing_tests","origin":"conformance/tests/specialtypes_any.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_24.py","code":"\"\"\"\nTests the handling of builtins.None in a type annotation.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#none\n\nfrom types import NoneType\nfrom typing import Hashable, Iterable, assert_type\n\n\n# > When used in a type hint, the expression None is considered equivalent to type(None).\n\n\ndef func1(val1: None) -> None:\n assert_type(val1, None)\n t1: None = None\n return None # OK\n\n\nfunc1(None) # OK\nfunc1(type(None)) # E\n\n# None is hashable\nnone1: Hashable = None # OK\n\n# None is not iterable\nnone2: Iterable = None # E: not iterable\n\n\nNone.__class__ # OK\nNone.__doc__ # OK\nNone.__eq__(0) # OK\n\n\ndef func2(val1: type[None]):\n assert_type(val1, type[None])\n\n\nfunc2(None.__class__) # OK\nfunc2(type(None)) # OK\nfunc2(None) # E: not compatible\n","source":"typing_tests","origin":"conformance/tests/specialtypes_none.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-hints","pep":"484","introduced_in":"3.5","form":"modern","file":"type-hints/modern_25.py","code":"\"\"\"\nTests \"type promotions\" for float and complex when they appear in annotations.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/special-types.html#special-cases-for-float-and-complex\n\nv1: float = 1\nv2: complex = 1.2\nv2 = 1\n\n\ndef func1(f: float):\n f.numerator # E\n\n if not isinstance(f, float):\n f.numerator # OK\n","source":"typing_tests","origin":"conformance/tests/specialtypes_promotions.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-is","pep":"742","introduced_in":"3.13","form":"modern","file":"type-is/modern_01.py","code":"\"\"\"\nTests TypeIs functionality.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/narrowing.html#typeis\n\nfrom collections.abc import Awaitable\nfrom typing import Any, Callable, Protocol, Self, TypeGuard, TypeVar, assert_type\nfrom typing_extensions import TypeIs\n\n\nT = TypeVar(\"T\")\n\ndef is_two_element_tuple(val: tuple[T, ...]) -> TypeIs[tuple[T, T]]:\n return len(val) == 2\n\ndef func1(names: tuple[str, str] | tuple[str, str, str]):\n if is_two_element_tuple(names):\n assert_type(names, tuple[str, str])\n else:\n assert_type(names, tuple[str, str, str])\n\n\n# > The final narrowed type may be narrower than **R**, due to the constraints of the\n# > argument's previously-known type\n\ndef is_awaitable(val: object) -> TypeIs[Awaitable[Any]]:\n return isinstance(val, Awaitable)\n\nasync def func2(val: int | Awaitable[int]):\n if is_awaitable(val):\n # Not `assert_type(val, Awaitable[int])` because a conformant\n # implementation could allow the possibility that instead it is\n # `int & Awaitable[Any]`, an awaitable subclass of int.\n x: int = await val\n return x\n else:\n # We can't say much here. The strictly correct answer is\n # (int | Awaitable[int]) & ~Awaitable[Any], but conformant implementations\n # may simplify this.\n # But it should definitely remain assignable to `int | Awaitable[int]`.\n y: int | Awaitable[int] = val\n return y\n\n\nT_A = TypeVar(\"T_A\", bound=\"A\")\n\nclass A:\n def tg_1(self, val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n @classmethod\n def tg_2(cls, val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n @staticmethod\n def tg_3(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n def tg4(self, val: object) -> TypeIs[Self]:\n return isinstance(val, type(self))\n\n def tg5(self: T_A, val: object) -> TypeIs[T_A]:\n return isinstance(val, type(self))\n\nclass B(A):\n pass\n\n# > The type narrowing behavior is applied to the first positional argument\n# > passed to the function. The function may accept additional arguments,\n# > but they are not affected by type narrowing.\n\n\ndef func3() -> None:\n val1 = object()\n if A().tg_1(val1):\n assert_type(val1, int)\n\n val2 = object()\n if A().tg_2(val2):\n assert_type(val2, int)\n\n val3 = object()\n if A.tg_2(val3):\n assert_type(val3, int)\n\n val4 = object()\n if A().tg_3(val4):\n assert_type(val4, int)\n\n val5 = object()\n if A.tg_3(val5):\n assert_type(val5, int)\n\n val6 = object()\n if B().tg4(val6):\n assert_type(val6, B)\n\n val7 = object()\n if B().tg4(val7):\n assert_type(val7, B)\n\n\n# > If a type narrowing function\n# > is implemented as an instance method or class method, the first positional\n# > argument maps to the second parameter (after self or cls).\n\nclass C:\n # Type checker should emit error here.\n def tg_1(self) -> TypeIs[int]: # E\n return False\n\n @classmethod\n # Type checker should emit error here.\n def tg_2(cls) -> TypeIs[int]: # E\n return False\n\n# > ``TypeIs`` is also valid as the return type of a callable, for example\n# > in callback protocols and in the ``Callable`` special form. In these\n# > contexts, it is treated as a subtype of bool. For example, ``Callable[..., TypeIs[int]]``\n# > is assignable to ``Callable[..., bool]``.\n\n\ndef takes_callable_bool(f: Callable[[object], bool]) -> None:\n pass\n\n\ndef takes_callable_str(f: Callable[[object], str]) -> None:\n pass\n\n\ndef simple_typeguard(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n\ntakes_callable_bool(simple_typeguard) # OK\ntakes_callable_str(simple_typeguard) # E\n\n\nclass CallableBoolProto(Protocol):\n def __call__(self, val: object) -> bool: ...\n\n\nclass CallableStrProto(Protocol):\n def __call__(self, val: object) -> str: ...\n\n\ndef takes_callable_bool_proto(f: CallableBoolProto) -> None:\n pass\n\n\ndef takes_callable_str_proto(f: CallableStrProto) -> None:\n pass\n\n\ntakes_callable_bool_proto(simple_typeguard) # OK\ntakes_callable_str_proto(simple_typeguard) # E\n\n# TypeIs and TypeGuard are not compatible with each other.\n\ndef takes_typeguard(f: Callable[[object], TypeGuard[int]]) -> None:\n pass\n\ndef takes_typeis(f: Callable[[object], TypeIs[int]]) -> None:\n pass\n\ndef is_int_typeis(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\ndef is_int_typeguard(val: object) -> TypeGuard[int]:\n return isinstance(val, int)\n\ntakes_typeguard(is_int_typeguard) # OK\ntakes_typeguard(is_int_typeis) # E\ntakes_typeis(is_int_typeguard) # E\ntakes_typeis(is_int_typeis) # OK\n\n\n# > Unlike ``TypeGuard``, ``TypeIs`` is invariant in its argument type:\n# > ``TypeIs[B]`` is not a subtype of ``TypeIs[A]``,\n# > even if ``B`` is a subtype of ``A``.\n\ndef takes_int_typeis(f: Callable[[object], TypeIs[int]]) -> None:\n pass\n\n\ndef int_typeis(val: object) -> TypeIs[int]:\n return isinstance(val, int)\n\n\ndef bool_typeis(val: object) -> TypeIs[bool]:\n return isinstance(val, bool)\n\n\ntakes_int_typeis(int_typeis) # OK\ntakes_int_typeis(bool_typeis) # E\n\n# > It is an error to narrow to a type that is not consistent with the input type\n\ndef bad_typeis(x: int) -> TypeIs[str]: # E\n return isinstance(x, str)\n\n\ndef bad_typeis_variance(x: list[object]) -> TypeIs[list[int]]: # E\n return all(isinstance(x, int) for x in x)\n","source":"typing_tests","origin":"conformance/tests/narrowing_typeis.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_15.py","code":"\"\"\"\nTests for basic usage of default values for TypeVar-like's.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#defaults-for-type-parameters.\n\nfrom typing import Any, Callable, Generic, Self, Unpack, assert_type\nfrom typing_extensions import TypeVar, ParamSpec, TypeVarTuple\n\n\nDefaultStrT = TypeVar(\"DefaultStrT\", default=str)\nDefaultIntT = TypeVar(\"DefaultIntT\", default=int)\nDefaultBoolT = TypeVar(\"DefaultBoolT\", default=bool)\nT = TypeVar(\"T\")\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\n\n# > The order for defaults should follow the standard function parameter\n# > rules, so a type parameter with no ``default`` cannot follow one with\n# > a ``default`` value. Doing so may raise a ``TypeError`` at runtime,\n# > and a type checker should flag this as an error.\n\n\nclass NonDefaultFollowsDefault(Generic[DefaultStrT, T]): ... # E: non-default TypeVars cannot follow ones with defaults\n\n\nclass NoNonDefaults(Generic[DefaultStrT, DefaultIntT]):\n x: DefaultStrT\n y: DefaultIntT\n\n\ndef test_no_non_defaults(a: NoNonDefaults, b: NoNonDefaults[str], c: NoNonDefaults[str, int]):\n assert_type(a.x, str)\n assert_type(a.y, int)\n\n assert_type(b.x, str)\n assert_type(b.y, int)\n\n assert_type(c.x, str)\n assert_type(c.y, int)\n\n\nclass OneDefault(Generic[T, DefaultBoolT]):\n x: T\n y: DefaultBoolT\n\n\ndef test_one_default(a: OneDefault[float], b: OneDefault[float, bool]):\n assert_type(a.x, float)\n assert_type(a.y, bool)\n\n assert_type(b.x, float)\n assert_type(b.y, bool)\n\n\nclass AllTheDefaults(Generic[T1, T2, DefaultStrT, DefaultIntT, DefaultBoolT]):\n x1: T1\n x2: T2\n x3: DefaultStrT\n x4: DefaultIntT\n x5: DefaultBoolT\n\n\ndef test_all_the_defaults(\n a: AllTheDefaults,\n b: AllTheDefaults[int], # E: expected 2 arguments to AllTheDefaults\n c: AllTheDefaults[int, complex],\n d: AllTheDefaults[int, complex, str, int, bool],\n e: AllTheDefaults[int, complex, str],\n f: AllTheDefaults[int, complex, str, int],\n g: AllTheDefaults[int, complex, str, int, bool],\n):\n assert_type(a.x1, Any)\n assert_type(a.x2, Any)\n assert_type(a.x3, str)\n assert_type(a.x4, int)\n assert_type(a.x5, bool)\n\n assert_type(c.x1, int)\n assert_type(c.x2, complex)\n assert_type(c.x3, str)\n assert_type(c.x4, int)\n assert_type(c.x5, bool)\n\n assert_type(d.x1, int)\n assert_type(d.x2, complex)\n assert_type(d.x3, str)\n assert_type(d.x4, int)\n assert_type(d.x5, bool)\n\n assert_type(e.x1, int)\n assert_type(e.x2, complex)\n assert_type(e.x3, str)\n assert_type(e.x4, int)\n assert_type(e.x5, bool)\n\n assert_type(f.x1, int)\n assert_type(f.x2, complex)\n assert_type(f.x3, str)\n assert_type(f.x4, int)\n assert_type(f.x5, bool)\n\n assert_type(g.x1, int)\n assert_type(g.x2, complex)\n assert_type(g.x3, str)\n assert_type(g.x4, int)\n assert_type(g.x5, bool)\n\n\n# > ``ParamSpec`` defaults are defined using the same syntax as\n# > ``TypeVar`` \\ s but use a ``list`` of types or an ellipsis\n# > literal \"``...``\" or another in-scope ``ParamSpec``.\n\nDefaultP = ParamSpec(\"DefaultP\", default=[str, int])\n\n\nclass Class_ParamSpec(Generic[DefaultP]):\n x: Callable[DefaultP, None]\n\n\ndef test_param_spec_defaults(a: Class_ParamSpec):\n assert_type(a.x, Callable[[str, int], None])\n assert_type(Class_ParamSpec(), Class_ParamSpec[str, int])\n assert_type(Class_ParamSpec[[bool, bool]](), Class_ParamSpec[bool, bool])\n\n\n# > ``TypeVarTuple`` defaults are defined using the same syntax as\n# > ``TypeVar`` \\ s, but instead of a single type, they use an unpacked tuple\n# > of types or an unpacked, in-scope ``TypeVarTuple`` (see `Scoping Rules`_).\n\nDefaultTs = TypeVarTuple(\"DefaultTs\", default=Unpack[tuple[str, int]])\n\n\nclass Class_TypeVarTuple(Generic[*DefaultTs]):\n x: tuple[*DefaultTs]\n\n\ndef test_type_var_tuple_defaults(a: Class_TypeVarTuple):\n assert_type(a.x, tuple[str, int])\n assert_type(Class_TypeVarTuple(), Class_TypeVarTuple[str, int])\n assert_type(Class_TypeVarTuple[int, bool](), Class_TypeVarTuple[int, bool])\n\n\nAnotherDefaultTs = TypeVarTuple(\"AnotherDefaultTs\", default=Unpack[DefaultTs])\n\n\n# > If both ``bound`` and ``default`` are passed, ``default`` must be a\n# > subtype of ``bound``. If not, the type checker should generate an\n# > error.\n\nOk1 = TypeVar(\"Ok1\", bound=float, default=int) # OK\nInvalid1 = TypeVar(\"Invalid1\", bound=str, default=int) # E: the bound and default are incompatible\n\n# > For constrained ``TypeVar``\\ s, the default needs to be one of the\n# > constraints. A type checker should generate an error even if it is a\n# > subtype of one of the constraints.\n\nOk2 = TypeVar(\"Ok2\", float, str, default=float) # OK\nInvalid2 = TypeVar(\"Invalid2\", float, str, default=int) # E: expected one of float or str got int\n\n\n# > In generic functions, type checkers may use a type parameter's default when the\n# > type parameter cannot be solved to anything. We leave the semantics of this\n# > usage unspecified, as ensuring the ``default`` is returned in every code path\n# > where the type parameter can go unsolved may be too hard to implement. Type\n# > checkers are free to either disallow this case or experiment with implementing\n# > support.\n\nT4 = TypeVar(\"T4\", default=int)\n\n\ndef func1(x: int | set[T4]) -> T4:\n raise NotImplementedError\n\n\nassert_type(func1(0), int) # E[optional-default-use]\nassert_type(func1(0), Any) # E[optional-default-use]\n\n\n# > A ``TypeVar`` that immediately follows a ``TypeVarTuple`` is not allowed\n# > to have a default, because it would be ambiguous whether a type argument\n# > should be bound to the ``TypeVarTuple`` or the defaulted ``TypeVar``.\n\nTs = TypeVarTuple(\"Ts\")\nT5 = TypeVar(\"T5\", default=bool)\n\n\nclass Foo5(Generic[*Ts, T5]): ... # E\n\n\n# > It is allowed to have a ``ParamSpec`` with a default following a\n# > ``TypeVarTuple`` with a default, as there can be no ambiguity between a\n# > type argument for the ``ParamSpec`` and one for the ``TypeVarTuple``.\n\nP = ParamSpec(\"P\", default=[float, bool])\n\n\nclass Foo6(Generic[*Ts, P]):\n x: tuple[*Ts]\n y: Callable[P, None]\n\n\ndef test_foo6(a: Foo6[int, str], b: Foo6[int, str, [bytes]]):\n assert_type(a.x, tuple[int, str])\n assert_type(a.y, Callable[[float, bool], None])\n\n assert_type(b.x, tuple[int, str])\n assert_type(b.y, Callable[[bytes], None])\n\n\n# > Type parameter defaults should be bound by attribute access\n# > (including call and subscript).\n\n\nclass Foo7(Generic[DefaultIntT]):\n def meth(self, /) -> Self:\n return self\n\n attr: DefaultIntT\n\n\nfoo7 = Foo7()\nassert_type(Foo7.meth(foo7), Foo7[int])\nassert_type(Foo7().attr, int)\n","source":"typing_tests","origin":"conformance/tests/generics_defaults.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_16.py","code":"\"\"\"\nTests for type parameter default values that reference other type parameters.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#defaults-for-type-parameters.\n\n# > To use another type parameter as a default the ``default`` and the\n# > type parameter must be the same type (a ``TypeVar``'s default must be\n# > a ``TypeVar``, etc.).\n\nfrom typing import Any, Generic, assert_type\nfrom typing_extensions import TypeVar\n\nDefaultStrT = TypeVar(\"DefaultStrT\", default=str)\nStartT = TypeVar(\"StartT\", default=int)\nStopT = TypeVar(\"StopT\", default=StartT)\nStepT = TypeVar(\"StepT\", default=int | None)\n\n\nclass slice(Generic[StartT, StopT, StepT]): ...\n\n\nassert_type(slice(), slice[int, int, int | None])\nassert_type(slice[str](), slice[str, str, int | None])\nassert_type(slice[str, bool, complex](), slice[str, bool, complex])\n\nT2 = TypeVar(\"T2\", default=DefaultStrT)\n\n\nclass Foo(Generic[DefaultStrT, T2]):\n def __init__(self, a: DefaultStrT, b: T2) -> None: ...\n\n\ndef func1(i: int, s: str) -> None:\n assert_type(Foo(i, s), Foo[int, str])\n Foo[int](i, s) # E: Foo[int, str] cannot be assigned to self: Foo[int, int] in Foo.__init__\n Foo[int](s, i) # E: Foo[str, int] cannot be assigned to self: Foo[int, int] in Foo.__init__\n\n\n# > ``T1`` must be used before ``T2`` in the parameter list of the generic.\n\nS1 = TypeVar(\"S1\")\nS2 = TypeVar(\"S2\", default=S1)\n\n\nclass Foo2(Generic[S1, S2]): ... # OK\n\n\nStart2T = TypeVar(\"Start2T\", default=\"StopT\")\nStop2T = TypeVar(\"Stop2T\", default=int)\n\n\nclass slice2(Generic[Start2T, Stop2T, StepT]): ... # E: bad ordering\n\n\n# > Using a type parameter from an outer scope as a default is not supported.\n\n\nclass Foo3(Generic[S1]):\n class Bar2(Generic[S2]): ... # E\n\n\n# > ``T1``'s bound must be a subtype of ``T2``'s bound.\n\nX1 = TypeVar(\"X1\", bound=int)\nOk1 = TypeVar(\"Ok1\", default=X1, bound=float) # OK\nAlsoOk1 = TypeVar(\"AlsoOk1\", default=X1, bound=int) # OK\nInvalid1 = TypeVar(\"Invalid1\", default=X1, bound=str) # E: int is not a subtype of str\n\n\n# > The constraints of ``T2`` must be a superset of the constraints of ``T1``.\n\nY1 = TypeVar(\"Y1\", bound=int)\nInvalid2 = TypeVar(\"Invalid2\", float, str, default=Y1) # E: upper bound int is incompatible with constraints float or str\n\nY2 = TypeVar(\"Y2\", int, str)\nAlsoOk2 = TypeVar(\"AlsoOk2\", int, str, bool, default=Y2) # OK\nAlsoInvalid2 = TypeVar(\"AlsoInvalid2\", bool, complex, default=Y2) # E: {bool, complex} is not a superset of {int, str}\n\n\n# > Type parameters are valid as parameters to generics inside of a\n# > ``default`` when the first parameter is in scope as determined by the\n# > `previous section `_.\n\n\nZ1 = TypeVar(\"Z1\")\nListDefaultT = TypeVar(\"ListDefaultT\", default=list[Z1]) # OK\n\n\nclass Bar(Generic[Z1, ListDefaultT]): # OK\n x: Z1\n y: ListDefaultT\n def __init__(self, x: Z1, y: ListDefaultT): ...\n\n\ndef f(b1: Bar, b2: Bar[int]):\n assert_type(b1.x, Any)\n assert_type(b1.y, list[Any])\n assert_type(b2.x, int)\n assert_type(b2.y, list[int])\n\n\nassert_type(Bar[int](0, []), Bar[int, list[int]])\nassert_type(Bar[int, list[str]](0, []), Bar[int, list[str]])\nassert_type(Bar[int, str](0, \"\"), Bar[int, str])\n","source":"typing_tests","origin":"conformance/tests/generics_defaults_referential.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-param-defaults","pep":"696","introduced_in":"3.13","form":"modern","file":"type-param-defaults/modern_17.py","code":"\"\"\"\nTests for specialization rules associated with type parameters with\ndefault values.\n\"\"\"\n\n# > A generic type alias can be further subscripted following normal subscription\n# > rules. If a type parameter has a default that hasn't been overridden, it should\n# > be treated like it was substituted into the type alias.\n\nfrom typing import Generic, TypeAlias, assert_type\nfrom typing_extensions import TypeVar\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nDefaultIntT = TypeVar(\"DefaultIntT\", default=int)\nDefaultStrT = TypeVar(\"DefaultStrT\", default=str)\n\n\nclass SomethingWithNoDefaults(Generic[T1, T2]): ...\n\n\nMyAlias: TypeAlias = SomethingWithNoDefaults[int, DefaultStrT] # OK\n\n\ndef func1(p1: MyAlias, p2: MyAlias[bool]):\n assert_type(p1, SomethingWithNoDefaults[int, str])\n assert_type(p2, SomethingWithNoDefaults[int, bool])\n\n\nMyAlias[bool, int] # E: too many arguments passed to MyAlias\n\n\n# > Generic classes with type parameters that have defaults behave similarly\n# > generic type aliases. That is, subclasses can be further subscripted following\n# > normal subscription rules, non-overridden defaults should be substituted.\n\n\nclass SubclassMe(Generic[T1, DefaultStrT]):\n x: DefaultStrT\n\n\nclass Bar(SubclassMe[int, DefaultStrT]): ...\n\n\nx1: type[Bar[str]] = Bar # ok\n# Type checkers may take type context into account when deciding how to\n# specialize a bare runtime reference to a generic class.\nx2: type[Bar[int]] = Bar # E?\nassert_type(Bar(), Bar[str])\nassert_type(Bar[bool](), Bar[bool])\n\n\nclass Foo(SubclassMe[float]): ...\n\n\nassert_type(Foo().x, str)\n\nFoo[str] # E: Foo cannot be further subscripted\n\n\nclass Baz(Generic[DefaultIntT, DefaultStrT]): ...\n\n\nclass Spam(Baz): ...\n\n\n# Spam is \nv1: Baz[int, str] = Spam()\n","source":"typing_tests","origin":"conformance/tests/generics_defaults_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_15.py","code":"\"\"\"\nTests the \"type\" statement introduced in Python 3.12.\n\"\"\"\n\nfrom typing import Callable, TypeVar\n\n\ntype GoodAlias1 = int\ntype GoodAlias2[S1, *S2, **S3] = Callable[S3, S1] | tuple[*S2]\ntype GoodAlias3 = GoodAlias2[int, tuple[int, str], ...]\n\n\nclass ClassA:\n type GoodAlias4 = int | None\n\n\nGoodAlias1.bit_count # E: cannot access attribute\n\nGoodAlias1() # E: cannot call alias\n\nprint(GoodAlias1.__value__) # OK\nprint(GoodAlias1.__type_params__) # OK\nprint(GoodAlias1.other_attrib) # E: unknown attribute\n\n\nclass DerivedInt(GoodAlias1): # E: cannot use alias as base class\n pass\n\n\ndef func2(x: object):\n if isinstance(x, GoodAlias1): # E: cannot use alias in isinstance\n pass\n\nvar1 = 1\n\n# The following should not be allowed as type aliases.\ntype BadTypeAlias1 = eval(\"\".join(map(chr, [105, 110, 116]))) # E\ntype BadTypeAlias2 = [int, str] # E\ntype BadTypeAlias3 = ((int, str),) # E\ntype BadTypeAlias4 = [int for i in range(1)] # E\ntype BadTypeAlias5 = {\"a\": \"b\"} # E\ntype BadTypeAlias6 = (lambda: int)() # E\ntype BadTypeAlias7 = [int][0] # E\ntype BadTypeAlias8 = int if 1 < 3 else str # E\ntype BadTypeAlias9 = var1 # E\ntype BadTypeAlias10 = True # E\ntype BadTypeAlias11 = 1 # E\ntype BadTypeAlias12 = list or set # E\ntype BadTypeAlias13 = f\"{'int'}\" # E\n\nV = TypeVar(\"V\")\n\ntype TA1[K] = dict[K, V] # E: combines old and new TypeVars\n\n\nT1 = TypeVar(\"T1\")\n\ntype TA2 = list[T1] # E: uses old TypeVar\n\n\ntype RecursiveTypeAlias1[T] = T | list[RecursiveTypeAlias1[T]]\n\nr1_1: RecursiveTypeAlias1[int] = 1\nr1_2: RecursiveTypeAlias1[int] = [1, [1, 2, 3]]\n\ntype RecursiveTypeAlias2[S: int, T: str, **P] = Callable[P, T] | list[S] | list[RecursiveTypeAlias2[S, T, P]]\n\nr2_1: RecursiveTypeAlias2[str, str, ...] # E: not compatible with S bound\nr2_2: RecursiveTypeAlias2[int, str, ...]\nr2_3: RecursiveTypeAlias2[int, int, ...] # E: not compatible with T bound\nr2_4: RecursiveTypeAlias2[int, str, [int, str]]\n\ntype RecursiveTypeAlias3 = RecursiveTypeAlias3 # E: circular definition\n\ntype RecursiveTypeAlias4[T] = T | RecursiveTypeAlias4[str] # E: circular definition\n\ntype RecursiveTypeAlias5[T] = T | list[RecursiveTypeAlias5[T]]\n\ntype RecursiveTypeAlias6 = RecursiveTypeAlias7 # E[RTA6+]: circular definition\ntype RecursiveTypeAlias7 = RecursiveTypeAlias6 # E[RTA6+]: circular definition\n","source":"typing_tests","origin":"conformance/tests/aliases_type_statement.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_16.py","code":"\"\"\"\nTests the TypeAliasType call introduced in Python 3.12.\n\"\"\"\n\nfrom typing import Callable, Generic, ParamSpec, TypeAliasType, TypeVar, TypeVarTuple\n\nS = TypeVar(\"S\")\nT = TypeVar(\"T\")\nTStr = TypeVar(\"TStr\", bound=str)\nP = ParamSpec(\"P\")\nTs = TypeVarTuple(\"Ts\")\n\nmy_tuple = (S, T)\nvar1 = 3\n\nGoodAlias1 = TypeAliasType(\"GoodAlias1\", int)\nGoodAlias2 = TypeAliasType(\"GoodAlias2\", list[T], type_params=(T,))\nGoodAlias3 = TypeAliasType(\"GoodAlias3\", list[T] | list[S], type_params=(S, T))\nGoodAlias4 = TypeAliasType(\"GoodAlias4\", T | \"list[GoodAlias4[T]]\", type_params=(T,))\nGoodAlias5 = TypeAliasType(\n \"GoodAlias5\",\n Callable[P, TStr] | list[S] | list[\"GoodAlias5[S, TStr, P]\"] | tuple[*Ts],\n type_params=(S, TStr, P, Ts),\n)\n\nclass ClassA(Generic[T]):\n GoodAlias6 = TypeAliasType(\"GoodAlias6\", list[T])\n\n\nprint(GoodAlias1.__value__) # OK\nprint(GoodAlias1.__type_params__) # OK\nprint(GoodAlias1.other_attrib) # E: unknown attribute\n\n\nx1: GoodAlias4[int] = 1 # OK\nx2: GoodAlias4[int] = [1] # OK\nx3: GoodAlias5[str, str, ..., int, str] # OK\nx4: GoodAlias5[int, str, ..., int, str] # OK\nx5: GoodAlias5[int, str, [int, str], *tuple[int, str, int]] # OK\nx6: GoodAlias5[int, int, ...] # E: incorrect type arguments\n\n\nBadAlias1 = TypeAliasType(\"BadAlias1\", list[S], type_params=(T,)) # E: S not in scope\nBadAlias2 = TypeAliasType(\"BadAlias2\", list[S]) # E: S not in scope\nBadAlias3 = TypeAliasType(\"BadAlias3\", int, type_params=my_tuple) # E: not literal tuple\nBadAlias4 = TypeAliasType(\"BadAlias4\", \"BadAlias4\") # E: circular dependency\nBadAlias5 = TypeAliasType(\"BadAlias5\", T | \"BadAlias5[str]\", type_params=(T,)) # E: circular dependency\nBadAlias6 = TypeAliasType(\"BadAlias6\", \"BadAlias7\") # E: circular dependency\nBadAlias7 = TypeAliasType(\"BadAlias7\", BadAlias6) # E?: circular dependency\n\n# The following are invalid type expressions for a type alias.\nBadAlias8 = TypeAliasType(\"BadAlias8\", eval(\"\".join(map(chr, [105, 110, 116])))) # E\nBadAlias9 = TypeAliasType(\"BadAlias9\", [int, str]) # E\nBadAlias10 = TypeAliasType(\"BadAlias10\", ((int, str),)) # E\nBadAlias11 = TypeAliasType(\"BadAlias11\", [int for i in range(1)]) # E\nBadAlias12 = TypeAliasType(\"BadAlias12\", {\"a\": \"b\"}) # E\nBadAlias13 = TypeAliasType(\"BadAlias13\", (lambda: int)()) # E\nBadAlias14 = TypeAliasType(\"BadAlias14\", [int][0]) # E\nBadAlias15 = TypeAliasType(\"BadAlias15\", int if 1 < 3 else str) # E\nBadAlias16 = TypeAliasType(\"BadAlias16\", var1) # E\nBadAlias17 = TypeAliasType(\"BadAlias17\", True) # E\nBadAlias18 = TypeAliasType(\"BadAlias18\", 1) # E\nBadAlias19 = TypeAliasType(\"BadAlias19\", list or set) # E\nBadAlias20 = TypeAliasType(\"BadAlias20\", f\"{'int'}\") # E\n\nBadAlias21 = TypeAliasType(\"BadAlias21\", list[BadAlias21]) # E\n","source":"typing_tests","origin":"conformance/tests/aliases_typealiastype.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_17.py","code":"\"\"\"\nTests the compatibility rules between type parameter syntax (introduced in PEP 695)\nand traditional TypeVars.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#compatibility-with-traditional-typevars\n\nfrom typing import TypeVar\n\n\nK = TypeVar(\"K\")\n\n\nclass ClassA[V](dict[K, V]): # E: traditional TypeVar not allowed here\n ...\n\n\nclass ClassB[K, V](dict[K, V]): # OK\n ...\n\n\nclass ClassC[V]:\n def method1(self, a: V, b: K) -> V | K: # OK\n raise NotImplementedError\n\n def method2[M](self, a: M, b: K) -> M | K: # E\n raise NotImplementedError\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_compatibility.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_18.py","code":"\"\"\"\nValidates the type parameter syntax introduced in PEP 695.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#type-parameter-declarations\n\n\n# This generic class is parameterized by a TypeVar T, a\n# TypeVarTuple Ts, and a ParamSpec P.\nfrom typing import Generic, Protocol\n\n\nclass ChildClass[T, *Ts, **P]:\n pass\n\n\nclass ClassA[T](Generic[T]): # E: Runtime error\n ...\n\n\nclass ClassB[S, T](Protocol): # OK\n ...\n\n\nclass ClassC[S, T](Protocol[S, T]): # E\n ...\n\n\nclass ClassD[T: str]:\n def method1(self, x: T):\n x.capitalize() # OK\n x.is_integer() # E\n\n\nclass ClassE[T: dict[str, int]]: # OK\n pass\n\n\nclass ClassF[S: ForwardReference[int], T: \"ForwardReference[str]\"]: # OK\n ...\n\n\nclass ClassG[V]:\n class ClassD[T: dict[str, V]]: # E: generic type not allowed\n ...\n\n\nclass ClassH[T: [str, int]]: # E: illegal expression form\n ...\n\n\nclass ClassI[AnyStr: (str, bytes)]: # OK\n ...\n\n\nclass ClassJ[T: (ForwardReference[int], \"ForwardReference[str]\", bytes)]: # OK\n ...\n\n\nclass ClassK[T: ()]: # E: two or more types required\n ...\n\n\nclass ClassL[T: (str,)]: # E: two or more types required\n ...\n\n\nt1 = (bytes, str)\n\n\nclass ClassM[T: t1]: # E: literal tuple expression required\n ...\n\n\nclass ClassN[T: (3, bytes)]: # E: invalid expression form\n ...\n\n\nclass ClassO[T: (list[S], str)]: # E: generic type\n ...\n\n\nclass ForwardReference[T]: ...\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_declarations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_19.py","code":"\"\"\"\nTests the handling of \"infer_variance\" parameter for TypeVar.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#auto-variance-for-typevar\n\nfrom typing import Final, Generic, Iterator, overload, Sequence, TypeVar\nfrom dataclasses import dataclass\n\n\nT = TypeVar(\"T\", infer_variance=True)\nK = TypeVar(\"K\", infer_variance=True)\nV = TypeVar(\"V\", infer_variance=True)\n\nS1 = TypeVar(\"S1\", covariant=True, infer_variance=True) # E: cannot use covariant with infer_variance\n\nS2 = TypeVar(\"S2\", contravariant=True, infer_variance=True) # E: cannot use contravariant with infer_variance\n\n\nclass ShouldBeCovariant1(Generic[T]):\n def __getitem__(self, index: int) -> T:\n raise NotImplementedError\n\n def __iter__(self) -> Iterator[T]:\n raise NotImplementedError\n\n\nvco1_1: ShouldBeCovariant1[float] = ShouldBeCovariant1[int]() # OK\nvco1_2: ShouldBeCovariant1[int] = ShouldBeCovariant1[float]() # E\n\n\nclass ShouldBeCovariant2(Sequence[T]):\n @overload\n def __getitem__(self, index: int) -> T:\n ...\n @overload\n def __getitem__(self, index: slice) -> Sequence[T]:\n ...\n def __getitem__(self, index: int | slice) -> T | Sequence[T]:\n raise NotImplementedError\n\n def __len__(self) -> int:\n raise NotImplementedError\n\n\nvco2_1: ShouldBeCovariant2[float] = ShouldBeCovariant2[int]() # OK\nvco2_2: ShouldBeCovariant2[int] = ShouldBeCovariant2[float]() # E\n\n\nclass ShouldBeCovariant3(Generic[T]):\n def method1(self) -> \"ShouldBeCovariant2[T]\":\n raise NotImplementedError\n\n\nvco3_1: ShouldBeCovariant3[float] = ShouldBeCovariant3[int]() # OK\nvco3_2: ShouldBeCovariant3[int] = ShouldBeCovariant3[float]() # E\n\n\n@dataclass(frozen=True)\nclass ShouldBeCovariant4(Generic[T]):\n x: T\n\n\n# This test is problematic as of Python 3.13 because of the\n# newly synthesized \"__replace__\" method, which causes the type\n# variable to be inferred as invariant rather than covariant.\n# See https://github.com/python/mypy/issues/17623#issuecomment-2266312738\n# for details. Until we sort this out, we'll leave this test commented\n# out.\n\n# vo4_1: ShouldBeCovariant4[float] = ShouldBeCovariant4[int](1) # OK\n# vo4_4: ShouldBeCovariant4[int] = ShouldBeCovariant4[float](1.0) # E\n\n\nclass ShouldBeCovariant5(Generic[T]):\n def __init__(self, x: T) -> None:\n self._x = x\n\n @property\n def x(self) -> T:\n return self._x\n\n\nvo5_1: ShouldBeCovariant5[float] = ShouldBeCovariant5[int](1) # OK\nvo5_2: ShouldBeCovariant5[int] = ShouldBeCovariant5[float](1.0) # E\n\n\nclass ShouldBeCovariant6(Generic[T]):\n x: Final[T]\n\n def __init__(self, value: T):\n self.x = value\n\n\nvo6_1: ShouldBeCovariant6[float] = ShouldBeCovariant6[int](1) # OK\nvo6_2: ShouldBeCovariant6[int] = ShouldBeCovariant6[float](1.0) # E\n\n\nclass ShouldBeInvariant1(Generic[T]):\n def __init__(self, value: T) -> None:\n self._value = value\n\n @property\n def value(self) -> T:\n return self._value\n\n @value.setter\n def value(self, value: T):\n self._value = value\n\n\nvinv1_1: ShouldBeInvariant1[float] = ShouldBeInvariant1[int](1) # E\nvinv1_2: ShouldBeInvariant1[int] = ShouldBeInvariant1[float](1.1) # E\n\n\nclass ShouldBeInvariant2(Generic[T]):\n def __init__(self, value: T) -> None:\n self._value = value\n\n def get_value(self) -> T:\n return self._value\n\n def set_value(self, value: T):\n self._value = value\n\n\nvinv2_1: ShouldBeInvariant2[float] = ShouldBeInvariant2[int](1) # E\nvinv2_2: ShouldBeInvariant2[int] = ShouldBeInvariant2[float](1.1) # E\n\n\nclass ShouldBeInvariant3(dict[K, V]):\n pass\n\n\nvinv3_1: ShouldBeInvariant3[float, str] = ShouldBeInvariant3[int, str]() # E\nvinv3_2: ShouldBeInvariant3[int, str] = ShouldBeInvariant3[float, str]() # E\nvinv3_3: ShouldBeInvariant3[str, float] = ShouldBeInvariant3[str, int]() # E\nvinv3_4: ShouldBeInvariant3[str, int] = ShouldBeInvariant3[str, float]() # E\n\n\n@dataclass\nclass ShouldBeInvariant4[T]:\n x: T\n\n\nvinv4_1: ShouldBeInvariant4[float] = ShouldBeInvariant4[int](1) # E\n\n\nclass ShouldBeInvariant5[T]:\n def __init__(self, x: T) -> None:\n self.x = x\n\n\nvinv5_1: ShouldBeInvariant5[float] = ShouldBeInvariant5[int](1) # E\n\n\nclass ShouldBeContravariant1(Generic[T]):\n def __init__(self, value: T) -> None:\n pass\n\n def set_value(self, value: T):\n pass\n\n\nvcontra1_1: ShouldBeContravariant1[float] = ShouldBeContravariant1[int](1) # E\nvcontra1_2: ShouldBeContravariant1[int] = ShouldBeContravariant1[float](1.2) # OK\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_infer_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"type-param-syntax","pep":"695","introduced_in":"3.12","form":"modern","file":"type-param-syntax/modern_20.py","code":"\"\"\"\nTests the scoping rules for type parameter syntax introduced in PEP 695.\n\"\"\"\n\n# Specification: https://peps.python.org/pep-0695/#type-parameter-scopes\n\nfrom typing import Callable, Mapping, Sequence, TypeVar, assert_type\n\n# > A compiler error or runtime exception is generated if the definition\n# > of an earlier type parameter references a later type parameter even\n# > if the name is defined in an outer scope.\n\n\nclass ClassA[S, T: Sequence[S]]: # E\n ...\n\n\nclass ClassB[S: Sequence[T], T]: # E\n ...\n\n\nclass Foo[T]:\n ...\n\n\nprint(T) # E: Runtime error: 'T' is not defined\n\n\ndef decorator1[\n T, **P, R\n](x: type[Foo[T]]) -> Callable[[Callable[P, R]], Callable[P, R]]:\n raise NotImplementedError\n\n\n@decorator1(Foo[T]) # E: Runtime error: 'T' is not defined\nclass ClassD[T]:\n ...\n\n\ntype Alias1[K, V] = Mapping[K, V] | Sequence[K]\n\n\nS: int = int(0)\n\n\ndef outer1[S](x: str):\n S: str = x\n T: int = 1\n\n def outer2[T]():\n def inner1():\n nonlocal S # OK\n assert_type(S, str)\n # nonlocal T # Syntax error\n\n def inner2():\n global S # OK\n assert_type(S, int)\n\n\nclass Outer1:\n class Private:\n pass\n\n class Inner[T](Private, Sequence[T]): # OK\n pass\n\n def method1[T](self, a: Inner[T]) -> Inner[T]: # OK\n return a\n\n\ndef decorator2[**P, R](x: int) -> Callable[[Callable[P, R]], Callable[P, R]]:\n raise NotImplementedError\n\n\nT = int(0)\n\n\n@decorator2(T) # OK\nclass ClassE[T](Sequence[T]):\n T = int(1)\n\n def method1[T](self): # E\n ...\n\n def method2[T](self, x=T): # E\n ...\n\n def method3[T](self, x: T): # E\n ...\n\n\nT = int(0)\n\n\ndef f(a: int, b: str, c: complex):\n class Outer2[T]:\n T = a\n\n assert_type(T, int)\n\n class Inner1:\n T = b\n\n assert_type(T, str)\n\n def inner_method(self):\n assert_type(T, TypeVar)\n\n def outer_method(self):\n T = c\n\n assert_type(T, complex)\n\n def inner_func():\n assert_type(T, complex)\n","source":"typing_tests","origin":"conformance/tests/generics_syntax_scoping.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_13.py","code":"\"\"\"\nTests the \"alternative\" (non-class) syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#alternative-syntax\n\nfrom typing import TypedDict\n\n\nMovie = TypedDict(\"Movie\", {\"name\": str, \"year\": int, \"illegal key name\": bool})\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982, \"illegal key name\": True}\n\nMovieOptional = TypedDict(\"MovieOptional\", {\"name\": str, \"year\": int}, total=False)\n\nmovie_opt1: MovieOptional = {}\nmovie_opt2: MovieOptional = {\"year\": 1982}\n\n# > A type checker is only expected to accept a dictionary display expression as\n# > the second argument to TypedDict. In particular, a variable that refers to a\n# > dictionary object does not need to be supported, to simplify implementation.\nmy_dict = {\"name\": str}\nBadTypedDict1 = TypedDict(\"BadTypedDict1\", my_dict) # E\n\n\n# This should generate an error because it uses a non-str key.\nBadTypedDict2 = TypedDict(\"BadTypedDict2\", {1: str}) # E\n\n\n# This should generate an error because it uses a non-matching name.\nBadTypedDict3 = TypedDict(\"WrongName\", {\"name\": str}) # E\n\n\n# This should generate an error because of the additional parameter.\nBadTypedDict4 = TypedDict(\"BadTypedDict4\", {\"name\": str}, total=False, other=False) # E\n\n\n# > The keyword-argument syntax is deprecated in 3.11 and will be removed in 3.13.\n# > It may also be unsupported by static type checkers.\n\nMovie2 = TypedDict(\"Movie2\", name=str, year=int) # E?\n\nmovie2: Movie2\nmovie2 = {\"name\": \"Blade Runner\", \"year\": 1982} # E?: May generate errors if keyword-argument syntax is unsupported\nmovie2 = {\"name\": \"Blade Runner\", \"year\": \"\"} # E?: Incorrect type for year\n","source":"typing_tests","origin":"conformance/tests/typeddicts_alt_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_14.py","code":"\"\"\"\nTests the class syntax for defining a TypedDict.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import Generic, TypeVar, TypedDict\nimport sys\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n # > String literal forward references are valid in the value types.\n director: \"Person\"\n\n\nclass Person(TypedDict):\n name: str\n age: int\n\n\n# > Methods are not allowed, since the runtime type of a TypedDict object\n# > will always be just dict (it is never a subclass of dict).\nclass BadTypedDict1(TypedDict):\n name: str\n\n # Methods are not allowed, so this should generate an error.\n def method1(self): # E\n pass\n\n # Methods are not allowed, so this should generate an error.\n @classmethod # E[method2]\n def method2(cls): # E[method2]\n pass\n\n # Methods are not allowed, so this should generate an error.\n @staticmethod # E[method3]\n def method3(): # E[method3]\n pass\n\n\nclass CustomMeta(type):\n pass\n\n\n# > Specifying a custom metaclass is not allowed.\nclass BadTypedDict2(TypedDict, metaclass=CustomMeta): # E\n name: str\n\n\n# This should generate an error because \"other\" is not an allowed keyword argument.\nclass BadTypedDict3(TypedDict, other=True): # E\n name: str\n\n# > `if` conditions that the type checker is able to\n# > statically evaluate are also permitted (e.g. `if sys.version_info > (3, 14)`),\n# > in order to specify items that exist only under the given conditions.\nclass ConditionalField(TypedDict):\n x: int\n if sys.version_info >= (3, 12):\n y: int\n if sys.version_info >= (4, 0):\n z: int\n\n# The conformance suite runs type checkers configured to Python 3.12 or later:\nConditionalField(x=1, y=2)\nConditionalField(x=1, y=2, z=3) # E\n\n\n# > TypedDicts may be made generic by adding Generic[T] among the bases.\nT = TypeVar(\"T\")\n\n\nclass GenericTypedDict(TypedDict, Generic[T]):\n name: str\n value: T\n\n\n# > An empty TypedDict can be created by only including pass in the\n# > body (if there is a docstring, pass can be omitted):\nclass EmptyDict1(TypedDict):\n pass\n\n\nclass EmptyDict2(TypedDict):\n \"\"\"Docstring\"\"\"\n\n\nclass MovieTotal(TypedDict, total=True):\n name: str\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n","source":"typing_tests","origin":"conformance/tests/typeddicts_class_syntax.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_15.py","code":"\"\"\"\nTests inheritance rules for TypedDict classes.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#typeddict\n\nfrom typing import TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\nclass BookBasedMovie(Movie):\n based_on: str\n\nclass BookBasedMovieAlso(TypedDict):\n name: str\n year: int\n based_on: str\n\nb1: BookBasedMovie = {\"name\": \"Little Women\", \"year\": 2019, \"based_on\": \"Little Women\"}\n\nb2: BookBasedMovieAlso = b1\n\n\nclass X(TypedDict):\n x: int\n\nclass Y(TypedDict):\n y: str\n\nclass XYZ(X, Y):\n z: bool\n\nx1 = XYZ(x=1, y=\"\", z=True)\n\n# > A TypedDict cannot inherit from both a TypedDict type and a\n# > non-TypedDict base class other than Generic.\n\nclass NonTypedDict:\n pass\n\nclass BadTypedDict(TypedDict, NonTypedDict): # E\n pass\n\n\n# > Changing a field type of a parent TypedDict class in a subclass is\n# > not allowed.\n\nclass X1(TypedDict):\n x: str\n\nclass Y1(X1): # E[Y1]\n x: int # E[Y1]: cannot overwrite TypedDict field \"x\"\n\n\n# > Multiple inheritance does not allow conflict types for the same name field:\nclass X2(TypedDict):\n x: int\n\nclass Y2(TypedDict):\n x: str\n\nclass XYZ2(X2, Y2): # E: cannot overwrite TypedDict field \"x\" while merging\n xyz: bool\n","source":"typing_tests","origin":"conformance/tests/typeddicts_inheritance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_16.py","code":"\"\"\"\nTests operations provided by a TypedDict object.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#supported-and-unsupported-operations\n\n\nfrom typing import TypedDict, assert_type\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie\n\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982}\nmovie[\"name\"] = \"Other\"\nmovie[\"year\"] = 1981\n\nmovie[\"name\"] = 1982 # E: wrong type\nmovie[\"year\"] = \"\" # E: wrong type\nmovie[\"other\"] = \"\" # E: unknown key added\n\nprint(movie[\"other\"]) # E: unknown key referenced\n\nmovie = {\"name\": \"Blade Runner\"} # E: year is missing\nmovie = {\"name\": \"Blade Runner\", \"year\": 1982.1} # E: year is wrong type\n\n# > The use of a key that is not known to exist should be reported as an error.\nmovie = {\"name\": \"\", \"year\": 1900, \"other\": 2} # E: extra key\n\n\ndef func1(variable_key: str):\n # > A key that is not a literal should generally be rejected.\n movie: Movie = {variable_key: \"\", \"year\": 1900} # E: variable key\n\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"name\")\n\n# It's not clear from the spec what type this should be.\nmovie.get(\"other\") # E?\n\n\nmovie.clear() # E: clear not allowed\n\ndel movie[\"name\"] # E: del not allowed for required key\n\n\n\nclass MovieOptional(TypedDict, total=False):\n name: str\n year: int\n\n\nmovie_optional: MovieOptional = {}\n\nassert_type(movie_optional.get(\"name\"), str | None)\n\nmovie_optional.clear() # E: clear not allowed\n\ndel movie_optional[\"name\"]\n","source":"typing_tests","origin":"conformance/tests/typeddicts_operations.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_17.py","code":"\"\"\"\nTests the type consistency rules for TypedDict objects.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#type-consistency\n\nfrom typing import Any, Literal, Mapping, TypedDict\n\n\nclass A1(TypedDict):\n x: int | None\n\n\nclass B1(TypedDict):\n x: int\n\n\nb1: B1 = {\"x\": 0}\n\n# > Value types behave invariantly.\na1: A1 = b1 # E: 'B1' not compatible with 'A1'\n\n# > any TypedDict type is consistent with Mapping[str, object]\nv1: Mapping[str, object] = b1\n\n# > A TypedDict type with a required key is not consistent with a TypedDict\n# > type where the same key is a non-required key.\n\nclass A2(TypedDict, total=False):\n x: int\n\n\nclass B2(TypedDict):\n x: int\n\n\nb2: B2 = {\"x\": 0}\na2: A2 = b2 # E: 'B2' not compatible with 'A2'\n\n\n# > A TypedDict type A is consistent with TypedDict B if A is structurally\n# > compatible with B. This is true if and only if both of these conditions\n# > are satisfied:\n# > 1. For each key in B, A has the corresponding key and the corresponding\n# > value type in A is consistent with the value type in B. For each key in B,\n# > the value type in B is also consistent with the corresponding value type\n# > in A.\n# > 2. For each required key in B, the corresponding key is required in A. For\n# > each non-required key in B, the corresponding key is not required in A.\n\n\nclass A3(TypedDict):\n x: int\n\n\nclass B3(TypedDict):\n x: int\n y: int\n\n\nb3: B3 = {\"x\": 0, \"y\": 0}\na3: A3 = b3\n\na3 = {\"x\": 0}\nb3 = a3 # E\n\n\n# This should generate an error because it's a literal assignment.\na3_1: A3 = {\"x\": 0, \"y\": 0} # E\n\n# This should not generate an error.\na3_2 = b3\n\n# > A TypedDict isn’t consistent with any Dict[...] type.\n\nd1: dict[str, int] = b3 # E\nd2: dict[str, object] = b3 # E\nd3: dict[Any, Any] = b3 # E\n\n# > A TypedDict with all int values is not consistent with Mapping[str, int].\n\nm1: Mapping[str, int] = b3 # E\nm2: Mapping[str, object] = b3 # OK\nm3: Mapping[str, Any] = b3 # OK\n\n\n# Test \"get\" method.\nUserType1 = TypedDict(\"UserType1\", {\"name\": str, \"age\": int}, total=False)\nuser1: UserType1 = {\"name\": \"Bob\", \"age\": 40}\n\nname1: str = user1.get(\"name\", \"n/a\")\nage1: int = user1.get(\"age\", 42)\n\nUserType2 = TypedDict(\"UserType2\", {\"name\": str, \"age\": int})\nuser2: UserType2 = {\"name\": \"Bob\", \"age\": 40}\n\nname2: str | None = user2.get(\"name\")\n\n# The spec does not say whether type checkers should adjust the return type of `.get()`\n# to exclude `None` if it is known that the key exists. Either option is acceptable.\nname3: str = user2.get(\"name\") # E?\n\nage2: int = user2.get(\"age\", 42)\n\nage3: int | str = user2.get(\"age\", \"42\")\n\nage4: int = user2.get(\"age\", \"42\") # E?\n\n# Test nested TypedDicts.\nclass Inner1(TypedDict):\n inner_key: str\n\n\nclass Inner2(TypedDict):\n inner_key: Inner1\n\n\nclass Outer1(TypedDict):\n outer_key: Inner2\n\n\no1: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": \"hi\"}}}\n\n# This should generate an error because the inner-most value\n# should be a string.\no2: Outer1 = {\"outer_key\": {\"inner_key\": {\"inner_key\": 1}}} # E\n\n\nclass Inner3(TypedDict):\n x: int\n\n\nclass Inner4(TypedDict):\n x: int\n\n\nclass Outer2(TypedDict):\n y: str\n z: Literal[\"\"] | Inner3\n\n\nclass Outer3(TypedDict):\n y: str\n z: Literal[\"\"] | Inner4\n\n\ndef func1(td: Outer3):\n ...\n\n\no3: Outer2 = {\"y\": \"\", \"z\": {\"x\": 0}}\no4: Outer3 = o3\n","source":"typing_tests","origin":"conformance/tests/typeddicts_type_consistency.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"typed-dict","pep":"589","introduced_in":"3.8","form":"modern","file":"typed-dict/modern_18.py","code":"\"\"\"\nTests for basic usage of TypedDict.\n\"\"\"\n\nfrom typing import TypeVar, TypedDict\n\n\nclass Movie(TypedDict):\n name: str\n year: int\n\n\nmovie: Movie = {\"name\": \"Blade Runner\", \"year\": 1982}\n\n\ndef record_movie(movie: Movie) -> None:\n ...\n\n\nrecord_movie({\"name\": \"Blade Runner\", \"year\": 1982})\n\n\nmovie[\"director\"] = \"Ridley Scott\" # E: invalid key 'director'\nmovie[\"year\"] = \"1982\" # E: invalid value type (\"int\" expected)\n\n# The code below should be rejected, since 'title' is not a valid key,\n# and the 'name' key is missing:\nmovie2: Movie = {\"title\": \"Blade Runner\", \"year\": 1982} # E\n\nm = Movie(name='Blade Runner', year=1982)\n\n\n# > TypedDict type objects cannot be used in isinstance() tests such as\n# > isinstance(d, Movie).\nif isinstance(movie, Movie): # E\n pass\n\n\n# TypedDict should not be allowed as a bound for a TypeVar.\nT = TypeVar(\"T\", bound=TypedDict) # E\n","source":"typing_tests","origin":"conformance/tests/typeddicts_usage.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"typed-kwargs","pep":"692","introduced_in":"3.12","form":"modern","file":"typed-kwargs/modern_01.py","code":"\"\"\"\nTests the use of an unpacked TypedDict for annotating **kwargs.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#unpack-for-keyword-arguments\n\n# This sample tests the handling of Unpack[TypedDict] when used with\n# a **kwargs parameter in a function signature.\n\nfrom typing import Protocol, TypeVar, TypedDict, NotRequired, Required, Unpack, assert_type\n\n\nclass TD1(TypedDict):\n v1: Required[int]\n v2: NotRequired[str]\n\n\nclass TD2(TD1):\n v3: Required[str]\n\n\ndef func1(**kwargs: Unpack[TD2]) -> None:\n v1 = kwargs[\"v1\"]\n assert_type(v1, int)\n\n # > Type checkers may allow reading an item using ``d['x']`` even if\n # > the key ``'x'`` is not required\n kwargs[\"v2\"] # E?: v2 may not be present\n\n if \"v2\" in kwargs:\n v2 = kwargs[\"v2\"]\n assert_type(v2, str)\n\n v3 = kwargs[\"v3\"]\n assert_type(v3, str)\n\n\ndef func2(v3: str, **kwargs: Unpack[TD1]) -> None:\n # > When Unpack is used, type checkers treat kwargs inside the function\n # > body as a TypedDict.\n assert_type(kwargs, TD1)\n\n\ndef func3() -> None:\n # Mypy reports multiple errors here.\n func1() # E: missing required keyword args\n func1(v1=1, v2=\"\", v3=\"5\") # OK\n\n td2 = TD2(v1=2, v3=\"4\")\n func1(**td2) # OK\n func1(v1=1, v2=\"\", v3=\"5\", v4=5) # E?: v4 is not in TD2, but could be in a subtype\n func1(1, \"\", \"5\") # E: args not passed by position\n\n # > Passing a dictionary of type dict[str, object] as a **kwargs argument\n # > to a function that has **kwargs annotated with Unpack must generate a\n # > type checker error.\n my_dict: dict[str, str] = {}\n func1(**my_dict) # E: untyped dict\n\n d1 = {\"v1\": 2, \"v3\": \"4\", \"v4\": 4}\n func1(**d1) # E?: OK or Type error (spec allows either)\n func2(**td2) # OK\n func1(v1=2, **td2) # E: v1 is already specified\n func2(1, **td2) # E: v1 is already specified\n func2(v1=1, **td2) # E: v1 is already specified\n\n\nclass TDProtocol1(Protocol):\n def __call__(self, *, v1: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol2(Protocol):\n def __call__(self, *, v1: int, v3: str, v2: str = \"\") -> None:\n ...\n\n\nclass TDProtocol3(Protocol):\n def __call__(self, *, v1: int, v2: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol4(Protocol):\n def __call__(self, *, v1: int) -> None:\n ...\n\n\nclass TDProtocol5(Protocol):\n def __call__(self, v1: int, v3: str) -> None:\n ...\n\n\nclass TDProtocol6(Protocol):\n def __call__(self, **kwargs: Unpack[TD2]) -> None:\n ...\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/callables.html#assignment\n\nv1: TDProtocol1 = func1 # OK\nv2: TDProtocol2 = func1 # OK\nv3: TDProtocol3 = func1 # E: v2 is wrong type\nv4: TDProtocol4 = func1 # E: v3 is missing\nv5: TDProtocol5 = func1 # E: params are positional\nv6: TDProtocol6 = func1 # OK\n\n\ndef func4(v1: int, /, **kwargs: Unpack[TD2]) -> None:\n ...\n\n\ndef func5(v1: int, **kwargs: Unpack[TD2]) -> None: # E: parameter v1 overlaps with the TypedDict.\n ...\n\n\nT = TypeVar(\"T\", bound=TD2)\n\n# > TypedDict is the only permitted heterogeneous type for typing **kwargs.\n# > Therefore, in the context of typing **kwargs, using Unpack with types other\n# > than TypedDict should not be allowed and type checkers should generate\n# > errors in such cases.\n\ndef func6(**kwargs: Unpack[T]) -> None: # E: unpacked value must be a TypedDict, not a TypeVar bound to TypedDict.\n ...\n\n# > The situation where the destination callable contains **kwargs: Unpack[TypedDict] and\n# > the source callable doesn’t contain **kwargs should be disallowed. This is because,\n# > we cannot be sure that additional keyword arguments are not being passed in when an instance of a subclass\n# > had been assigned to a variable with a base class type and then unpacked in the destination callable invocation\n\ndef func7(*, v1: int, v3: str, v2: str = \"\") -> None:\n ...\n\n\nv7: TDProtocol6 = func7 # E: source does not have kwargs\n","source":"typing_tests","origin":"conformance/tests/callables_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"typed-kwargs","pep":"692","introduced_in":"3.12","form":"modern","file":"typed-kwargs/modern_02.py","code":"\"\"\"\nTests the use of unpacked TypedDicts with read-only items when used to annotate\na **kwargs parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/typeddict.html#read-only-items\n\nfrom typing import Protocol, TypedDict, Unpack\nfrom typing_extensions import ReadOnly\n\n# > :pep:`692` introduced ``Unpack`` to annotate ``**kwargs`` with a\n# > ``TypedDict``. Marking one or more of the items of a ``TypedDict`` used\n# > in this way as read-only will have no effect on the type signature of\n# > the method. However, it *will* prevent the item from being modified in\n# > the body of the function.\n\n\nclass Args(TypedDict):\n key1: int\n key2: str\n\n\nclass ReadOnlyArgs(TypedDict):\n key1: ReadOnly[int]\n key2: ReadOnly[str]\n\n\nclass Function(Protocol):\n def __call__(self, **kwargs: Unpack[Args]) -> None: ...\n\n\ndef impl(**kwargs: Unpack[ReadOnlyArgs]) -> None:\n kwargs[\"key1\"] = 3 # E\n\n\nfn: Function = impl # OK\n","source":"typing_tests","origin":"conformance/tests/typeddicts_readonly_kwargs.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"typeddict-extra-items","pep":"728","introduced_in":"3.15","form":"modern","file":"typeddict-extra-items/modern_01.py","code":"# pyright: enableExperimentalFeatures=true\nfrom collections.abc import Mapping\nfrom typing_extensions import ReadOnly, TypedDict, Unpack\nfrom typing import assert_type, Required, NotRequired, Never\n\n\n# > For a TypedDict type that specifies\n# > ``extra_items``, during construction, the value type of each unknown item\n# is expected to be non-required and assignable to the ``extra_items`` argument.\n\nclass Movie(TypedDict, extra_items=bool):\n name: str\n\na: Movie = {\"name\": \"Blade Runner\", \"novel_adaptation\": True} # OK\nb: Movie = {\"name\": \"Blade Runner\", \"year\": 1982} # E: 'int' is not assignable to 'bool'\n\n# > The alternative inline syntax is also supported::\n\nMovieFunctional = TypedDict(\"MovieFunctional\", {\"name\": str}, extra_items=bool)\n\nc: MovieFunctional = {\"name\": \"Blade Runner\", \"novel_adaptation\": True} # OK\nd: MovieFunctional = {\"name\": \"Blade Runner\", \"year\": 1982} # E: 'int' is not assignable to 'bool'\n\n# > Accessing extra items is allowed. Type checkers must infer their value type from\n# > the ``extra_items`` argument\n\ndef movie_keys(movie: Movie) -> None:\n assert_type(movie[\"name\"], str)\n assert_type(movie[\"novel_adaptation\"], bool)\n\n# > ``extra_items`` is inherited through subclassing\n\nclass MovieBase(TypedDict, extra_items=ReadOnly[int | None]):\n name: str\n\nclass InheritedMovie(MovieBase):\n year: int\n\ne: InheritedMovie = {\"name\": \"Blade Runner\", \"year\": None} # E: 'None' is incompatible with 'int'\nf: InheritedMovie = {\n \"name\": \"Blade Runner\",\n \"year\": 1982,\n \"other_extra_key\": None,\n} # OK\n\n# > Similar to ``total``, only a literal ``True`` or ``False`` is supported as the\n# > value of the ``closed`` argument. Type checkers should reject any non-literal value.\n\nclass IllegalTD(TypedDict, closed=42 == 42): # E: Argument to \"closed\" must be a literal True or False\n name: str\n\n# > Passing ``closed=False`` explicitly requests the default TypedDict behavior,\n# > where arbitrary other keys may be present and subclasses may add arbitrary items.\n\nclass BaseTD(TypedDict, closed=False):\n name: str\n\nclass ChildTD(BaseTD): # OK\n age: int\n\n# > It is a type checker error to pass ``closed=False`` if a superclass has\n# > ``closed=True`` or sets ``extra_items``.\n\nclass ClosedBase(TypedDict, closed=True):\n name: str\n\nclass IllegalChild1(ClosedBase, closed=False): # E: Cannot set 'closed=False' when superclass is 'closed=True'\n pass\n\nclass ExtraItemsBase(TypedDict, extra_items=int):\n name: str\n\nclass IllegalChild2(ExtraItemsBase, closed=False): # E: Cannot set 'closed=False' when superclass has 'extra_items'\n pass\n\n# > If ``closed`` is not provided, the behavior is inherited from the superclass.\n# > If the superclass is TypedDict itself or the superclass does not have ``closed=True``\n# > or the ``extra_items`` parameter, the previous TypedDict behavior is preserved:\n# > arbitrary extra items are allowed. If the superclass has ``closed=True``, the\n# > child class is also closed.\n\nclass BaseMovie(TypedDict, closed=True):\n name: str\n\nclass MovieA(BaseMovie): # OK, still closed\n pass\n\nclass MovieB(BaseMovie, closed=True): # OK, but redundant\n pass\n\nclass MovieC(MovieA): # E[MovieC]\n age: int # E[MovieC]: \"MovieC\" is a closed TypedDict; extra key \"age\" not allowed\n\nclass MovieD(MovieB): # E[MovieD]\n age: int # E[MovieD]: \"MovieD\" is a closed TypedDict; extra key \"age\" not allowed\n\n# > It is possible to use ``closed=True`` when subclassing if the ``extra_items``\n# > argument is a read-only type.\n\nclass MovieES(TypedDict, extra_items=ReadOnly[str]):\n pass\n\nclass MovieClosed(MovieES, closed=True): # OK\n pass\n\nclass MovieNever(MovieES, extra_items=Never): # OK, but 'closed=True' is preferred\n pass\n\nclass IllegalCloseNonReadOnly(ExtraItemsBase, closed=True): # E: Cannot set 'closed=True' when superclass has non-read-only 'extra_items'\n pass\n\n# > It is an error to use ``Required[]`` or ``NotRequired[]`` with ``extra_items``.\n\nclass IllegalExtraItemsTD(TypedDict, extra_items=Required[int]): # E: 'extra_items' value cannot be 'Required[...]'\n name: str\n\nclass AnotherIllegalExtraItemsTD(TypedDict, extra_items=NotRequired[int]): # E: 'extra_items' value cannot be 'NotRequired[...]'\n name: str\n\n# > The extra items are non-required, regardless of the totality of the\n# > TypedDict. Operations that are available to ``NotRequired`` items should also be available to the\n# > extra items.\n\nclass MovieEI(TypedDict, extra_items=int):\n name: str\n\ndef del_items(movie: MovieEI) -> None:\n del movie[\"name\"] # E: The value type of 'name' is 'Required[str]'\n del movie[\"year\"] # OK: The value type of 'year' is 'NotRequired[int]'\n\n# > For type checking purposes, ``Unpack[SomeTypedDict]`` with extra items should be\n# > treated as its equivalent in regular parameters.\n\nclass MovieNoExtra(TypedDict):\n name: str\n\nclass MovieExtra(TypedDict, extra_items=int):\n name: str\n\ndef unpack_no_extra(**kwargs: Unpack[MovieNoExtra]) -> None: ...\ndef unpack_extra(**kwargs: Unpack[MovieExtra]) -> None: ...\n\nunpack_no_extra(name=\"No Country for Old Men\", year=2007) # E?: Unrecognized item\nunpack_extra(name=\"No Country for Old Men\", year=2007) # OK\n\n# > Notably, if the TypedDict type specifies ``extra_items`` to be read-only,\n# > subclasses of the TypedDict type may redeclare ``extra_items``.\n\nclass ReadOnlyBase(TypedDict, extra_items=ReadOnly[int]):\n pass\n\nclass ReadOnlyChild(ReadOnlyBase, extra_items=ReadOnly[bool]): # OK\n pass\n\nclass MutableChild(ReadOnlyBase, extra_items=int): # OK\n pass\n\n# > Because a non-closed TypedDict type implicitly allows non-required extra items\n# > of value type ``ReadOnly[object]``, its subclass can override the\n# > ``extra_items`` argument with more specific types.\n\nclass NonClosedBase(TypedDict):\n name: str\n\nclass SpecificExtraItems(NonClosedBase, extra_items=bytes): # OK\n year: int\n\n# > First, it is not allowed to change the value of ``extra_items`` in a subclass\n# > unless it is declared to be ``ReadOnly`` in the superclass.\n\nclass Parent(TypedDict, extra_items=int | None):\n pass\n\nclass Child(Parent, extra_items=int): # E: Cannot change 'extra_items' type unless it is 'ReadOnly' in the superclass\n pass\n\n# > Second, ``extra_items=T`` effectively defines the value type of any unnamed\n# > items accepted to the TypedDict and marks them as non-required. Thus, the above\n# > restriction applies to any additional items defined in a subclass.\n\nclass MovieBase2(TypedDict, extra_items=int | None):\n name: str\n\nclass MovieRequiredYear(MovieBase2): # E[MovieRequiredYear]: Required key 'year' is not known to 'MovieBase2'\n year: int | None # E[MovieRequiredYear]\n\nclass MovieNotRequiredYear(MovieBase2): # E[MovieNotRequiredYear]: 'int | None' is not consistent with 'int'\n year: NotRequired[int] # E[MovieNotRequiredYear]\n\nclass MovieWithYear(MovieBase2): # OK\n year: NotRequired[int | None]\n\nclass BookBase(TypedDict, extra_items=ReadOnly[int | None]):\n name: str\n\nclass BookWithPublisher(BookBase): # E[BookWithPublisher]: 'str' is not assignable to 'int | None'\n publisher: str # E[BookWithPublisher]\n\n# > Let ``S`` be the set of keys of the explicitly defined items on a TypedDict\n# > type. If it specifies ``extra_items=T``, the TypedDict type is considered to\n# > have an infinite set of items that all satisfy the following conditions.\n# > - If ``extra_items`` is read-only:\n# > - The key's value type is :term:`assignable` to ``T``.\n# > - The key is not in ``S``.\n# > - If ``extra_items`` is not read-only:\n# > - The key is non-required.\n# > - The key's value type is :term:`consistent` with ``T``.\n# > - The key is not in ``S``.\n\nclass MovieDetails(TypedDict, extra_items=int | None):\n name: str\n year: NotRequired[int]\n\ndetails2: MovieDetails = {\"name\": \"Kill Bill Vol. 1\", \"year\": 2003}\nmovie2: MovieBase2 = details2 # E: While 'int' is not consistent with 'int | None'\n\nclass MovieWithYear2(TypedDict, extra_items=int | None):\n name: str\n year: int | None\n\ndetails3: MovieWithYear2 = {\"name\": \"Kill Bill Vol. 1\", \"year\": 2003}\nmovie3: MovieBase2 = details3 # E: 'year' is not required in 'MovieBase2', but it is required in 'MovieWithYear2'\n\n# > When ``extra_items`` is specified to be read-only on a TypedDict type, it is\n# > possible for an item to have a :term:`narrower ` type than the\n# > ``extra_items`` argument.\n\nclass MovieSI(TypedDict, extra_items=ReadOnly[str | int]):\n name: str\n\nclass MovieDetails4(TypedDict, extra_items=int):\n name: str\n year: NotRequired[int]\n\nclass MovieDetails5(TypedDict, extra_items=int):\n name: str\n actors: list[str]\n\ndetails4: MovieDetails4 = {\"name\": \"Kill Bill Vol. 2\", \"year\": 2004}\ndetails5: MovieDetails5 = {\"name\": \"Kill Bill Vol. 2\", \"actors\": [\"Uma Thurman\"]}\nmovie4: MovieSI = details4 # OK. 'int' is assignable to 'str | int'.\nmovie5: MovieSI = details5 # E: 'list[str]' is not assignable to 'str | int'.\n\n# > ``extra_items`` as a pseudo-item follows the same rules that other items have,\n# > so when both TypedDicts types specify ``extra_items``, this check is naturally\n# > enforced.\n\nclass MovieExtraInt(TypedDict, extra_items=int):\n name: str\n\nclass MovieExtraStr(TypedDict, extra_items=str):\n name: str\n\nextra_int: MovieExtraInt = {\"name\": \"No Country for Old Men\", \"year\": 2007}\nextra_str: MovieExtraStr = {\"name\": \"No Country for Old Men\", \"description\": \"\"}\nextra_int = extra_str # E: 'str' is not assignable to extra items type 'int'\nextra_str = extra_int # E: 'int' is not assignable to extra items type 'str'\n\n# > A non-closed TypedDict type implicitly allows non-required extra keys of value\n# > type ``ReadOnly[object]``. Applying the assignability rules between this type\n# > and a closed TypedDict type is allowed.\n\nclass MovieNotClosed(TypedDict):\n name: str\n\nextra_int2: MovieExtraInt = {\"name\": \"No Country for Old Men\", \"year\": 2007}\nnot_closed: MovieNotClosed = {\"name\": \"No Country for Old Men\"}\nextra_int2 = not_closed # E: 'extra_items=ReadOnly[object]' implicitly on 'MovieNotClosed' is not assignable to with 'extra_items=int'\nnot_closed = extra_int2 # OK\n\n# > TypedDicts that allow extra items of type ``T`` also allow arbitrary keyword\n# > arguments of this type when constructed by calling the class object.\n\nclass NonClosedMovie(TypedDict):\n name: str\n\nNonClosedMovie(name=\"No Country for Old Men\") # OK\nNonClosedMovie(name=\"No Country for Old Men\", year=2007) # E: Unrecognized item\n\nclass ExtraMovie(TypedDict, extra_items=int):\n name: str\n\nExtraMovie(name=\"No Country for Old Men\") # OK\nExtraMovie(name=\"No Country for Old Men\", year=2007) # OK\nExtraMovie(name=\"No Country for Old Men\", language=\"English\") # E: Wrong type for extra item 'language'\n\n# This implies 'extra_items=Never',\n# so extra keyword arguments would produce an error\nclass ClosedMovie(TypedDict, closed=True):\n name: str\n\nClosedMovie(name=\"No Country for Old Men\") # OK\nClosedMovie(name=\"No Country for Old Men\", year=2007) # E: Extra items not allowed\n\n# > A TypedDict type is :term:`assignable` to a type of the form ``Mapping[str, VT]``\n# > when all value types of the items in the TypedDict\n# > are assignable to ``VT``.\n\nextra_str3: MovieExtraStr = {\"name\": \"Blade Runner\", \"summary\": \"\"}\nstr_mapping: Mapping[str, str] = extra_str3 # OK\n\nextra_int3: MovieExtraInt = {\"name\": \"Blade Runner\", \"year\": 1982}\nint_mapping: Mapping[str, int] = extra_int3 # E: 'int | str' is not assignable with 'int'\nint_str_mapping: Mapping[str, int | str] = extra_int3 # OK\n\n# > Type checkers should infer the precise signatures of ``values()`` and ``items()``\n# > on such TypedDict types.\n\ndef foo(movie: MovieExtraInt) -> None:\n assert_type(list(movie.items()), list[tuple[str, int | str]])\n assert_type(list(movie.values()), list[int | str])\n\n# > The TypedDict type is :term:`assignable` to ``dict[str, VT]`` if all\n# > items on the TypedDict type satisfy the following conditions:\n# > - The value type of the item is :term:`consistent` with ``VT``.\n# > - The item is not read-only.\n# > - The item is not required.\n\nclass IntDict(TypedDict, extra_items=int):\n pass\n\nclass IntDictWithNum(IntDict):\n num: NotRequired[int]\n\ndef clear_intdict(x: IntDict) -> None:\n v: dict[str, int] = x # OK\n v.clear() # OK\n\nnot_required_num_dict: IntDictWithNum = {\"num\": 1, \"bar\": 2}\nregular_dict: dict[str, int] = not_required_num_dict # OK\nclear_intdict(not_required_num_dict) # OK\n\n# > In this case, methods that are previously unavailable on a TypedDict are allowed,\n# > with signatures matching ``dict[str, VT]``\n# > (e.g.: ``__setitem__(self, key: str, value: VT) -> None``).\n\nnot_required_num_dict.clear() # OK\n\nassert_type(not_required_num_dict.popitem(), tuple[str, int])\n\ndef nrnd(not_required_num_dict: IntDictWithNum, key: str):\n not_required_num_dict[key] = 42 # OK\n del not_required_num_dict[key] # OK\n\n# > ``dict[str, VT]`` is not assignable to a TypedDict type,\n# > because such dict can be a subtype of dict.\n\nclass CustomDict(dict[str, int]):\n pass\n\ndef might_not_be(might_not_be_a_builtin_dict: dict[str, int]):\n int_dict: IntDict = might_not_be_a_builtin_dict # E\n print(int_dict)\n\nnot_a_builtin_dict = CustomDict({\"num\": 1})\nmight_not_be(not_a_builtin_dict)\n","source":"typing_tests","origin":"conformance/tests/typeddicts_extra_items.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_13.py","code":"\"\"\"\nTests for the use of TypeVarTuple with \"*args\" parameter.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#args-as-a-type-variable-tuple\n\n# > If *args is annotated as a type variable tuple, the types of the individual\n# > arguments become the types in the type variable tuple.\n\nfrom typing import TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef args_to_tuple(*args: *Ts) -> tuple[*Ts]:\n raise NotImplementedError\n\n\nclass Env:\n ...\n\n\ndef exec_le(path: str, *args: *tuple[*Ts, Env], env: Env | None = None) -> tuple[*Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(x: int, y: str):\n assert_type(args_to_tuple(x, y), tuple[int, str])\n\n assert_type(exec_le(\"\", Env()), tuple[()]) # OK\n assert_type(exec_le(y, x, y, Env()), tuple[int, str]) # OK\n exec_le(\"\", 0, \"\") # E\n exec_le(\"\", 0, \"\", env=Env()) # E\n\n\n# > Using an unpacked unbounded tuple is equivalent to the\n# > PEP 484#arbitrary-argument-lists-and-default-argument-values behavior of\n# > *args: int, which accepts zero or more values of type int.\n\n\ndef func1(*args: *tuple[int, ...]) -> None:\n ...\n\n\nfunc1() # OK\nfunc1(1, 2, 3, 4, 5) # OK\nfunc1(1, \"2\", 3) # E\n\n\ndef func2(*args: *tuple[int, *tuple[str, ...], str]) -> None:\n ...\n\n\nfunc2(1, \"\") # OK\nfunc2(1, \"\", \"\", \"\", \"\") # OK\nfunc2(1, 1, \"\") # E\nfunc2(1) # E\nfunc2(\"\") # E\n\n\ndef func3(*args: *tuple[int, str]) -> None:\n ...\n\n\nfunc3(1, \"hello\") # OK\nfunc3(1) # E\n\n\ndef func4(*args: tuple[*Ts]):\n ...\n\n\nfunc4((0,), (1,)) # OK\nfunc4((0,), (1, 2)) # E (length mismatch)\nfunc4((0,), (\"1\",)) # OK\n\n\n# This is a syntax error, so leave it commented out.\n# def func5(**kwargs: *Ts): # E\n# ...\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_args.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_14.py","code":"\"\"\"\nTests basic usage of TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#typevartuple\n\nfrom typing import Generic, NewType, TypeVarTuple, assert_type\n\nTs = TypeVarTuple(\"Ts\")\nTs1 = TypeVarTuple(\"Ts1\")\n\n\nclass Array1(Generic[*Ts]):\n ...\n\n\ndef func1(*args: *Ts) -> tuple[*Ts]:\n raise NotImplementedError\n\n\nShape = TypeVarTuple(\"Shape\")\n\n\nclass Array(Generic[*Shape]):\n def __init__(self, shape: tuple[*Shape]):\n self._shape: tuple[*Shape] = shape\n\n def get_shape(self) -> tuple[*Shape]:\n return self._shape\n\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nTime = NewType(\"Time\", int)\nBatch = NewType(\"Batch\", int)\n\nv1: Array[Height, Width] = Array((Height(1), Width(2))) # OK\nv2: Array[Batch, Height, Width] = Array((Batch(1), Height(1), Width(1))) # OK\nv3: Array[Time, Batch, Height, Width] = Array(\n (Time(1), Batch(1), Height(1), Width(1))\n) # OK\n\nv4: Array[Height, Width] = Array(Height(1)) # E\nv5: Array[Batch, Height, Width] = Array((Batch(1), Width(1))) # E\nv6: Array[Time, Batch, Height, Width] = Array( # E[v6]\n (Time(1), Batch(1), Width(1), Height(1)) # E[v6]\n)\n\n\n# > Type Variable Tuples Must Always be Unpacked\n\n\nclass ClassA(Generic[Shape]): # E: not unpacked\n def __init__(self, shape: tuple[Shape]): # E: not unpacked\n self._shape: tuple[*Shape] = shape\n\n def get_shape(self) -> tuple[Shape]: # E: not unpacked\n raise NotImplementedError\n\n def method1(*args: Shape) -> None: # E: not unpacked\n ...\n\n\n# > TypeVarTuple does not support type constraints.\n\nTs2 = TypeVarTuple(\"Ts2\", int, float) # E\nTs3 = TypeVarTuple(\"Ts3\", bound=int) # E: bound is unavailable in Python 3.12\n\n\n# > If the same TypeVarTuple instance is used in multiple places in a signature\n# > or class, a valid type inference might be to bind the TypeVarTuple to a\n# > tuple of a union of types.\n\n\ndef func2(arg1: tuple[*Ts], arg2: tuple[*Ts]) -> tuple[*Ts]:\n raise NotImplementedError\n\n\n# > We do not allow this; type unions may not appear within the tuple.\n# > If a type variable tuple appears in multiple places in a signature,\n# > the types must match exactly (the list of type parameters must be the\n# > same length, and the type parameters themselves must be identical)\n\ndef check_func2(x: int):\n assert_type(func2((x,), (1,)), tuple[int]) # OK\nfunc2((0,), (0.0,)) # OK\nfunc2((0.0,), (0,)) # OK\nfunc2((0,), (1,)) # OK\n\nfunc2((0,), (\"0\",)) # OK\nfunc2((0, 0), (0,)) # E\n\n\ndef multiply(x: Array[*Shape], y: Array[*Shape]) -> Array[*Shape]:\n raise NotImplementedError\n\n\ndef func3(x: Array[Height], y: Array[Width], z: Array[Height, Width]):\n multiply(x, x) # OK\n multiply(x, y) # E\n multiply(x, z) # E\n\n\n# > Only a single type variable tuple may appear in a type parameter list.\n\n\nclass Array3(Generic[*Ts, *Ts1]): # E\n ...\n\n\nclass Array4[*Ts1, *Ts2]: # E\n ...\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_basic.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_15.py","code":"\"\"\"\nTests the use of TypeVarTuple within a Callable.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-variable-tuples-with-callable\n\n# > Type variable tuples can also be used in the arguments section of a Callable.\n\n\nfrom typing import Callable, TypeVar, TypeVarTuple, assert_type\n\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Process:\n def __init__(self, target: Callable[[*Ts], None], args: tuple[*Ts]) -> None:\n ...\n\n\ndef func1(arg1: int, arg2: str) -> None:\n ...\n\n\nProcess(target=func1, args=(0, \"\")) # OK\nProcess(target=func1, args=(\"\", 0)) # E\n\n\ndef func2(f: Callable[[int, *Ts, T], tuple[T, *Ts]]) -> tuple[*Ts, T]:\n raise NotImplementedError\n\n\ndef callback1(a: int, b: str, c: int, d: complex) -> tuple[complex, str, int]:\n raise NotImplementedError\n\n\ndef callback2(a: int, d: str) -> tuple[str]:\n raise NotImplementedError\n\n\nassert_type(func2(callback1), tuple[str, int, complex])\nassert_type(func2(callback2), tuple[str])\n\n\ndef func3(*args: *tuple[int, *Ts, T]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef has_int_and_str(a: int, b: str, c: float, d: complex):\n assert_type(func3(a, b, c, d), tuple[complex, str, float])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_callable.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_16.py","code":"\"\"\"\nTests type concatenation using TypeVarTuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#type-concatenation\n\n# > Type variable tuples don’t have to be alone; normal types can be prefixed and/or suffixed.\n\nfrom typing import Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nShape = TypeVarTuple(\"Shape\")\nTs = TypeVarTuple(\"Ts\")\nT = TypeVar(\"T\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef add_batch_axis(x: Array[*Shape]) -> Array[Batch, *Shape]:\n raise NotImplementedError\n\n\ndef del_batch_axis(x: Array[Batch, *Shape]) -> Array[*Shape]:\n raise NotImplementedError\n\n\ndef add_batch_channels(x: Array[*Shape]) -> Array[Batch, *Shape, Channels]:\n raise NotImplementedError\n\n\ndef func1(a: Array[Height, Width]):\n b = add_batch_axis(a) # OK\n assert_type(b, Array[Batch, Height, Width])\n c = del_batch_axis(b) # OK\n assert_type(c, Array[Height, Width])\n d = add_batch_channels(a) # OK\n assert_type(d, Array[Batch, Height, Width, Channels])\n\n\ndef prefix_tuple(x: T, y: tuple[*Ts]) -> tuple[T, *Ts]:\n raise NotImplementedError\n\n\ndef call_prefix_tuple(x: int, y: bool, z: str):\n result = prefix_tuple(x=x, y=(y, z))\n assert_type(result, tuple[int, bool, str])\n\n\ndef move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:\n return (*tup[1:], tup[0])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_concat.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_17.py","code":"\"\"\"\nTests the use of TypeVarTuple in function overloads.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#overloads-for-accessing-individual-types\n\nfrom typing import Any, Generic, TypeVar, TypeVarTuple, assert_type, overload\n\n\nShape = TypeVarTuple(\"Shape\")\nAxis1 = TypeVar(\"Axis1\")\nAxis2 = TypeVar(\"Axis2\")\nAxis3 = TypeVar(\"Axis3\")\n\n\nclass Array(Generic[*Shape]):\n @overload\n def transpose(self: \"Array[Axis1, Axis2]\") -> \"Array[Axis2, Axis1]\":\n ...\n\n @overload\n def transpose(self: \"Array[Axis1, Axis2, Axis3]\") -> \"Array[Axis3, Axis2, Axis1]\":\n ...\n\n def transpose(self) -> Any:\n raise NotImplementedError\n\n\ndef func1(a: Array[Axis1, Axis2], b: Array[Axis1, Axis2, Axis3]):\n assert_type(a.transpose(), Array[Axis2, Axis1])\n assert_type(b.transpose(), Array[Axis3, Axis2, Axis1])\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_overloads.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_18.py","code":"\"\"\"\nTests the handling of a TypeVarTuple specialization.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#behaviour-when-type-parameters-are-not-specified\n\nfrom typing import Any, Generic, NewType, TypeVar, TypeVarTuple, assert_type\n\n\nTs = TypeVarTuple(\"Ts\")\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nTime = NewType(\"Time\", int)\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef takes_any_array1(arr: Array):\n ...\n\n\ndef takes_any_array2(arr: Array[*tuple[Any, ...]]):\n ...\n\n\ndef func1(x: Array[Height, Width]):\n takes_any_array1(x) # OK\n takes_any_array2(x) # OK\n\n\ndef func2(y: Array[Time, Height, Width]):\n takes_any_array1(y) # OK\n takes_any_array2(y) # OK\n\n\n# > Generic aliases can be created using a type variable tuple in a similar\n# > way to regular type variables.\n\nIntTuple = tuple[int, *Ts]\nNamedArray = tuple[str, Array[*Ts]]\n\n\ndef func3(a: IntTuple[float, bool], b: NamedArray[Height]):\n assert_type(a, tuple[int, float, bool])\n assert_type(b, tuple[str, Array[Height]])\n\n\ndef func4(a: IntTuple[()], b: NamedArray[()]):\n assert_type(a, tuple[int])\n assert_type(b, tuple[str, Array[()]])\n\n\nShape = TypeVarTuple(\"Shape\")\nDType = TypeVar(\"DType\")\n\n\nclass Array2(Generic[DType, *Shape]):\n ...\n\n\nFloatArray = Array2[float, *Shape]\nArray1D = Array2[DType, Any]\n\n\ndef func5_0(a: Array1D, b: Array1D[int]):\n assert_type(a, Array2[Any, Any])\n assert_type(b, Array2[int, Any])\n\n\ndef takes_float_array_of_any_shape(x: FloatArray):\n ...\n\n\ndef func5_1(x: FloatArray[Height, Width]):\n takes_float_array_of_any_shape(x) # OK\n\n\ndef takes_float_array_with_specific_shape(y: FloatArray[Height, Width]):\n ...\n\n\ndef func5_2(x: FloatArray):\n takes_float_array_with_specific_shape(x) # OK\n\n\nT = TypeVar(\"T\")\nVariadicTuple = tuple[T, *Ts]\n\n\ndef func6(a: VariadicTuple[str, int], b: VariadicTuple[float], c: VariadicTuple):\n assert_type(a, tuple[str, int])\n assert_type(b, tuple[float])\n assert_type(c, tuple[Any, *tuple[Any, ...]])\n\n\nTs1 = TypeVarTuple(\"Ts1\")\nTs2 = TypeVarTuple(\"Ts2\")\n\nIntTupleVar = tuple[int, *Ts1] # OK\nIntFloatTupleVar = IntTupleVar[float, *Ts2] # OK\nIntFloatsTupleVar = IntTupleVar[*tuple[float, ...]] # OK\n\n\nIntTupleGeneric = tuple[int, T]\n\nIntTupleGeneric[str] # OK\nIntTupleGeneric[*Ts] # E\nIntTupleGeneric[*tuple[float, ...]] # E\n\n\nT1 = TypeVar(\"T1\")\nT2 = TypeVar(\"T2\")\nT3 = TypeVar(\"T3\")\n\nTA1 = tuple[*Ts, T1, T2] # OK\nTA2 = tuple[T1, T2, *Ts] # OK\nTA3 = tuple[T1, *Ts, T2, T3] # OK\nTA4 = tuple[T1, T2, *tuple[int, ...]] # OK\nTA5 = tuple[T1, *Ts, T2, *Ts] # E\nTA6 = tuple[T1, *Ts, T2, *tuple[int, ...]] # E\n\n\nTA7 = tuple[*Ts, T1, T2]\n\nv1: TA7[int] # E: requires at least two type arguments\n\n\ndef func7(a: TA7[*Ts, T1, T2]) -> tuple[tuple[*Ts], T1, T2]:\n raise NotImplementedError\n\n\ndef func8(a: TA7[str, bool], b: TA7[str, bool, float], c: TA7[str, bool, float, int]):\n assert_type(func7(a), tuple[tuple[()], str, bool])\n assert_type(func7(b), tuple[tuple[str], bool, float])\n assert_type(func7(c), tuple[tuple[str, bool], float, int])\n\n\nTA8 = tuple[T1, *Ts, T2, T3]\n\n\ndef func9(a: TA8[T1, *Ts, T2, T3]) -> tuple[tuple[*Ts], T1, T2, T3]:\n raise NotImplementedError\n\n\ndef func10(a: TA8[str, bool, float], b: TA8[str, bool, float, int]):\n assert_type(func9(a), tuple[tuple[()], str, bool, float])\n assert_type(func9(b), tuple[tuple[bool], str, float, int])\n\n\nTA9 = tuple[*Ts, T1]\nTA10 = TA9[*tuple[int, ...]] # OK\n\n\ndef func11(a: TA10, b: TA9[*tuple[int, ...], str], c: TA9[*tuple[int, ...], str]):\n assert_type(a, tuple[*tuple[int, ...], int])\n assert_type(b, tuple[*tuple[int, ...], str])\n assert_type(c, tuple[*tuple[int, ...], str])\n\n\nTA11 = tuple[T, *Ts1]\nTA12 = TA11[*Ts2] # E\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_specialization.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_19.py","code":"\"\"\"\nTests unpack operations for TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#unpacking-tuple-types\n\nfrom typing import Any, Generic, NewType, TypeVarTuple\n\nHeight = NewType(\"Height\", int)\nWidth = NewType(\"Width\", int)\nBatch = NewType(\"Batch\", int)\nChannels = NewType(\"Channels\", int)\n\nTs = TypeVarTuple(\"Ts\")\n\n\nclass Array(Generic[*Ts]):\n ...\n\n\ndef process_batch_channels(x: Array[Batch, *tuple[Any, ...], Channels]) -> None:\n ...\n\n\ndef func3(\n x: Array[Batch, Height, Width, Channels], y: Array[Batch, Channels], z: Array[Batch]\n):\n process_batch_channels(x) # OK\n process_batch_channels(y) # OK\n process_batch_channels(z) # E\n\n\nShape = TypeVarTuple(\"Shape\")\n\n\ndef expect_variadic_array(x: Array[Batch, *Shape]) -> None:\n ...\n\n\ndef expect_precise_array(x: Array[Batch, Height, Width, Channels]) -> None:\n ...\n\n\ndef func4(y: Array[*tuple[Any, ...]]):\n expect_variadic_array(y) # OK\n expect_precise_array(y) # OK\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_unpack.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_20.py","code":"\"\"\"\nTests variance of TypeVarTuple.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/generics.html#variance-inference\n\n\nfrom typing import Generic\nfrom typing_extensions import TypeVarTuple\n\nclass InvariantTypeVarTuple[*InOutTs]:\n a: tuple[*InOutTs]\n\nin_out_obj: InvariantTypeVarTuple[object] = InvariantTypeVarTuple[int]() # E\nin_out_int: InvariantTypeVarTuple[int] = InvariantTypeVarTuple[object]() # E\nin_out_int = InvariantTypeVarTuple[int]()\nin_out_variadic_int: InvariantTypeVarTuple[*tuple[int, ...]] = InvariantTypeVarTuple[*tuple[object, ...]]() # E\nin_out_variadic_object: InvariantTypeVarTuple[*tuple[object, ...]] = InvariantTypeVarTuple[*tuple[int, ...]]() # E\nin_out_empty: InvariantTypeVarTuple[()] = InvariantTypeVarTuple[()]() # OK\nin_out_fixed_from_variadic: InvariantTypeVarTuple[int] = InvariantTypeVarTuple[*tuple[int, ...]]() # E\nin_out_variadic_from_fixed: InvariantTypeVarTuple[*tuple[int, ...]] = InvariantTypeVarTuple[int]() # E\n\n\nclass ContravariantTypeVarTuple[*InTs]:\n def f(self, t: tuple[*InTs]):\n raise NotImplementedError\n\nin_obj: ContravariantTypeVarTuple[object, object] = ContravariantTypeVarTuple[object, int]() # E\nin_int: ContravariantTypeVarTuple[int] = ContravariantTypeVarTuple[object]() # OK\nin_variadic_int: ContravariantTypeVarTuple[*tuple[int, ...]] = ContravariantTypeVarTuple[*tuple[object, ...]]() # OK\nin_variadic_object: ContravariantTypeVarTuple[*tuple[object, ...]] = ContravariantTypeVarTuple[*tuple[int, ...]]() # E\nin_empty: ContravariantTypeVarTuple[()] = ContravariantTypeVarTuple[()]() # OK\nin_fixed_from_variadic: ContravariantTypeVarTuple[int] = ContravariantTypeVarTuple[*tuple[int, ...]]() # OK\nin_variadic_from_fixed: ContravariantTypeVarTuple[*tuple[int, ...]] = ContravariantTypeVarTuple[int]() # E\n\n\nclass CovariantTypeVarTuple[*OutTs]:\n def f(self) -> tuple[*OutTs]:\n raise NotImplementedError\n\n\nout_int: CovariantTypeVarTuple[int] = CovariantTypeVarTuple[object]() # E\nout_obj: CovariantTypeVarTuple[object] = CovariantTypeVarTuple[int]() # OK\nout_multiple1: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[bool, bool]() # OK\nout_multiple2: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[bool, object]() # E\nout_multiple3: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[object, bool]() # E\nout_multiple4: CovariantTypeVarTuple[int, int] = CovariantTypeVarTuple[object, object]() # E\nout_variadic_int: CovariantTypeVarTuple[*tuple[int, ...]] = CovariantTypeVarTuple[*tuple[object, ...]]() # E\nout_variadic_object: CovariantTypeVarTuple[*tuple[object, ...]] = CovariantTypeVarTuple[*tuple[int, ...]]() # OK\nout_empty: CovariantTypeVarTuple[()] = CovariantTypeVarTuple[()]() # OK\nout_fixed_from_variadic: CovariantTypeVarTuple[int] = CovariantTypeVarTuple[*tuple[int, ...]]() # E\nout_variadic_from_fixed: CovariantTypeVarTuple[*tuple[int, ...]] = CovariantTypeVarTuple[int]() # OK\n\nTs = TypeVarTuple(\"Ts\") # OK\nInferTs = TypeVarTuple(\"InferTs\", infer_variance=True) # OK\nInvTs1 = TypeVarTuple(\"InvTs1\", covariant=True, contravariant=True) # E\nInvTs2 = TypeVarTuple(\"InvTs2\", covariant=True, infer_variance=True) # E\nInvTs3 = TypeVarTuple(\"InvTs3\", contravariant=True, infer_variance=True) # E\n\nclass InvariantTypeVarTupleOld(Generic[*Ts]):\n def in_f(self, *args: *Ts) -> None: # OK\n raise NotImplementedError\n\n def out_f(self) -> tuple[*Ts]: # OK\n raise NotImplementedError\n\n\nobj_old: InvariantTypeVarTupleOld[object] = InvariantTypeVarTupleOld[int]() # E\nint_old: InvariantTypeVarTupleOld[int] = InvariantTypeVarTupleOld[object]() # E\nint_old = InvariantTypeVarTupleOld[int]()\n\n\nInTs = TypeVarTuple(\"InTs\", contravariant=True)\n\nclass ContravariantTypeVarTupleOld(Generic[*InTs]):\n def in_f(self, *args: *InTs) -> None: # OK\n raise NotImplementedError\n\n def out_f(self) -> tuple[*InTs]: # E\n raise NotImplementedError\n\n\nin_obj_old: ContravariantTypeVarTupleOld[object] = ContravariantTypeVarTupleOld[int]() # E\nin_int_old: ContravariantTypeVarTupleOld[int] = ContravariantTypeVarTupleOld[object]() # OK\n\n\nOutTs = TypeVarTuple(\"OutTs\", covariant=True)\n\nclass CovariantTypeVarTupleOld(Generic[*OutTs]):\n def in_f(self, *args: *OutTs) -> None: # E\n raise NotImplementedError\n\n def out_f(self) -> tuple[*OutTs]: # OK\n raise NotImplementedError\n\n\nout_int_old: CovariantTypeVarTupleOld[int] = CovariantTypeVarTupleOld[object]() # E\nout_obj_old: CovariantTypeVarTupleOld[object] = CovariantTypeVarTupleOld[int]() # OK\n\n\n# `infer_variance=True` on a traditional `TypeVarTuple`\nclass InferredContravariantTypeVarTupleOld(Generic[*InferTs]):\n def in_f(self, *args: *InferTs) -> None: # OK\n raise NotImplementedError\n\n\ninfer_in_obj_old: InferredContravariantTypeVarTupleOld[object] = InferredContravariantTypeVarTupleOld[int]() # E\ninfer_in_int_old: InferredContravariantTypeVarTupleOld[int] = InferredContravariantTypeVarTupleOld[object]() # OK\n\n\nclass InferredCovariantTypeVarTupleOld(Generic[*InferTs]):\n def out_f(self) -> tuple[*InferTs]: # OK\n raise NotImplementedError\n\n\ninfer_out_int_old: InferredCovariantTypeVarTupleOld[int] = InferredCovariantTypeVarTupleOld[object]() # E\ninfer_out_obj_old: InferredCovariantTypeVarTupleOld[object] = InferredCovariantTypeVarTupleOld[int]() # OK\n","source":"typing_tests","origin":"conformance/tests/generics_typevartuple_variance.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"variadic-generics","pep":"646","introduced_in":"3.11","form":"modern","file":"variadic-generics/modern_21.py","code":"\"\"\"\nTests the handling of unpacked tuples embedded within other tuples.\n\"\"\"\n\n# Specification: https://typing.readthedocs.io/en/latest/spec/tuples.html#unpacked-tuple-form\n\n# > An unpacked form of ``tuple`` (using an unpack operator ``*``)\n# > can be used within a tuple type argument list\n\n# > Unpacking a concrete tuple type is analogous to unpacking a tuple of values at runtime.\n\n\nfrom typing import TypeVarTuple, Unpack, assert_type\n\n\ndef func1(x: tuple[int, *tuple[bool, bool], str]):\n assert_type(x, tuple[int, bool, bool, str])\n assert_type(x, tuple[*tuple[int, bool], bool, str])\n assert_type(x, tuple[int, bool, *tuple[bool, str]])\n\n\n# > Unpacking an unbounded tuple preserves the unbounded tuple as it is.\n\n\ndef func2(x: tuple[int, *tuple[bool, ...], str]):\n assert_type(x, tuple[int, *tuple[bool, ...], str])\n\n\n# > For example, tuple[int, *tuple[str]] is equivalent to tuple[int, str].\n\nu1: tuple[*tuple[int], *tuple[int]] = (int(1), int(1)) # OK\nassert_type(u1, tuple[int, int])\nu2: tuple[*tuple[int, ...], *tuple[int]] # OK\n\n\n# > Only one unbounded tuple can be used within another tuple:\n\nt1: tuple[*tuple[str], *tuple[str]] # OK\nt2: tuple[*tuple[str, *tuple[str, ...]]] # OK\nt3: tuple[*tuple[str, ...], *tuple[int, ...]] # E\nt4: tuple[*tuple[str, *tuple[str, ...]], *tuple[int, ...]] # E\n\n\n# > An unpacked TypeVarTuple counts as an unbounded tuple in the context of this rule\n\nTs = TypeVarTuple(\"Ts\")\n\n\ndef func3(t: tuple[*Ts]):\n t5: tuple[*tuple[str], *Ts] # OK\n t6: tuple[*tuple[str, ...], *Ts] # E\n\n\n# > The ``*`` syntax requires Python 3.11 or newer. For older versions of Python,\n# > the ``typing.Unpack`` special form can be used:\n\nt11: tuple[Unpack[tuple[str]], Unpack[tuple[str]]] # OK\nt12: tuple[Unpack[tuple[str, Unpack[tuple[str, ...]]]]] # OK\nt13: tuple[Unpack[tuple[str, ...]], Unpack[tuple[int, ...]]] # E\nt14: tuple[ # E[t14]\n Unpack[tuple[str, Unpack[tuple[str, ...]]]], Unpack[tuple[int, ...]] # E[t14]\n]\n","source":"typing_tests","origin":"conformance/tests/tuples_unpacked.py","origin_revision":"d06c5dd","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_01.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenSyntaxTest(unittest.TestCase):\n\n def test_async_gen_syntax_01(self):\n code = '''async def foo():\n await abc\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_02(self):\n code = '''async def foo():\n yield from 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'yield from.*inside async'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_03(self):\n code = '''async def foo():\n await abc\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_04(self):\n code = '''async def foo():\n yield\n return 123\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n\n def test_async_gen_syntax_05(self):\n code = '''async def foo():\n if 0:\n yield\n return 12\n '''\n\n with self.assertRaisesRegex(SyntaxError, 'return.*value.*async gen'):\n exec(code, {}, {})\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenSyntaxTest","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_02.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenTest(unittest.TestCase):\n\n def compare_generators(self, sync_gen, async_gen):\n def sync_iterate(g):\n res = []\n while True:\n try:\n res.append(g.__next__())\n except StopIteration:\n res.append('STOP')\n break\n except Exception as ex:\n res.append(str(type(ex)))\n return res\n\n def async_iterate(g):\n res = []\n while True:\n an = g.__anext__()\n try:\n while True:\n try:\n an.__next__()\n except StopIteration as ex:\n if ex.args:\n res.append(ex.args[0])\n break\n else:\n res.append('EMPTY StopIteration')\n break\n except StopAsyncIteration:\n raise\n except Exception as ex:\n res.append(str(type(ex)))\n break\n except StopAsyncIteration:\n res.append('STOP')\n break\n return res\n\n sync_gen_result = sync_iterate(sync_gen)\n async_gen_result = async_iterate(async_gen)\n self.assertEqual(sync_gen_result, async_gen_result)\n return async_gen_result\n\n def test_async_gen_iteration_01(self):\n async def gen():\n await awaitable()\n a = yield 123\n self.assertIs(a, None)\n await awaitable()\n yield 456\n await awaitable()\n yield 789\n\n self.assertEqual(to_list(gen()), [123, 456, 789])\n\n def test_async_gen_iteration_02(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable()\n\n g = gen()\n ai = g.__aiter__()\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopAsyncIteration as ex:\n self.assertFalse(ex.args)\n else:\n self.fail('StopAsyncIteration was not raised')\n\n def test_async_gen_exception_03(self):\n async def gen():\n await awaitable()\n yield 123\n await awaitable(throw=True)\n yield 456\n\n with self.assertRaises(AwaitException):\n to_list(gen())\n\n def test_async_gen_exception_04(self):\n async def gen():\n await awaitable()\n yield 123\n 1 / 0\n\n g = gen()\n ai = g.__aiter__()\n an = ai.__anext__()\n self.assertEqual(an.__next__(), ('result',))\n\n try:\n an.__next__()\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 123)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(ZeroDivisionError):\n ai.__anext__().__next__()\n\n def test_async_gen_exception_05(self):\n async def gen():\n yield 123\n raise StopAsyncIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopAsyncIteration'):\n to_list(gen())\n\n def test_async_gen_exception_06(self):\n async def gen():\n yield 123\n raise StopIteration\n\n with self.assertRaisesRegex(RuntimeError,\n 'async generator.*StopIteration'):\n to_list(gen())\n\n def test_async_gen_exception_07(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_08(self):\n def sync_gen():\n try:\n yield 1\n finally:\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n yield 1\n await awaitable()\n finally:\n await awaitable()\n yield 2\n 1 / 0\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_09(self):\n def sync_gen():\n try:\n yield 1\n 1 / 0\n finally:\n yield 2\n yield 3\n\n yield 100\n\n async def async_gen():\n try:\n await awaitable()\n yield 1\n 1 / 0\n finally:\n yield 2\n await awaitable()\n yield 3\n\n yield 100\n\n self.compare_generators(sync_gen(), async_gen())\n\n def test_async_gen_exception_10(self):\n async def gen():\n yield 123\n with self.assertRaisesRegex(TypeError,\n \"non-None value .* async generator\"):\n gen().__anext__().send(100)\n\n def test_async_gen_exception_11(self):\n def sync_gen():\n yield 10\n yield 20\n\n def sync_gen_wrapper():\n yield 1\n sg = sync_gen()\n sg.send(None)\n try:\n sg.throw(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n async def async_gen():\n yield 10\n yield 20\n\n async def async_gen_wrapper():\n yield 1\n asg = async_gen()\n await asg.asend(None)\n try:\n await asg.athrow(GeneratorExit())\n except GeneratorExit:\n yield 2\n yield 3\n\n self.compare_generators(sync_gen_wrapper(), async_gen_wrapper())\n\n def test_async_gen_exception_12(self):\n async def gen():\n with self.assertWarnsRegex(RuntimeWarning,\n f\"coroutine method 'asend' of '{gen.__qualname__}' \"\n f\"was never awaited\"):\n await anext(me)\n yield 123\n\n me = gen()\n ai = me.__aiter__()\n an = ai.__anext__()\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n an.__next__()\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"):\n an.send(None)\n\n def test_async_gen_asend_throw_concurrent_with_send(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n return\n yield\n\n\n agen = agenfn()\n gen = agen.asend(None)\n gen.send(None)\n gen2 = agen.asend(None)\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_athrow_throw_concurrent_with_send(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n return\n yield\n\n\n agen = agenfn()\n gen = agen.asend(None)\n gen.send(None)\n gen2 = agen.athrow(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r'athrow\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_asend_throw_concurrent_with_throw(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n try:\n yield\n except MyExc:\n pass\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n\n\n agen = agenfn()\n with self.assertRaises(StopIteration):\n agen.asend(None).send(None)\n\n gen = agen.athrow(MyExc)\n gen.throw(MyExc)\n gen2 = agen.asend(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r'anext\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_athrow_throw_concurrent_with_throw(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n try:\n yield\n except MyExc:\n pass\n while True:\n try:\n await _async_yield(None)\n except MyExc:\n pass\n\n agen = agenfn()\n with self.assertRaises(StopIteration):\n agen.asend(None).send(None)\n\n gen = agen.athrow(MyExc)\n gen.throw(MyExc)\n gen2 = agen.athrow(None)\n\n with self.assertRaisesRegex(RuntimeError,\n r'athrow\\(\\): asynchronous generator is already running'):\n gen2.throw(MyExc)\n\n with self.assertRaisesRegex(RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"):\n gen2.send(None)\n\n def test_async_gen_3_arg_deprecation_warning(self):\n async def gen():\n yield 123\n\n with self.assertWarns(DeprecationWarning):\n x = gen().athrow(GeneratorExit, GeneratorExit(), None)\n with self.assertRaises(GeneratorExit):\n x.send(None)\n del x\n gc_collect()\n\n def test_async_gen_api_01(self):\n async def gen():\n yield 123\n\n g = gen()\n\n self.assertEqual(g.__name__, 'gen')\n g.__name__ = '123'\n self.assertEqual(g.__name__, '123')\n\n self.assertIn('.gen', g.__qualname__)\n g.__qualname__ = '123'\n self.assertEqual(g.__qualname__, '123')\n\n self.assertIsNone(g.ag_await)\n self.assertIsInstance(g.ag_frame, types.FrameType)\n self.assertFalse(g.ag_running)\n self.assertIsInstance(g.ag_code, types.CodeType)\n aclose = g.aclose()\n self.assertTrue(inspect.isawaitable(aclose))\n aclose.close()\n\n def test_async_gen_asend_close_runtime_error(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n async def agenfn():\n try:\n await _async_yield(None)\n except GeneratorExit:\n await _async_yield(None)\n return\n yield\n\n agen = agenfn()\n gen = agen.asend(None)\n gen.send(None)\n with self.assertRaisesRegex(RuntimeError, \"coroutine ignored GeneratorExit\"):\n gen.close()\n\n def test_async_gen_athrow_close_runtime_error(self):\n import types\n\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyExc(Exception):\n pass\n\n async def agenfn():\n try:\n yield\n except MyExc:\n try:\n await _async_yield(None)\n except GeneratorExit:\n await _async_yield(None)\n\n agen = agenfn()\n with self.assertRaises(StopIteration):\n agen.asend(None).send(None)\n gen = agen.athrow(MyExc)\n gen.send(None)\n with self.assertRaisesRegex(RuntimeError, \"coroutine ignored GeneratorExit\"):\n gen.close()\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenTest","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"async-generators","pep":"525","introduced_in":"3.6","form":"modern","file":"async-generators/modern_03.py","code":"import inspect\nimport types\nimport unittest\nimport contextlib\nfrom test.support.import_helper import import_module\nfrom test.support import gc_collect, requires_working_socket\n\n\nclass AsyncGenAsyncioTest(unittest.TestCase):\n\n def setUp(self):\n self.loop = asyncio.new_event_loop()\n asyncio.set_event_loop(None)\n\n def tearDown(self):\n self.loop.close()\n self.loop = None\n asyncio.events._set_event_loop_policy(None)\n\n def check_async_iterator_anext(self, ait_class):\n with self.subTest(anext=\"pure-Python\"):\n self._check_async_iterator_anext(ait_class, py_anext)\n with self.subTest(anext=\"builtin\"):\n self._check_async_iterator_anext(ait_class, anext)\n\n def _check_async_iterator_anext(self, ait_class, anext):\n g = ait_class()\n async def consume():\n results = []\n results.append(await anext(g))\n results.append(await anext(g))\n results.append(await anext(g, 'buckle my shoe'))\n return results\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2, 'buckle my shoe'])\n with self.assertRaises(StopAsyncIteration):\n self.loop.run_until_complete(consume())\n\n async def test_2():\n g1 = ait_class()\n self.assertEqual(await anext(g1), 1)\n self.assertEqual(await anext(g1), 2)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n with self.assertRaises(StopAsyncIteration):\n await anext(g1)\n\n g2 = ait_class()\n self.assertEqual(await anext(g2, \"default\"), 1)\n self.assertEqual(await anext(g2, \"default\"), 2)\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n self.assertEqual(await anext(g2, \"default\"), \"default\")\n\n return \"completed\"\n\n result = self.loop.run_until_complete(test_2())\n self.assertEqual(result, \"completed\")\n\n def test_send():\n p = ait_class()\n obj = anext(p, \"completed\")\n with self.assertRaises(StopIteration):\n with contextlib.closing(obj.__await__()) as g:\n g.send(None)\n\n test_send()\n\n async def test_throw():\n p = ait_class()\n obj = anext(p, \"completed\")\n self.assertRaises(SyntaxError, obj.throw, SyntaxError)\n return \"completed\"\n\n result = self.loop.run_until_complete(test_throw())\n self.assertEqual(result, \"completed\")\n\n def test_async_generator_anext(self):\n async def agen():\n yield 1\n yield 2\n self.check_async_iterator_anext(agen)\n\n def test_python_async_iterator_anext(self):\n class MyAsyncIter:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n async def __anext__(self):\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIter)\n\n def test_python_async_iterator_types_coroutine_anext(self):\n import types\n class MyAsyncIterWithTypesCoro:\n \"\"\"Asynchronously yield 1, then 2.\"\"\"\n def __init__(self):\n self.yielded = 0\n def __aiter__(self):\n return self\n @types.coroutine\n def __anext__(self):\n if False:\n yield \"this is a generator-based coroutine\"\n if self.yielded >= 2:\n raise StopAsyncIteration()\n else:\n self.yielded += 1\n return self.yielded\n self.check_async_iterator_anext(MyAsyncIterWithTypesCoro)\n\n def test_async_gen_aiter(self):\n async def gen():\n yield 1\n yield 2\n g = gen()\n async def consume():\n return [i async for i in aiter(g)]\n res = self.loop.run_until_complete(consume())\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_aiter_class(self):\n results = []\n class Gen:\n async def __aiter__(self):\n yield 1\n yield 2\n g = Gen()\n async def consume():\n ait = aiter(g)\n while True:\n try:\n results.append(await anext(ait))\n except StopAsyncIteration:\n break\n self.loop.run_until_complete(consume())\n self.assertEqual(results, [1, 2])\n\n def test_aiter_idempotent(self):\n async def gen():\n yield 1\n applied_once = aiter(gen())\n applied_twice = aiter(applied_once)\n self.assertIs(applied_once, applied_twice)\n\n def test_anext_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await anext()\n async def call_with_too_many_args():\n await anext(gen(), 1, 3)\n async def call_with_wrong_type_args():\n await anext(1, gen())\n async def call_with_kwarg():\n await anext(aiterator=gen())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_kwarg())\n\n def test_anext_bad_await(self):\n async def bad_awaitable():\n class BadAwaitable:\n def __await__(self):\n return 42\n class MyAsyncIter:\n def __aiter__(self):\n return self\n def __anext__(self):\n return BadAwaitable()\n regex = r\"__await__.*iterator\"\n awaitable = anext(MyAsyncIter(), \"default\")\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n awaitable = anext(MyAsyncIter())\n with self.assertRaisesRegex(TypeError, regex):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(bad_awaitable())\n self.assertEqual(result, \"completed\")\n\n async def check_anext_returning_iterator(self, aiter_class):\n awaitable = anext(aiter_class(), \"default\")\n with self.assertRaises(TypeError):\n await awaitable\n awaitable = anext(aiter_class())\n with self.assertRaises(TypeError):\n await awaitable\n return \"completed\"\n\n def test_anext_return_iterator(self):\n class WithIterAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return iter(\"abc\")\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithIterAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_return_generator(self):\n class WithGenAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n yield\n result = self.loop.run_until_complete(self.check_anext_returning_iterator(WithGenAnext))\n self.assertEqual(result, \"completed\")\n\n def test_anext_await_raises(self):\n class RaisingAwaitable:\n def __await__(self):\n raise ZeroDivisionError()\n yield\n class WithRaisingAwaitableAnext:\n def __aiter__(self):\n return self\n def __anext__(self):\n return RaisingAwaitable()\n async def do_test():\n awaitable = anext(WithRaisingAwaitableAnext())\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n awaitable = anext(WithRaisingAwaitableAnext(), \"default\")\n with self.assertRaises(ZeroDivisionError):\n await awaitable\n return \"completed\"\n result = self.loop.run_until_complete(do_test())\n self.assertEqual(result, \"completed\")\n\n def test_anext_iter(self):\n @types.coroutine\n def _async_yield(v):\n return (yield v)\n\n class MyError(Exception):\n pass\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n def test1(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError()), 2)\n try:\n g.send(None)\n except StopIteration as e:\n err = e\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(err.value, \"default\")\n\n def test2(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n self.assertEqual(g.throw(MyError()), 2)\n with self.assertRaises(MyError):\n g.throw(MyError())\n\n def test3(anext):\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 1)\n g.close()\n with self.assertRaisesRegex(RuntimeError, 'cannot reuse'):\n self.assertEqual(g.send(None), 1)\n\n def test4(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n await _async_yield(2)\n return\n yield\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n self.assertEqual(g.throw(MyError()), 20)\n with self.assertRaisesRegex(MyError, 'val'):\n g.throw(MyError('val'))\n\n def test5(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n try:\n await _async_yield(1)\n except MyError:\n return\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n self.assertEqual(g.send(None), 10)\n with self.assertRaisesRegex(StopIteration, 'default'):\n g.throw(MyError())\n\n def test6(anext):\n @types.coroutine\n def _async_yield(v):\n yield v * 10\n return (yield (v * 10 + 1))\n\n async def agenfn():\n await _async_yield(1)\n yield 'aaa'\n\n agen = agenfn()\n with contextlib.closing(anext(agen, \"default\").__await__()) as g:\n with self.assertRaises(MyError):\n g.throw(MyError())\n\n def run_test(test):\n with self.subTest('pure-Python anext()'):\n test(py_anext)\n with self.subTest('builtin anext()'):\n test(anext)\n\n run_test(test1)\n run_test(test2)\n run_test(test3)\n run_test(test4)\n run_test(test5)\n run_test(test6)\n\n def test_aiter_bad_args(self):\n async def gen():\n yield 1\n async def call_with_too_few_args():\n await aiter()\n async def call_with_too_many_args():\n await aiter(gen(), 1)\n async def call_with_wrong_type_arg():\n await aiter(1)\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_few_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_too_many_args())\n with self.assertRaises(TypeError):\n self.loop.run_until_complete(call_with_wrong_type_arg())\n\n async def to_list(self, gen):\n res = []\n async for i in gen:\n res.append(i)\n return res\n\n def test_async_gen_asyncio_01(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n await asyncio.sleep(0.01)\n return\n yield 3\n\n res = self.loop.run_until_complete(self.to_list(gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_02(self):\n async def gen():\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n 1 / 0\n yield 3\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(self.to_list(gen()))\n\n def test_async_gen_asyncio_03(self):\n loop = self.loop\n\n class Gen:\n async def __aiter__(self):\n yield 1\n await asyncio.sleep(0.01)\n yield 2\n\n res = loop.run_until_complete(self.to_list(Gen()))\n self.assertEqual(res, [1, 2])\n\n def test_async_gen_asyncio_anext_04(self):\n async def foo():\n yield 1\n await asyncio.sleep(0.01)\n try:\n yield 2\n yield 3\n except ZeroDivisionError:\n yield 1000\n await asyncio.sleep(0.01)\n yield 4\n\n async def run1():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n self.assertEqual(await it.__anext__(), 3)\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n async def run2():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), 1)\n self.assertEqual(await it.__anext__(), 2)\n try:\n it.__anext__().throw(ZeroDivisionError)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1000)\n else:\n self.fail('StopIteration was not raised')\n self.assertEqual(await it.__anext__(), 4)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run1())\n self.loop.run_until_complete(run2())\n\n def test_async_gen_asyncio_anext_05(self):\n async def foo():\n v = yield 1\n v = yield v\n yield v * 100\n\n async def run():\n it = foo().__aiter__()\n\n try:\n it.__anext__().send(None)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(10)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 10)\n else:\n self.fail('StopIteration was not raised')\n\n try:\n it.__anext__().send(12)\n except StopIteration as ex:\n self.assertEqual(ex.args[0], 1200)\n else:\n self.fail('StopIteration was not raised')\n\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_06(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.send(None)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_anext_tuple(self):\n async def foo():\n try:\n yield (1,)\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n it = foo().__aiter__()\n\n self.assertEqual(await it.__anext__(), (1,))\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n self.assertEqual(cm.exception.args[0], (2,))\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_anext_tuple_no_exceptions(self):\n # StopAsyncIteration exceptions should be cleared.\n # See: https://github.com/python/cpython/issues/128078.\n\n async def foo():\n if False:\n yield (1, 2)\n\n async def run():\n it = foo().__aiter__()\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n res = await anext(it, ('a', 'b'))\n self.assertTupleEqual(res, ('a', 'b'))\n\n self.loop.run_until_complete(run())\n\n def test_sync_anext_raises_exception(self):\n # See: https://github.com/python/cpython/issues/131670\n msg = 'custom'\n for exc_type in [\n StopAsyncIteration,\n StopIteration,\n ValueError,\n Exception,\n ]:\n exc = exc_type(msg)\n with self.subTest(exc=exc):\n class A:\n def __anext__(self):\n raise exc\n\n with self.assertRaisesRegex(exc_type, msg):\n anext(A())\n with self.assertRaisesRegex(exc_type, msg):\n anext(A(), 1)\n\n def test_async_gen_asyncio_anext_stopiteration(self):\n async def foo():\n try:\n yield StopIteration(1)\n except ZeroDivisionError:\n yield StopIteration(3)\n\n async def run():\n it = foo().__aiter__()\n\n v = await it.__anext__()\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 1)\n with self.assertRaises(StopIteration) as cm:\n it.__anext__().throw(ZeroDivisionError)\n v = cm.exception.args[0]\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 3)\n with self.assertRaises(StopAsyncIteration):\n await it.__anext__()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_06(self):\n async def foo():\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n yield 12\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n with self.assertRaisesRegex(\n RuntimeError,\n \"async generator ignored GeneratorExit\"):\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_aclose_07(self):\n DONE = 0\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n 1 / 0\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_08(self):\n DONE = 0\n\n fut = asyncio.Future(loop=self.loop)\n\n async def foo():\n nonlocal DONE\n try:\n yield 1\n await fut\n DONE += 1000\n yield 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE += 1\n DONE += 1000\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n self.assertEqual(await it.__anext__(), 1)\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n # Silence ResourceWarnings\n fut.cancel()\n self.loop.run_until_complete(asyncio.sleep(0.01))\n\n def test_async_gen_asyncio_gc_aclose_09(self):\n DONE = 0\n\n async def gen():\n nonlocal DONE\n try:\n while True:\n yield 1\n finally:\n await asyncio.sleep(0)\n DONE = 1\n\n async def run():\n g = gen()\n await g.__anext__()\n await g.__anext__()\n del g\n gc_collect() # For PyPy or other GCs.\n\n # Starts running the aclose task\n await asyncio.sleep(0)\n # For asyncio.sleep(0) in finally block\n await asyncio.sleep(0)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_aclose_10(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_aclose_11(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n yield\n g = foo()\n g.send(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n g.close()\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n yield\n DONE += 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaisesRegex(RuntimeError, 'ignored GeneratorExit'):\n await g.aclose()\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 10)\n\n def test_async_gen_asyncio_aclose_12(self):\n DONE = 0\n\n async def target():\n await asyncio.sleep(0.01)\n 1 / 0\n\n async def foo():\n nonlocal DONE\n task = asyncio.create_task(target())\n try:\n yield 1\n finally:\n try:\n await task\n except ZeroDivisionError:\n DONE = 1\n\n async def run():\n gen = foo()\n it = gen.__aiter__()\n await it.__anext__()\n await gen.aclose()\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_01(self):\n DONE = 0\n\n # Sanity check:\n def sgen():\n v = yield 1\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.send(100)\n self.assertEqual(v, 200)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.asend(100)\n self.assertEqual(v, 200)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_02(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n await asyncio.sleep(delay)\n 1 / 0\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(ZeroDivisionError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_asend_03(self):\n DONE = 0\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n v = yield 1\n await sleep_n_crash(0.01)\n DONE += 1000\n yield v * 2\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n await g.asend(100)\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_01(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n # Sanity check:\n def sgen():\n try:\n v = yield 1\n except FooEr:\n v = 1000\n yield v * 2\n sg = sgen()\n v = sg.send(None)\n self.assertEqual(v, 1)\n v = sg.throw(FooEr)\n self.assertEqual(v, 2000)\n with self.assertRaises(StopIteration):\n sg.send(None)\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n v = 1000\n await asyncio.sleep(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n v = await g.athrow(FooEr)\n self.assertEqual(v, 2000)\n\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_02(self):\n DONE = 0\n\n class FooEr(Exception):\n pass\n\n async def sleep_n_crash(delay):\n fut = asyncio.ensure_future(asyncio.sleep(delay),\n loop=self.loop)\n self.loop.call_later(delay / 2, lambda: fut.cancel())\n return await fut\n\n async def gen():\n nonlocal DONE\n try:\n await asyncio.sleep(0.01)\n try:\n v = yield 1\n except FooEr:\n await sleep_n_crash(0.01)\n yield v * 2\n await asyncio.sleep(0.01)\n # return\n finally:\n await asyncio.sleep(0.01)\n await asyncio.sleep(0.01)\n DONE = 1\n\n async def run():\n g = gen()\n\n v = await g.asend(None)\n self.assertEqual(v, 1)\n\n try:\n await g.athrow(FooEr)\n except asyncio.CancelledError:\n self.assertEqual(DONE, 1)\n raise\n else:\n self.fail('CancelledError was not raised')\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 1)\n\n def test_async_gen_asyncio_athrow_03(self):\n DONE = 0\n\n # test synchronous generators\n def foo():\n try:\n yield\n except:\n pass\n g = foo()\n g.send(None)\n with self.assertRaises(StopIteration):\n g.throw(ValueError)\n\n # now with asynchronous generators\n\n async def gen():\n nonlocal DONE\n try:\n yield\n except:\n pass\n DONE = 1\n\n async def run():\n nonlocal DONE\n g = gen()\n await g.asend(None)\n with self.assertRaises(StopAsyncIteration):\n await g.athrow(ValueError)\n DONE += 10\n\n self.loop.run_until_complete(run())\n self.assertEqual(DONE, 11)\n\n def test_async_gen_asyncio_athrow_tuple(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield (2,)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertEqual(v, (2,))\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_athrow_stopiteration(self):\n async def gen():\n try:\n yield 1\n except ZeroDivisionError:\n yield StopIteration(2)\n\n async def run():\n g = gen()\n v = await g.asend(None)\n self.assertEqual(v, 1)\n v = await g.athrow(ZeroDivisionError)\n self.assertIsInstance(v, StopIteration)\n self.assertEqual(v.value, 2)\n with self.assertRaises(StopAsyncIteration):\n await g.asend(None)\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_asyncio_shutdown_01(self):\n finalized = 0\n\n async def waiter(timeout):\n nonlocal finalized\n try:\n await asyncio.sleep(timeout)\n yield 1\n finally:\n await asyncio.sleep(0)\n finalized += 1\n\n async def wait():\n async for _ in waiter(1):\n pass\n\n t1 = self.loop.create_task(wait())\n t2 = self.loop.create_task(wait())\n\n self.loop.run_until_complete(asyncio.sleep(0.1))\n\n # Silence warnings\n t1.cancel()\n t2.cancel()\n\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t1)\n with self.assertRaises(asyncio.CancelledError):\n self.loop.run_until_complete(t2)\n\n self.loop.run_until_complete(self.loop.shutdown_asyncgens())\n\n self.assertEqual(finalized, 2)\n\n def test_async_gen_asyncio_shutdown_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n self.assertEqual(messages, [])\n\n def test_async_gen_asyncio_shutdown_exception_01(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n it = async_iterate()\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in it:\n break\n\n asyncio.run(main())\n\n message, = messages\n self.assertEqual(message['asyncgen'], it)\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('an error occurred during closing of asynchronous generator',\n message['message'])\n\n def test_async_gen_asyncio_shutdown_exception_02(self):\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n try:\n yield 1\n yield 2\n finally:\n 1/0\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n gc_collect()\n\n asyncio.run(main())\n\n message, = messages\n self.assertIsInstance(message['exception'], ZeroDivisionError)\n self.assertIn('unhandled exception during asyncio.run() shutdown',\n message['message'])\n del message, messages\n gc_collect()\n\n def test_async_gen_expression_01(self):\n async def arange(n):\n for i in range(n):\n await asyncio.sleep(0.01)\n yield i\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 async for i in arange(n))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(10)])\n\n def test_async_gen_expression_02(self):\n async def wrap(n):\n await asyncio.sleep(0.01)\n return n\n\n def make_arange(n):\n # This syntax is legal starting with Python 3.7\n return (i * 2 for i in range(n) if await wrap(i))\n\n async def run():\n return [i async for i in make_arange(10)]\n\n res = self.loop.run_until_complete(run())\n self.assertEqual(res, [i * 2 for i in range(1, 10)])\n\n def test_asyncgen_nonstarted_hooks_are_cancellable(self):\n # See https://bugs.python.org/issue38013\n messages = []\n\n def exception_handler(loop, context):\n messages.append(context)\n\n async def async_iterate():\n yield 1\n yield 2\n\n async def main():\n loop = asyncio.get_running_loop()\n loop.set_exception_handler(exception_handler)\n\n async for i in async_iterate():\n break\n\n asyncio.run(main())\n\n self.assertEqual([], messages)\n gc_collect()\n\n def test_async_gen_await_same_anext_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.__anext__()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited __anext__\\(\\)/asend\\(\\)\"\n ):\n await nxt\n\n await it.aclose() # prevent unfinished iterator warning\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_await_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n nxt = it.aclose()\n await nxt\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n await nxt\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_throw_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n nxt = it.aclose()\n with self.assertRaises(StopIteration):\n nxt.throw(GeneratorExit)\n\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n nxt.throw(GeneratorExit)\n\n def test_async_gen_throw_custom_same_aclose_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n\n class MyException(Exception):\n pass\n\n nxt = it.aclose()\n with self.assertRaises(MyException):\n nxt.throw(MyException)\n\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n nxt.throw(MyException)\n\n def test_async_gen_throw_custom_same_athrow_coro_twice(self):\n async def async_iterate():\n yield 1\n yield 2\n\n it = async_iterate()\n\n class MyException(Exception):\n pass\n\n nxt = it.athrow(MyException)\n with self.assertRaises(MyException):\n nxt.throw(MyException)\n\n with self.assertRaisesRegex(\n RuntimeError,\n r\"cannot reuse already awaited aclose\\(\\)/athrow\\(\\)\"\n ):\n nxt.throw(MyException)\n\n def test_async_gen_aclose_twice_with_different_coros(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n await it.aclose()\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_after_exhaustion(self):\n # Regression test for https://bugs.python.org/issue39606\n async def async_iterate():\n yield 1\n yield 2\n\n async def run():\n it = async_iterate()\n async for _ in it:\n pass\n await it.aclose()\n\n self.loop.run_until_complete(run())\n\n def test_async_gen_aclose_compatible_with_get_stack(self):\n async def async_generator():\n yield object()\n\n async def run():\n ag = async_generator()\n asyncio.create_task(ag.aclose())\n tasks = asyncio.all_tasks()\n for task in tasks:\n # No AttributeError raised\n task.get_stack()\n\n self.loop.run_until_complete(run())\n","source":"cpython_tests","origin":"Lib/test/test_asyncgen.py::AsyncGenAsyncioTest","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"breakpoint","pep":"553","introduced_in":"3.7","form":"modern","file":"breakpoint/modern_01.py","code":"import ast\nimport builtins\nimport collections\nimport contextlib\nimport copy\nimport decimal\nimport fractions\nimport gc\nimport io\nimport locale\nimport math\nimport os\nimport pickle\nimport platform\nimport random\nimport re\nimport sys\nimport traceback\nimport types\nimport typing\nimport unittest\nimport warnings\nimport weakref\nfrom contextlib import ExitStack\nfrom functools import partial\nfrom inspect import CO_COROUTINE\nfrom itertools import product\nfrom textwrap import dedent\nfrom types import AsyncGeneratorType, FunctionType, CellType\nfrom operator import neg\nfrom test import support\nfrom test.support import cpython_only, swap_attr\nfrom test.support import async_yield, run_yielding_async_fn\nfrom test.support import warnings_helper\nfrom test.support.import_helper import import_module\nfrom test.support.os_helper import (EnvironmentVarGuard, TESTFN, unlink)\nfrom test.support.script_helper import assert_python_ok\nfrom test.support.testcase import ComplexesAreIdenticalMixin\nfrom test.support.warnings_helper import check_warnings\nfrom test.support import requires_IEEE_754\nfrom unittest.mock import MagicMock, patch\n\n\nclass TestBreakpoint(unittest.TestCase):\n def setUp(self):\n # These tests require a clean slate environment. For example, if the\n # test suite is run with $PYTHONBREAKPOINT set to something else, it\n # will mess up these tests. Similarly for sys.breakpointhook.\n # Cleaning the slate here means you can't use breakpoint() to debug\n # these tests, but I think that's okay. Just use pdb.set_trace() if\n # you must.\n self.resources = ExitStack()\n self.addCleanup(self.resources.close)\n self.env = self.resources.enter_context(EnvironmentVarGuard())\n del self.env['PYTHONBREAKPOINT']\n self.resources.enter_context(\n swap_attr(sys, 'breakpointhook', sys.__breakpointhook__))\n\n def test_breakpoint(self):\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once()\n\n def test_breakpoint_with_breakpointhook_set(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_breakpointhook_reset(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint()\n my_breakpointhook.assert_called_once_with()\n # Reset the hook and it will not be called again.\n sys.breakpointhook = sys.__breakpointhook__\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n my_breakpointhook.assert_called_once_with()\n\n def test_breakpoint_with_args_and_keywords(self):\n my_breakpointhook = MagicMock()\n sys.breakpointhook = my_breakpointhook\n breakpoint(1, 2, 3, four=4, five=5)\n my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5)\n\n def test_breakpoint_with_passthru_error(self):\n def my_breakpointhook():\n pass\n sys.breakpointhook = my_breakpointhook\n self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5)\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_builtin(self):\n self.env['PYTHONBREAKPOINT'] = 'int'\n with patch('builtins.int') as mock:\n breakpoint('7')\n mock.assert_called_once_with('7')\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_other(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_good_path_noop_0(self):\n self.env['PYTHONBREAKPOINT'] = '0'\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_not_called()\n\n def test_envar_good_path_empty_string(self):\n # PYTHONBREAKPOINT='' is the same as it not being set.\n self.env['PYTHONBREAKPOINT'] = ''\n with patch('pdb.set_trace') as mock:\n breakpoint()\n mock.assert_called_once_with()\n\n @unittest.skipIf(sys.flags.ignore_environment, '-E was given')\n def test_envar_unimportable(self):\n for envar in (\n '.', '..', '.foo', 'foo.', '.int', 'int.',\n '.foo.bar', '..foo.bar', '/./',\n 'nosuchbuiltin',\n 'nosuchmodule.nosuchcallable',\n ):\n with self.subTest(envar=envar):\n self.env['PYTHONBREAKPOINT'] = envar\n mock = self.resources.enter_context(patch('pdb.set_trace'))\n w = self.resources.enter_context(check_warnings(quiet=True))\n breakpoint()\n self.assertEqual(\n str(w.message),\n f'Ignoring unimportable $PYTHONBREAKPOINT: \"{envar}\"')\n self.assertEqual(w.category, RuntimeWarning)\n mock.assert_not_called()\n\n def test_envar_ignored_when_hook_is_set(self):\n self.env['PYTHONBREAKPOINT'] = 'sys.exit'\n with patch('sys.exit') as mock:\n sys.breakpointhook = int\n breakpoint()\n mock.assert_not_called()\n\n def test_runtime_error_when_hook_is_lost(self):\n del sys.breakpointhook\n with self.assertRaises(RuntimeError):\n breakpoint()\n","source":"cpython_tests","origin":"Lib/test/test_builtin.py::TestBreakpoint","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"class-creation-hooks","pep":"487","introduced_in":"3.6","form":"modern","file":"class-creation-hooks/modern_01.py","code":"import types\nimport unittest\n\n\nclass Test(unittest.TestCase):\n def test_init_subclass(self):\n class A:\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_dict(self):\n class A(dict):\n initialized = False\n\n def __init_subclass__(cls):\n super().__init_subclass__()\n cls.initialized = True\n\n class B(A):\n pass\n\n self.assertFalse(A.initialized)\n self.assertTrue(B.initialized)\n\n def test_init_subclass_kwargs(self):\n class A:\n def __init_subclass__(cls, **kwargs):\n cls.kwargs = kwargs\n\n class B(A, x=3):\n pass\n\n self.assertEqual(B.kwargs, dict(x=3))\n\n def test_init_subclass_error(self):\n class A:\n def __init_subclass__(cls):\n raise RuntimeError\n\n with self.assertRaises(RuntimeError):\n class B(A):\n pass\n\n def test_init_subclass_wrong(self):\n class A:\n def __init_subclass__(cls, whatever):\n pass\n\n with self.assertRaises(TypeError):\n class B(A):\n pass\n\n def test_init_subclass_skipped(self):\n class BaseWithInit:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.initialized = cls\n\n class BaseWithoutInit(BaseWithInit):\n pass\n\n class A(BaseWithoutInit):\n pass\n\n self.assertIs(A.initialized, A)\n self.assertIs(BaseWithoutInit.initialized, BaseWithoutInit)\n\n def test_init_subclass_diamond(self):\n class Base:\n def __init_subclass__(cls, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls = []\n\n class Left(Base):\n pass\n\n class Middle:\n def __init_subclass__(cls, middle, **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [middle]\n\n class Right(Base):\n def __init_subclass__(cls, right=\"right\", **kwargs):\n super().__init_subclass__(**kwargs)\n cls.calls += [right]\n\n class A(Left, Middle, Right, middle=\"middle\"):\n pass\n\n self.assertEqual(A.calls, [\"right\", \"middle\"])\n self.assertEqual(Left.calls, [])\n self.assertEqual(Right.calls, [])\n\n def test_set_name(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A:\n d = Descriptor()\n\n self.assertEqual(A.d.name, \"d\")\n self.assertIs(A.d.owner, A)\n\n def test_set_name_metaclass(self):\n class Meta(type):\n def __new__(cls, name, bases, ns):\n ret = super().__new__(cls, name, bases, ns)\n self.assertEqual(ret.d.name, \"d\")\n self.assertIs(ret.d.owner, ret)\n return 0\n\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class A(metaclass=Meta):\n d = Descriptor()\n self.assertEqual(A, 0)\n\n def test_set_name_error(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n 1/0\n\n with self.assertRaises(ZeroDivisionError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n notes = cm.exception.__notes__\n self.assertRegex(str(notes), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(notes), r'\\battr\\b')\n self.assertRegex(str(notes), r'\\bDescriptor\\b')\n\n def test_set_name_wrong(self):\n class Descriptor:\n def __set_name__(self):\n pass\n\n with self.assertRaises(TypeError) as cm:\n class NotGoingToWork:\n attr = Descriptor()\n\n notes = cm.exception.__notes__\n self.assertRegex(str(notes), r'\\bNotGoingToWork\\b')\n self.assertRegex(str(notes), r'\\battr\\b')\n self.assertRegex(str(notes), r'\\bDescriptor\\b')\n\n def test_set_name_lookup(self):\n resolved = []\n class NonDescriptor:\n def __getattr__(self, name):\n resolved.append(name)\n\n class A:\n d = NonDescriptor()\n\n self.assertNotIn('__set_name__', resolved,\n '__set_name__ is looked up in instance dict')\n\n def test_set_name_init_subclass(self):\n class Descriptor:\n def __set_name__(self, owner, name):\n self.owner = owner\n self.name = name\n\n class Meta(type):\n def __new__(cls, name, bases, ns):\n self = super().__new__(cls, name, bases, ns)\n self.meta_owner = self.owner\n self.meta_name = self.name\n return self\n\n class A:\n def __init_subclass__(cls):\n cls.owner = cls.d.owner\n cls.name = cls.d.name\n\n class B(A, metaclass=Meta):\n d = Descriptor()\n\n self.assertIs(B.owner, B)\n self.assertEqual(B.name, 'd')\n self.assertIs(B.meta_owner, B)\n self.assertEqual(B.name, 'd')\n\n def test_set_name_modifying_dict(self):\n notified = []\n class Descriptor:\n def __set_name__(self, owner, name):\n setattr(owner, name + 'x', None)\n notified.append(name)\n\n class A:\n a = Descriptor()\n b = Descriptor()\n c = Descriptor()\n d = Descriptor()\n e = Descriptor()\n\n self.assertCountEqual(notified, ['a', 'b', 'c', 'd', 'e'])\n\n def test_errors(self):\n class MyMeta(type):\n pass\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta, otherarg=1):\n pass\n\n with self.assertRaises(TypeError):\n types.new_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n types.prepare_class(\"MyClass\", (object,),\n dict(metaclass=MyMeta, otherarg=1))\n\n class MyMeta(type):\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n\n with self.assertRaises(TypeError):\n class MyClass2(metaclass=MyMeta, otherarg=1):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n return super().__new__(cls, name, bases, namespace)\n\n def __init__(self, name, bases, namespace, otherarg):\n super().__init__(name, bases, namespace)\n self.otherarg = otherarg\n\n class MyClass3(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass3.otherarg, 1)\n\n def test_errors_changed_pep487(self):\n # These tests failed before Python 3.6, PEP 487\n class MyMeta(type):\n def __new__(cls, name, bases, namespace):\n return super().__new__(cls, name=name, bases=bases,\n dict=namespace)\n\n with self.assertRaises(TypeError):\n class MyClass(metaclass=MyMeta):\n pass\n\n class MyMeta(type):\n def __new__(cls, name, bases, namespace, otherarg):\n self = super().__new__(cls, name, bases, namespace)\n self.otherarg = otherarg\n return self\n\n class MyClass2(metaclass=MyMeta, otherarg=1):\n pass\n\n self.assertEqual(MyClass2.otherarg, 1)\n\n def test_type(self):\n t = type('NewClass', (object,), {})\n self.assertIsInstance(t, type)\n self.assertEqual(t.__name__, 'NewClass')\n\n with self.assertRaises(TypeError):\n type(name='NewClass', bases=(object,), dict={})\n","source":"cpython_tests","origin":"Lib/test/test_subclassinit.py::Test","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"context-vars","pep":"567","introduced_in":"3.7","form":"modern","file":"context-vars/modern_03.py","code":"import sys\nimport collections.abc\nimport concurrent.futures\nimport contextvars\nimport functools\nimport gc\nimport random\nimport time\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import threading_helper\n\n\nclass ContextTest(unittest.TestCase):\n def test_context_var_new_1(self):\n with self.assertRaisesRegex(TypeError, 'takes exactly 1'):\n contextvars.ContextVar()\n\n with self.assertRaisesRegex(TypeError, 'must be a str'):\n contextvars.ContextVar(1)\n\n c = contextvars.ContextVar('aaa')\n self.assertEqual(c.name, 'aaa')\n\n with self.assertRaises(AttributeError):\n c.name = 'bbb'\n\n self.assertNotEqual(hash(c), hash('aaa'))\n\n @isolated_context\n def test_context_var_repr_1(self):\n c = contextvars.ContextVar('a')\n self.assertIn('a', repr(c))\n\n c = contextvars.ContextVar('a', default=123)\n self.assertIn('123', repr(c))\n\n lst = []\n c = contextvars.ContextVar('a', default=lst)\n lst.append(c)\n self.assertIn('...', repr(c))\n self.assertIn('...', repr(lst))\n\n t = c.set(1)\n self.assertIn(repr(c), repr(t))\n self.assertNotIn(' used ', repr(t))\n c.reset(t)\n self.assertIn(' used ', repr(t))\n\n @isolated_context\n def test_token_repr_1(self):\n c = contextvars.ContextVar('a')\n tok = c.set(1)\n self.assertRegex(repr(tok),\n r\"^ at 0x[0-9a-fA-F]+>$\")\n\n def test_context_subclassing_1(self):\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContextVar(contextvars.ContextVar):\n # Potentially we might want ContextVars to be subclassable.\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyContext(contextvars.Context):\n pass\n\n with self.assertRaisesRegex(TypeError, 'not an acceptable base type'):\n class MyToken(contextvars.Token):\n pass\n\n def test_context_new_1(self):\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(1, a=1)\n with self.assertRaisesRegex(TypeError, 'any arguments'):\n contextvars.Context(a=1)\n contextvars.Context(**{})\n\n def test_context_new_unhashable_str_subclass(self):\n # gh-132002: it used to crash on unhashable str subtypes.\n class weird_str(str):\n def __eq__(self, other):\n pass\n\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n contextvars.ContextVar(weird_str())\n\n def test_context_typerrors_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx[1]\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n 1 in ctx\n with self.assertRaisesRegex(TypeError, 'ContextVar key was expected'):\n ctx.get(1)\n\n def test_context_get_context_1(self):\n ctx = contextvars.copy_context()\n self.assertIsInstance(ctx, contextvars.Context)\n\n def test_context_run_1(self):\n ctx = contextvars.Context()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required'):\n ctx.run()\n\n def test_context_run_2(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n kwargs['spam'] = 'foo'\n args += ('bar',)\n return args, kwargs\n\n for f in (func, functools.partial(func)):\n # partial doesn't support FASTCALL\n\n self.assertEqual(ctx.run(f), (('bar',), {'spam': 'foo'}))\n self.assertEqual(ctx.run(f, 1), ((1, 'bar'), {'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, a=2),\n (('bar',), {'a': 2, 'spam': 'foo'}))\n\n self.assertEqual(\n ctx.run(f, 11, a=2),\n ((11, 'bar'), {'a': 2, 'spam': 'foo'}))\n\n a = {}\n self.assertEqual(\n ctx.run(f, 11, **a),\n ((11, 'bar'), {'spam': 'foo'}))\n self.assertEqual(a, {})\n\n def test_context_run_3(self):\n ctx = contextvars.Context()\n\n def func(*args, **kwargs):\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2)\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func, 1, 2, a=123)\n\n @isolated_context\n def test_context_run_4(self):\n ctx1 = contextvars.Context()\n ctx2 = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func2():\n self.assertIsNone(var.get(None))\n\n def func1():\n self.assertIsNone(var.get(None))\n var.set('spam')\n ctx2.run(func2)\n self.assertEqual(var.get(None), 'spam')\n\n cur = contextvars.copy_context()\n self.assertEqual(len(cur), 1)\n self.assertEqual(cur[var], 'spam')\n return cur\n\n returned_ctx = ctx1.run(func1)\n self.assertEqual(ctx1, returned_ctx)\n self.assertEqual(returned_ctx[var], 'spam')\n self.assertIn(var, returned_ctx)\n\n def test_context_run_5(self):\n ctx = contextvars.Context()\n var = contextvars.ContextVar('var')\n\n def func():\n self.assertIsNone(var.get(None))\n var.set('spam')\n 1 / 0\n\n with self.assertRaises(ZeroDivisionError):\n ctx.run(func)\n\n self.assertIsNone(var.get(None))\n\n def test_context_run_6(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('a', default=0)\n\n def fun():\n self.assertEqual(c.get(), 0)\n self.assertIsNone(ctx.get(c))\n\n c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(ctx.get(c), 42)\n\n ctx.run(fun)\n\n def test_context_run_7(self):\n ctx = contextvars.Context()\n\n def fun():\n with self.assertRaisesRegex(RuntimeError, 'is already entered'):\n ctx.run(fun)\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_1(self):\n c = contextvars.ContextVar('c')\n with self.assertRaises(LookupError):\n c.get()\n\n self.assertIsNone(c.get(None))\n\n t0 = c.set(42)\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n self.assertIs(t0.old_value, t0.MISSING)\n self.assertIs(t0.old_value, contextvars.Token.MISSING)\n self.assertIs(t0.var, c)\n\n t = c.set('spam')\n self.assertEqual(c.get(), 'spam')\n self.assertEqual(c.get(None), 'spam')\n self.assertEqual(t.old_value, 42)\n c.reset(t)\n\n self.assertEqual(c.get(), 42)\n self.assertEqual(c.get(None), 42)\n\n c.set('spam2')\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t)\n self.assertEqual(c.get(), 'spam2')\n\n ctx1 = contextvars.copy_context()\n self.assertIn(c, ctx1)\n\n c.reset(t0)\n with self.assertRaisesRegex(RuntimeError, 'has already been used'):\n c.reset(t0)\n self.assertIsNone(c.get(None))\n\n self.assertIn(c, ctx1)\n self.assertEqual(ctx1[c], 'spam2')\n self.assertEqual(ctx1.get(c, 'aa'), 'spam2')\n self.assertEqual(len(ctx1), 1)\n self.assertEqual(list(ctx1.items()), [(c, 'spam2')])\n self.assertEqual(list(ctx1.values()), ['spam2'])\n self.assertEqual(list(ctx1.keys()), [c])\n self.assertEqual(list(ctx1), [c])\n\n ctx2 = contextvars.copy_context()\n self.assertNotIn(c, ctx2)\n with self.assertRaises(KeyError):\n ctx2[c]\n self.assertEqual(ctx2.get(c, 'aa'), 'aa')\n self.assertEqual(len(ctx2), 0)\n self.assertEqual(list(ctx2), [])\n\n @isolated_context\n def test_context_getset_2(self):\n v1 = contextvars.ContextVar('v1')\n v2 = contextvars.ContextVar('v2')\n\n t1 = v1.set(42)\n with self.assertRaisesRegex(ValueError, 'by a different'):\n v2.reset(t1)\n\n @isolated_context\n def test_context_getset_3(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n def fun():\n self.assertEqual(c.get(), 42)\n with self.assertRaises(KeyError):\n ctx[c]\n self.assertIsNone(ctx.get(c))\n self.assertEqual(ctx.get(c, 'spam'), 'spam')\n self.assertNotIn(c, ctx)\n self.assertEqual(list(ctx.keys()), [])\n\n t = c.set(1)\n self.assertEqual(list(ctx.keys()), [c])\n self.assertEqual(ctx[c], 1)\n\n c.reset(t)\n self.assertEqual(list(ctx.keys()), [])\n with self.assertRaises(KeyError):\n ctx[c]\n\n ctx.run(fun)\n\n @isolated_context\n def test_context_getset_4(self):\n c = contextvars.ContextVar('c', default=42)\n ctx = contextvars.Context()\n\n tok = ctx.run(c.set, 1)\n\n with self.assertRaisesRegex(ValueError, 'different Context'):\n c.reset(tok)\n\n @isolated_context\n def test_context_getset_5(self):\n c = contextvars.ContextVar('c', default=42)\n c.set([])\n\n def fun():\n c.set([])\n c.get().append(42)\n self.assertEqual(c.get(), [42])\n\n contextvars.copy_context().run(fun)\n self.assertEqual(c.get(), [])\n\n def test_context_copy_1(self):\n ctx1 = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def ctx1_fun():\n c.set(10)\n\n ctx2 = ctx1.copy()\n self.assertEqual(ctx2[c], 10)\n\n c.set(20)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 10)\n\n ctx2.run(ctx2_fun)\n self.assertEqual(ctx1[c], 20)\n self.assertEqual(ctx2[c], 30)\n\n def ctx2_fun():\n self.assertEqual(c.get(), 10)\n c.set(30)\n self.assertEqual(c.get(), 30)\n\n ctx1.run(ctx1_fun)\n\n def test_context_isinstance(self):\n ctx = contextvars.Context()\n self.assertIsInstance(ctx, collections.abc.Mapping)\n self.assertTrue(issubclass(contextvars.Context, collections.abc.Mapping))\n\n mapping_methods = (\n '__contains__', '__eq__', '__getitem__', '__iter__', '__len__',\n '__ne__', 'get', 'items', 'keys', 'values',\n )\n for name in mapping_methods:\n with self.subTest(name=name):\n self.assertTrue(callable(getattr(ctx, name)))\n\n @isolated_context\n @threading_helper.requires_working_threading()\n def test_context_threads_1(self):\n cvar = contextvars.ContextVar('cvar')\n\n def sub(num):\n for i in range(10):\n cvar.set(num + i)\n time.sleep(random.uniform(0.001, 0.05))\n self.assertEqual(cvar.get(), num + i)\n return num\n\n tp = concurrent.futures.ThreadPoolExecutor(max_workers=10)\n try:\n results = list(tp.map(sub, range(10)))\n finally:\n tp.shutdown()\n self.assertEqual(results, list(range(10)))\n\n @isolated_context\n @threading_helper.requires_working_threading()\n def test_context_thread_inherit(self):\n import threading\n\n cvar = contextvars.ContextVar('cvar')\n\n def run_context_none():\n if sys.flags.thread_inherit_context:\n expected = 1\n else:\n expected = None\n self.assertEqual(cvar.get(None), expected)\n\n # By default, context is inherited based on the\n # sys.flags.thread_inherit_context option.\n cvar.set(1)\n thread = threading.Thread(target=run_context_none)\n thread.start()\n thread.join()\n\n # Passing 'None' explicitly should have same behaviour as not\n # passing parameter.\n thread = threading.Thread(target=run_context_none, context=None)\n thread.start()\n thread.join()\n\n # An explicit Context value can also be passed\n custom_ctx = contextvars.Context()\n custom_var = None\n\n def setup_context():\n nonlocal custom_var\n custom_var = contextvars.ContextVar('custom')\n custom_var.set(2)\n\n custom_ctx.run(setup_context)\n\n def run_custom():\n self.assertEqual(custom_var.get(), 2)\n\n thread = threading.Thread(target=run_custom, context=custom_ctx)\n thread.start()\n thread.join()\n\n # You can also pass a new Context() object to start with an empty context\n def run_empty():\n with self.assertRaises(LookupError):\n cvar.get()\n\n thread = threading.Thread(target=run_empty, context=contextvars.Context())\n thread.start()\n thread.join()\n\n def test_token_contextmanager_with_default(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('c', default=42)\n\n def fun():\n with c.set(36):\n self.assertEqual(c.get(), 36)\n\n self.assertEqual(c.get(), 42)\n\n ctx.run(fun)\n\n def test_token_contextmanager_without_default(self):\n ctx = contextvars.Context()\n c = contextvars.ContextVar('c')\n\n def fun():\n with c.set(36):\n self.assertEqual(c.get(), 36)\n\n with self.assertRaisesRegex(LookupError, \".C])\")\n\n def test_docstring_one_field(self):\n @dataclass\n class C:\n x: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int)\")\n\n def test_docstring_two_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int)\")\n\n def test_docstring_three_fields(self):\n @dataclass\n class C:\n x: int\n y: int\n z: str\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int, y:int, z:str)\")\n\n def test_docstring_one_field_with_default(self):\n @dataclass\n class C:\n x: int = 3\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int=3)\")\n\n def test_docstring_one_field_with_default_none(self):\n @dataclass\n class C:\n x: Union[int, type(None)] = None\n\n self.assertDocStrEqual(C.__doc__, \"C(x:int|None=None)\")\n\n def test_docstring_list_field(self):\n @dataclass\n class C:\n x: List[int]\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int])\")\n\n def test_docstring_list_field_with_default_factory(self):\n @dataclass\n class C:\n x: List[int] = field(default_factory=list)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:List[int]=)\")\n\n def test_docstring_deque_field(self):\n @dataclass\n class C:\n x: deque\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque)\")\n\n def test_docstring_deque_field_with_default_factory(self):\n @dataclass\n class C:\n x: deque = field(default_factory=deque)\n\n self.assertDocStrEqual(C.__doc__, \"C(x:collections.deque=)\")\n\n def test_docstring_undefined_name(self):\n @dataclass\n class C:\n x: undef\n\n self.assertDocStrEqual(C.__doc__, \"C(x:undef)\")\n\n def test_docstring_with_unsolvable_forward_ref_in_init(self):\n # See: https://github.com/python/cpython/issues/128184\n ns = {}\n exec(\n textwrap.dedent(\n \"\"\"\n from dataclasses import dataclass\n\n @dataclass\n class C:\n def __init__(self, x: X, num: int) -> None: ...\n \"\"\",\n ),\n ns,\n )\n\n self.assertDocStrEqual(ns['C'].__doc__, \"C(x:X,num:int)\")\n\n def test_docstring_with_no_signature(self):\n # See https://github.com/python/cpython/issues/103449\n class Meta(type):\n __call__ = dict\n class Base(metaclass=Meta):\n pass\n\n @dataclass\n class C(Base):\n pass\n\n self.assertDocStrEqual(C.__doc__, \"C\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestDocString","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_19.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestInit(unittest.TestCase):\n def test_base_has_init(self):\n class B:\n def __init__(self):\n self.z = 100\n\n # Make sure that declaring this class doesn't raise an error.\n # The issue is that we can't override __init__ in our class,\n # but it should be okay to add __init__ to us if our base has\n # an __init__.\n @dataclass\n class C(B):\n x: int = 0\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertNotIn('z', vars(c))\n\n # Make sure that if we don't add an init, the base __init__\n # gets called.\n @dataclass(init=False)\n class C(B):\n x: int = 10\n c = C()\n self.assertEqual(c.x, 10)\n self.assertEqual(c.z, 100)\n\n def test_no_init(self):\n @dataclass(init=False)\n class C:\n i: int = 0\n self.assertEqual(C().i, 0)\n\n @dataclass(init=False)\n class C:\n i: int = 2\n def __init__(self):\n self.i = 3\n self.assertEqual(C().i, 3)\n\n def test_overwriting_init(self):\n # If the class has __init__, use it no matter the value of\n # init=.\n\n @dataclass\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(3).x, 6)\n\n @dataclass(init=True)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(4).x, 8)\n\n @dataclass(init=False)\n class C:\n x: int\n def __init__(self, x):\n self.x = 2 * x\n self.assertEqual(C(5).x, 10)\n\n def test_inherit_from_protocol(self):\n # Dataclasses inheriting from protocol should preserve their own `__init__`.\n # See bpo-45081.\n\n class P(Protocol):\n a: int\n\n @dataclass\n class C(P):\n a: int\n\n self.assertEqual(C(5).a, 5)\n\n @dataclass\n class D(P):\n def __init__(self, a):\n self.a = a * 2\n\n self.assertEqual(D(5).a, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestInit","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_20.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestRepr(unittest.TestCase):\n def test_repr(self):\n @dataclass\n class B:\n x: int\n\n @dataclass\n class C(B):\n y: int = 10\n\n o = C(4)\n self.assertEqual(repr(o), 'TestRepr.test_repr..C(x=4, y=10)')\n\n @dataclass\n class D(C):\n x: int = 20\n self.assertEqual(repr(D()), 'TestRepr.test_repr..D(x=20, y=10)')\n\n @dataclass\n class C:\n @dataclass\n class D:\n i: int\n @dataclass\n class E:\n pass\n self.assertEqual(repr(C.D(0)), 'TestRepr.test_repr..C.D(i=0)')\n self.assertEqual(repr(C.E()), 'TestRepr.test_repr..C.E()')\n\n def test_no_repr(self):\n # Test a class with no __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n self.assertIn(f'{__name__}.TestRepr.test_no_repr..C object at',\n repr(C(3)))\n\n # Test a class with a __repr__ and repr=False.\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'C-class'\n self.assertEqual(repr(C(3)), 'C-class')\n\n def test_overwriting_repr(self):\n # If the class has __repr__, use it no matter the value of\n # repr=.\n\n @dataclass\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=True)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n\n @dataclass(repr=False)\n class C:\n x: int\n def __repr__(self):\n return 'x'\n self.assertEqual(repr(C(0)), 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestRepr","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_21.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestEq(unittest.TestCase):\n def test_recursive_eq(self):\n # Test a class with recursive child\n @dataclass\n class C:\n recursive: object = ...\n c = C()\n c.recursive = c\n self.assertEqual(c, c)\n\n def test_no_eq(self):\n # Test a class with no __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n self.assertNotEqual(C(0), C(0))\n c = C(3)\n self.assertEqual(c, c)\n\n # Test a class with an __eq__ and eq=False.\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 10\n self.assertEqual(C(3), 10)\n\n def test_overwriting_eq(self):\n # If the class has __eq__, use it no matter the value of\n # eq=.\n\n @dataclass\n class C:\n x: int\n def __eq__(self, other):\n return other == 3\n self.assertEqual(C(1), 3)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=True)\n class C:\n x: int\n def __eq__(self, other):\n return other == 4\n self.assertEqual(C(1), 4)\n self.assertNotEqual(C(1), 1)\n\n @dataclass(eq=False)\n class C:\n x: int\n def __eq__(self, other):\n return other == 5\n self.assertEqual(C(1), 5)\n self.assertNotEqual(C(1), 1)\n\n def test_eq_field_by_field(self):\n @dataclasses.dataclass\n class Point:\n x: int\n y: int\n\n p1 = Point(1, 2)\n p2 = Point(1, 2)\n p3 = Point(2, 1)\n self.assertEqual(p1, p2)\n self.assertNotEqual(p1, p3)\n\n def test_eq_type_check(self):\n @dataclasses.dataclass\n class A:\n x: int\n\n @dataclasses.dataclass\n class B:\n x: int\n\n a = A(1)\n b = B(1)\n self.assertNotEqual(a, b)\n\n def test_eq_custom_field(self):\n class AlwaysEqual(int):\n def __eq__(self, other):\n return True\n\n @dataclasses.dataclass\n class Foo:\n x: AlwaysEqual\n y: int\n\n f1 = Foo(AlwaysEqual(1), 2)\n f2 = Foo(AlwaysEqual(2), 2)\n self.assertEqual(f1, f2)\n\n def test_eq_nan_field(self):\n @dataclasses.dataclass\n class D:\n x: float\n\n nan = float('nan')\n d1 = D(nan)\n d2 = D(nan)\n self.assertNotEqual(d1, d2)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestEq","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_22.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestOrdering(unittest.TestCase):\n def test_functools_total_ordering(self):\n # Test that functools.total_ordering works with this class.\n @total_ordering\n @dataclass\n class C:\n x: int\n def __lt__(self, other):\n # Perform the test \"backward\", just to make\n # sure this is being called.\n return self.x >= other\n\n self.assertLess(C(0), -1)\n self.assertLessEqual(C(0), -1)\n self.assertGreater(C(0), 1)\n self.assertGreaterEqual(C(0), 1)\n\n def test_no_order(self):\n # Test that no ordering functions are added by default.\n @dataclass(order=False)\n class C:\n x: int\n # Make sure no order methods are added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__lt__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n # Test that __lt__ is still called\n @dataclass(order=False)\n class C:\n x: int\n def __lt__(self, other):\n return False\n # Make sure other methods aren't added.\n self.assertNotIn('__le__', C.__dict__)\n self.assertNotIn('__ge__', C.__dict__)\n self.assertNotIn('__gt__', C.__dict__)\n\n def test_overwriting_order(self):\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __lt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __lt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __le__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __le__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __gt__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __gt__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __ge__'\n '.*using functools.total_ordering'):\n @dataclass(order=True)\n class C:\n x: int\n def __ge__(self):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestOrdering","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_23.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestHash(unittest.TestCase):\n def test_unsafe_hash(self):\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n y: str\n self.assertEqual(hash(C(1, 'foo')), hash((1, 'foo')))\n\n def test_hash_rules(self):\n def non_bool(value):\n # Map to something else that's True, but not a bool.\n if value is None:\n return None\n if value:\n return (3,)\n return 0\n\n def test(case, unsafe_hash, eq, frozen, with_hash, result):\n with self.subTest(case=case, unsafe_hash=unsafe_hash, eq=eq,\n frozen=frozen):\n if result != 'exception':\n if with_hash:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n else:\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n pass\n\n # See if the result matches what's expected.\n if result == 'fn':\n # __hash__ contains the function we generated.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNotNone(C.__dict__['__hash__'])\n\n elif result == '':\n # __hash__ is not present in our class.\n if not with_hash:\n self.assertNotIn('__hash__', C.__dict__)\n\n elif result == 'none':\n # __hash__ is set to None.\n self.assertIn('__hash__', C.__dict__)\n self.assertIsNone(C.__dict__['__hash__'])\n\n elif result == 'exception':\n # Creating the class should cause an exception.\n # This only happens with with_hash==True.\n assert(with_hash)\n with self.assertRaisesRegex(TypeError, 'Cannot overwrite attribute __hash__'):\n @dataclass(unsafe_hash=unsafe_hash, eq=eq, frozen=frozen)\n class C:\n def __hash__(self):\n return 0\n\n else:\n assert False, f'unknown result {result!r}'\n\n # There are 8 cases of:\n # unsafe_hash=True/False\n # eq=True/False\n # frozen=True/False\n # And for each of these, a different result if\n # __hash__ is defined or not.\n for case, (unsafe_hash, eq, frozen, res_no_defined_hash, res_defined_hash) in enumerate([\n (False, False, False, '', ''),\n (False, False, True, '', ''),\n (False, True, False, 'none', ''),\n (False, True, True, 'fn', ''),\n (True, False, False, 'fn', 'exception'),\n (True, False, True, 'fn', 'exception'),\n (True, True, False, 'fn', 'exception'),\n (True, True, True, 'fn', 'exception'),\n ], 1):\n test(case, unsafe_hash, eq, frozen, False, res_no_defined_hash)\n test(case, unsafe_hash, eq, frozen, True, res_defined_hash)\n\n # Test non-bool truth values, too. This is just to\n # make sure the data-driven table in the decorator\n # handles non-bool values.\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), False, res_no_defined_hash)\n test(case, non_bool(unsafe_hash), non_bool(eq), non_bool(frozen), True, res_defined_hash)\n\n\n def test_eq_only(self):\n # If a class defines __eq__, __hash__ is automatically added\n # and set to None. This is normal Python behavior, not\n # related to dataclasses. Make sure we don't interfere with\n # that (see bpo=32546).\n\n @dataclass\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1))\n self.assertNotEqual(C(1), C(4))\n\n # And make sure things work in this case if we specify\n # unsafe_hash=True.\n @dataclass(unsafe_hash=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == other.i\n self.assertEqual(C(1), C(1.0))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n # And check that the classes __eq__ is being used, despite\n # specifying eq=True.\n @dataclass(unsafe_hash=True, eq=True)\n class C:\n i: int\n def __eq__(self, other):\n return self.i == 3 and self.i == other.i\n self.assertEqual(C(3), C(3))\n self.assertNotEqual(C(1), C(1))\n self.assertEqual(hash(C(1)), hash(C(1.0)))\n\n def test_0_field_hash(self):\n @dataclass(frozen=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n @dataclass(unsafe_hash=True)\n class C:\n pass\n self.assertEqual(hash(C()), hash(()))\n\n def test_1_field_hash(self):\n @dataclass(frozen=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n @dataclass(unsafe_hash=True)\n class C:\n x: int\n self.assertEqual(hash(C(4)), hash((4,)))\n self.assertEqual(hash(C(42)), hash((42,)))\n\n def test_hash_no_args(self):\n # Test dataclasses with no hash= argument. This exists to\n # make sure that if the @dataclass parameter name is changed\n # or the non-default hashing behavior changes, the default\n # hashability keeps working the same way.\n\n class Base:\n def __hash__(self):\n return 301\n\n # If frozen or eq is None, then use the default value (do not\n # specify any value in the decorator).\n for frozen, eq, base, expected in [\n (None, None, object, 'unhashable'),\n (None, None, Base, 'unhashable'),\n (None, False, object, 'object'),\n (None, False, Base, 'base'),\n (None, True, object, 'unhashable'),\n (None, True, Base, 'unhashable'),\n (False, None, object, 'unhashable'),\n (False, None, Base, 'unhashable'),\n (False, False, object, 'object'),\n (False, False, Base, 'base'),\n (False, True, object, 'unhashable'),\n (False, True, Base, 'unhashable'),\n (True, None, object, 'tuple'),\n (True, None, Base, 'tuple'),\n (True, False, object, 'object'),\n (True, False, Base, 'base'),\n (True, True, object, 'tuple'),\n (True, True, Base, 'tuple'),\n ]:\n\n with self.subTest(frozen=frozen, eq=eq, base=base, expected=expected):\n # First, create the class.\n if frozen is None and eq is None:\n @dataclass\n class C(base):\n i: int\n elif frozen is None:\n @dataclass(eq=eq)\n class C(base):\n i: int\n elif eq is None:\n @dataclass(frozen=frozen)\n class C(base):\n i: int\n else:\n @dataclass(frozen=frozen, eq=eq)\n class C(base):\n i: int\n\n # Now, make sure it hashes as expected.\n if expected == 'unhashable':\n c = C(10)\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(c)\n\n elif expected == 'base':\n self.assertEqual(hash(C(10)), 301)\n\n elif expected == 'object':\n # I'm not sure what test to use here. object's\n # hash isn't based on id(), so calling hash()\n # won't tell us much. So, just check the\n # function used is object's.\n self.assertIs(C.__hash__, object.__hash__)\n\n elif expected == 'tuple':\n self.assertEqual(hash(C(42)), hash((42,)))\n\n else:\n assert False, f'unknown value for expected={expected!r}'\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestHash","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_24.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestFrozen(unittest.TestCase):\n # Some tests have a subtest with a slotted dataclass.\n # See https://github.com/python/cpython/issues/105936 for the reasons.\n\n def test_frozen(self):\n for slots in (False, True):\n with self.subTest(slots=slots):\n\n @dataclass(frozen=True, slots=slots)\n class C:\n i: int\n\n c = C(10)\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertEqual(c.i, 10)\n with self.assertRaises(FrozenInstanceError):\n del c.i\n self.assertEqual(c.i, 10)\n\n def test_frozen_empty(self):\n for slots in (False, True):\n with self.subTest(slots=slots):\n\n @dataclass(frozen=True, slots=slots)\n class C:\n pass\n\n c = C()\n self.assertNotHasAttr(c, 'i')\n with self.assertRaises(FrozenInstanceError):\n c.i = 5\n self.assertNotHasAttr(c, 'i')\n with self.assertRaises(FrozenInstanceError):\n del c.i\n\n def test_inherit(self):\n @dataclass(frozen=True)\n class C:\n i: int\n\n @dataclass(frozen=True)\n class D(C):\n j: int\n\n d = D(0, 10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n with self.assertRaises(FrozenInstanceError):\n d.j = 6\n self.assertEqual(d.i, 0)\n self.assertEqual(d.j, 10)\n\n def test_inherit_nonfrozen_from_empty_frozen(self):\n @dataclass(frozen=True)\n class C:\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(C):\n j: int\n\n def test_inherit_frozen_mutliple_inheritance(self):\n @dataclass\n class NotFrozen:\n pass\n\n @dataclass(frozen=True)\n class Frozen:\n pass\n\n class NotDataclass:\n pass\n\n for bases in (\n (NotFrozen, Frozen),\n (Frozen, NotFrozen),\n (Frozen, NotDataclass),\n (NotDataclass, Frozen),\n ):\n with self.subTest(bases=bases):\n with self.assertRaisesRegex(\n TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one',\n ):\n @dataclass\n class NotFrozenChild(*bases):\n pass\n\n for bases in (\n (NotFrozen, Frozen),\n (Frozen, NotFrozen),\n (NotFrozen, NotDataclass),\n (NotDataclass, NotFrozen),\n ):\n with self.subTest(bases=bases):\n with self.assertRaisesRegex(\n TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one',\n ):\n @dataclass(frozen=True)\n class FrozenChild(*bases):\n pass\n\n def test_inherit_frozen_mutliple_inheritance_regular_mixins(self):\n @dataclass(frozen=True)\n class Frozen:\n pass\n\n class NotDataclass:\n pass\n\n class C1(Frozen, NotDataclass):\n pass\n self.assertEqual(C1.__mro__, (C1, Frozen, NotDataclass, object))\n\n class C2(NotDataclass, Frozen):\n pass\n self.assertEqual(C2.__mro__, (C2, NotDataclass, Frozen, object))\n\n @dataclass(frozen=True)\n class C3(Frozen, NotDataclass):\n pass\n self.assertEqual(C3.__mro__, (C3, Frozen, NotDataclass, object))\n\n @dataclass(frozen=True)\n class C4(NotDataclass, Frozen):\n pass\n self.assertEqual(C4.__mro__, (C4, NotDataclass, Frozen, object))\n\n def test_multiple_frozen_dataclasses_inheritance(self):\n @dataclass(frozen=True)\n class FrozenA:\n pass\n\n @dataclass(frozen=True)\n class FrozenB:\n pass\n\n class C1(FrozenA, FrozenB):\n pass\n self.assertEqual(C1.__mro__, (C1, FrozenA, FrozenB, object))\n\n class C2(FrozenB, FrozenA):\n pass\n self.assertEqual(C2.__mro__, (C2, FrozenB, FrozenA, object))\n\n @dataclass(frozen=True)\n class C3(FrozenA, FrozenB):\n pass\n self.assertEqual(C3.__mro__, (C3, FrozenA, FrozenB, object))\n\n @dataclass(frozen=True)\n class C4(FrozenB, FrozenA):\n pass\n self.assertEqual(C4.__mro__, (C4, FrozenB, FrozenA, object))\n\n def test_inherit_nonfrozen_from_empty(self):\n @dataclass\n class C:\n pass\n\n @dataclass\n class D(C):\n j: int\n\n d = D(3)\n self.assertEqual(d.j, 3)\n self.assertIsInstance(d, C)\n\n # Test both ways: with an intermediate normal (non-dataclass)\n # class and without an intermediate class.\n def test_inherit_nonfrozen_from_frozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass(frozen=True)\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit non-frozen dataclass from a frozen one'):\n @dataclass\n class D(I):\n pass\n\n def test_inherit_frozen_from_nonfrozen(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n @dataclass\n class C:\n i: int\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n with self.assertRaisesRegex(TypeError,\n 'cannot inherit frozen dataclass from a non-frozen one'):\n @dataclass(frozen=True)\n class D(I):\n pass\n\n def test_inherit_from_normal_class(self):\n for intermediate_class in [True, False]:\n with self.subTest(intermediate_class=intermediate_class):\n class C:\n pass\n\n if intermediate_class:\n class I(C): pass\n else:\n I = C\n\n @dataclass(frozen=True)\n class D(I):\n i: int\n\n d = D(10)\n with self.assertRaises(FrozenInstanceError):\n d.i = 5\n\n def test_non_frozen_normal_derived(self):\n # See bpo-32953 and https://github.com/python/cpython/issues/105936\n for slots in (False, True):\n with self.subTest(slots=slots):\n\n @dataclass(frozen=True, slots=slots)\n class D:\n x: int\n y: int = 10\n z: int = 1\n\n @property\n def readonly(self) -> int:\n return self.x\n\n @property\n def prop(self) -> int:\n return self.z\n\n @prop.setter\n def prop(self, val: int) -> None:\n object.__setattr__(self, 'z', val)\n\n @prop.deleter\n def prop(self) -> None:\n object.__setattr__(self, 'z', 0)\n\n d = D(5)\n self.assertEqual(d.x, 5)\n self.assertEqual(d.y, 10)\n self.assertEqual(d.z, 1)\n self.assertEqual(d.readonly, 5)\n self.assertEqual(d.prop, 1)\n\n with self.assertRaises(FrozenInstanceError):\n d.x = 5\n with self.assertRaises(FrozenInstanceError):\n d.readonly = 5\n with self.assertRaises(FrozenInstanceError):\n d.z = 5\n with self.assertRaises(FrozenInstanceError):\n d.prop = 5\n with self.assertRaises(FrozenInstanceError):\n del d.prop\n\n self.assertEqual(d.x, 5)\n self.assertEqual(d.y, 10)\n self.assertEqual(d.z, 1)\n self.assertEqual(d.readonly, 5)\n self.assertEqual(d.prop, 1)\n\n class S(D):\n pass\n\n s = S(3)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.z, 1)\n self.assertEqual(s.readonly, 3)\n self.assertEqual(s.prop, 1)\n # Can set new attrs:\n s.cached = True\n self.assertTrue(s.cached)\n # Can mutate them:\n s.cached = False\n self.assertFalse(s.cached)\n\n # Can also change writable properties:\n with self.assertRaisesRegex(\n AttributeError,\n 'object has no setter',\n ) as cm:\n s.readonly = 5\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n s.prop = 2\n self.assertEqual(s.x, 3)\n self.assertEqual(s.readonly, 3)\n self.assertEqual(s.prop, 2)\n self.assertEqual(s.z, 2)\n\n # But can't change the frozen attributes.\n with self.assertRaises(FrozenInstanceError):\n s.x = 5\n with self.assertRaises(FrozenInstanceError):\n s.y = 5\n with self.assertRaises(FrozenInstanceError):\n s.z = 5\n self.assertEqual(s.x, 3)\n self.assertEqual(s.y, 10)\n self.assertEqual(s.z, 2)\n self.assertIs(s.cached, False)\n\n with self.assertRaises(FrozenInstanceError):\n del s.x\n self.assertEqual(s.x, 3)\n with self.assertRaises(FrozenInstanceError):\n del s.y\n self.assertEqual(s.y, 10)\n with self.assertRaisesRegex(\n AttributeError,\n 'object has no deleter',\n ) as cm:\n del s.readonly\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n self.assertEqual(s.x, 3)\n self.assertEqual(s.readonly, 3)\n del s.cached\n self.assertNotHasAttr(s, 'cached')\n with self.assertRaisesRegex(\n AttributeError,\n \"object has no attribute 'cached'\",\n ) as cm:\n del s.cached\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n del s.prop\n self.assertEqual(s.z, 0)\n self.assertEqual(s.prop, 0)\n del s.prop\n\n def test_non_frozen_normal_derived_from_empty_frozen(self):\n @dataclass(frozen=True)\n class D:\n pass\n\n class S(D):\n pass\n\n s = S()\n self.assertNotHasAttr(s, 'x')\n s.x = 5\n self.assertEqual(s.x, 5)\n\n del s.x\n self.assertNotHasAttr(s, 'x')\n with self.assertRaises(AttributeError) as cm:\n del s.x\n self.assertNotIsInstance(cm.exception, FrozenInstanceError)\n\n def test_overwriting_frozen(self):\n # frozen uses __setattr__ and __delattr__.\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __setattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __setattr__(self):\n pass\n\n with self.assertRaisesRegex(TypeError,\n 'Cannot overwrite attribute __delattr__'):\n @dataclass(frozen=True)\n class C:\n x: int\n def __delattr__(self):\n pass\n\n @dataclass(frozen=False)\n class C:\n x: int\n def __setattr__(self, name, value):\n self.__dict__['x'] = value * 2\n self.assertEqual(C(10).x, 20)\n\n def test_frozen_hash(self):\n @dataclass(frozen=True)\n class C:\n x: Any\n\n # If x is immutable, we can compute the hash. No exception is\n # raised.\n hash(C(3))\n\n # If x is mutable, computing the hash is an error.\n with self.assertRaisesRegex(TypeError, 'unhashable type'):\n hash(C({}))\n\n def test_frozen_deepcopy_without_slots(self):\n # see: https://github.com/python/cpython/issues/89683\n @dataclass(frozen=True, slots=False)\n class C:\n s: str\n\n c = C('hello')\n self.assertEqual(deepcopy(c), c)\n\n def test_frozen_deepcopy_with_slots(self):\n # see: https://github.com/python/cpython/issues/89683\n with self.subTest('generated __slots__'):\n @dataclass(frozen=True, slots=True)\n class C:\n s: str\n\n c = C('hello')\n self.assertEqual(deepcopy(c), c)\n\n with self.subTest('user-defined __slots__ and no __{get,set}state__'):\n @dataclass(frozen=True, slots=False)\n class C:\n __slots__ = ('s',)\n s: str\n\n # with user-defined slots, __getstate__ and __setstate__ are not\n # automatically added, hence the error\n err = r\"^cannot\\ assign\\ to\\ field\\ 's'$\"\n self.assertRaisesRegex(FrozenInstanceError, err, deepcopy, C(''))\n\n with self.subTest('user-defined __slots__ and __{get,set}state__'):\n @dataclass(frozen=True, slots=False)\n class C:\n __slots__ = ('s',)\n __getstate__ = dataclasses._dataclass_getstate\n __setstate__ = dataclasses._dataclass_setstate\n\n s: str\n\n c = C('hello')\n self.assertEqual(deepcopy(c), c)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestFrozen","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_25.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestSlots(unittest.TestCase):\n def test_simple(self):\n @dataclass\n class C:\n __slots__ = ('x',)\n x: Any\n\n # There was a bug where a variable in a slot was assumed to\n # also have a default value (of type\n # types.MemberDescriptorType).\n with self.assertRaisesRegex(TypeError,\n r\"__init__\\(\\) missing 1 required positional argument: 'x'\"):\n C()\n\n # We can create an instance, and assign to x.\n c = C(10)\n self.assertEqual(c.x, 10)\n c.x = 5\n self.assertEqual(c.x, 5)\n\n # We can't assign to anything else.\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'y'\"):\n c.y = 5\n\n def test_derived_added_field(self):\n # See bpo-33100.\n @dataclass\n class Base:\n __slots__ = ('x',)\n x: Any\n\n @dataclass\n class Derived(Base):\n x: int\n y: int\n\n d = Derived(1, 2)\n self.assertEqual((d.x, d.y), (1, 2))\n\n # We can add a new field to the derived instance.\n d.z = 10\n\n def test_generated_slots(self):\n @dataclass(slots=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n self.assertEqual((c.x, c.y), (1, 2))\n\n c.x = 3\n c.y = 4\n self.assertEqual((c.x, c.y), (3, 4))\n\n with self.assertRaisesRegex(AttributeError, \"'C' object has no attribute 'z'\"):\n c.z = 5\n\n def test_add_slots_when_slots_exists(self):\n with self.assertRaisesRegex(TypeError, '^C already specifies __slots__$'):\n @dataclass(slots=True)\n class C:\n __slots__ = ('x',)\n x: int\n\n def test_generated_slots_value(self):\n\n class Root:\n __slots__ = {'x'}\n\n class Root2(Root):\n __slots__ = {'k': '...', 'j': ''}\n\n class Root3(Root2):\n __slots__ = ['h']\n\n class Root4(Root3):\n __slots__ = 'aa'\n\n @dataclass(slots=True)\n class Base(Root4):\n y: int\n j: str\n h: str\n\n self.assertEqual(Base.__slots__, ('y',))\n\n @dataclass(slots=True)\n class Derived(Base):\n aa: float\n x: str\n z: int\n k: str\n h: str\n\n self.assertEqual(Derived.__slots__, ('z',))\n\n @dataclass\n class AnotherDerived(Base):\n z: int\n\n self.assertNotIn('__slots__', AnotherDerived.__dict__)\n\n def test_slots_with_docs(self):\n class Root:\n __slots__ = {'x': 'x'}\n\n @dataclass(slots=True)\n class Base(Root):\n y1: int = field(doc='y1')\n y2: int\n\n self.assertEqual(Base.__slots__, {'y1': 'y1', 'y2': None})\n\n @dataclass(slots=True)\n class Child(Base):\n z1: int = field(doc='z1')\n z2: int\n\n self.assertEqual(Child.__slots__, {'z1': 'z1', 'z2': None})\n\n def test_cant_inherit_from_iterator_slots(self):\n\n class Root:\n __slots__ = iter(['a'])\n\n class Root2(Root):\n __slots__ = ('b', )\n\n with self.assertRaisesRegex(\n TypeError,\n \"^Slots of 'Root' cannot be determined\"\n ):\n @dataclass(slots=True)\n class C(Root2):\n x: int\n\n def test_returns_new_class(self):\n class A:\n x: int\n\n B = dataclass(A, slots=True)\n self.assertIsNot(A, B)\n\n self.assertNotHasAttr(A, \"__slots__\")\n self.assertHasAttr(B, \"__slots__\")\n\n # Can't be local to test_frozen_pickle.\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsClass:\n foo: str\n bar: int\n\n @dataclass(frozen=True)\n class FrozenWithoutSlotsClass:\n foo: str\n bar: int\n\n def test_frozen_pickle(self):\n # bpo-43999\n\n self.assertEqual(self.FrozenSlotsClass.__slots__, (\"foo\", \"bar\"))\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n obj = self.FrozenWithoutSlotsClass(\"a\", 1)\n p = pickle.loads(pickle.dumps(obj, protocol=proto))\n self.assertIsNot(obj, p)\n self.assertEqual(obj, p)\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsGetStateClass:\n foo: str\n bar: int\n\n getstate_called: bool = field(default=False, compare=False)\n\n def __getstate__(self):\n object.__setattr__(self, 'getstate_called', True)\n return [self.foo, self.bar]\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsSetStateClass:\n foo: str\n bar: int\n\n setstate_called: bool = field(default=False, compare=False)\n\n def __setstate__(self, state):\n object.__setattr__(self, 'setstate_called', True)\n object.__setattr__(self, 'foo', state[0])\n object.__setattr__(self, 'bar', state[1])\n\n @dataclass(frozen=True, slots=True)\n class FrozenSlotsAllStateClass:\n foo: str\n bar: int\n\n getstate_called: bool = field(default=False, compare=False)\n setstate_called: bool = field(default=False, compare=False)\n\n def __getstate__(self):\n object.__setattr__(self, 'getstate_called', True)\n return [self.foo, self.bar]\n\n def __setstate__(self, state):\n object.__setattr__(self, 'setstate_called', True)\n object.__setattr__(self, 'foo', state[0])\n object.__setattr__(self, 'bar', state[1])\n\n def test_frozen_slots_pickle_custom_state(self):\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsGetStateClass('a', 1)\n dumped = pickle.dumps(obj, protocol=proto)\n\n self.assertTrue(obj.getstate_called)\n self.assertEqual(obj, pickle.loads(dumped))\n\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsSetStateClass('a', 1)\n obj2 = pickle.loads(pickle.dumps(obj, protocol=proto))\n\n self.assertTrue(obj2.setstate_called)\n self.assertEqual(obj, obj2)\n\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n obj = self.FrozenSlotsAllStateClass('a', 1)\n dumped = pickle.dumps(obj, protocol=proto)\n\n self.assertTrue(obj.getstate_called)\n\n obj2 = pickle.loads(dumped)\n self.assertTrue(obj2.setstate_called)\n self.assertEqual(obj, obj2)\n\n def test_slots_with_default_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default='b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_with_default_factory_no_init(self):\n # Originally reported in bpo-44649.\n @dataclass(slots=True)\n class A:\n a: str\n b: str = field(default_factory=lambda:'b', init=False)\n\n obj = A(\"a\")\n self.assertEqual(obj.a, 'a')\n self.assertEqual(obj.b, 'b')\n\n def test_slots_no_weakref(self):\n @dataclass(slots=True)\n class A:\n # No weakref.\n pass\n\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A()\n with self.assertRaisesRegex(TypeError,\n \"cannot create weak reference\"):\n weakref.ref(a)\n with self.assertRaises(AttributeError):\n a.__weakref__\n\n def test_slots_weakref(self):\n @dataclass(slots=True, weakref_slot=True)\n class A:\n a: int\n\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n\n self.assertIs(a.__weakref__, a_ref)\n\n def test_slots_weakref_base_str(self):\n class Base:\n __slots__ = '__weakref__'\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_slots_weakref_base_tuple(self):\n # Same as test_slots_weakref_base, but use a tuple instead of a string\n # in the base class.\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True)\n class A(Base):\n a: int\n\n # __weakref__ is in the base class, not A. But an A is still\n # weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n def test_weakref_slot_without_slot(self):\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n @dataclass(weakref_slot=True)\n class A:\n a: int\n\n def test_weakref_slot_make_dataclass(self):\n A = make_dataclass('A', [('a', int),], slots=True, weakref_slot=True)\n self.assertIn(\"__weakref__\", A.__slots__)\n a = A(1)\n weakref.ref(a)\n\n # And make sure if raises if slots=True is not given.\n with self.assertRaisesRegex(TypeError,\n \"weakref_slot is True but slots is False\"):\n B = make_dataclass('B', [('a', int),], weakref_slot=True)\n\n def test_weakref_slot_subclass_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n # A *can* also specify weakref_slot=True if it wants to (gh-93521)\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. But an instance of A\n # is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_weakref_slot_subclass_no_weakref_slot(self):\n @dataclass(slots=True, weakref_slot=True)\n class Base:\n field: int\n\n @dataclass(slots=True)\n class A(Base):\n ...\n\n # __weakref__ is in the base class, not A. Even though A doesn't\n # specify weakref_slot, it should still be weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_weakref_slot_normal_base_weakref_slot(self):\n class Base:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True, weakref_slot=True)\n class A(Base):\n field: int\n\n # __weakref__ is in the base class, not A. But an instance of\n # A is still weakref-able.\n self.assertIn(\"__weakref__\", Base.__slots__)\n self.assertNotIn(\"__weakref__\", A.__slots__)\n a = A(1)\n a_ref = weakref.ref(a)\n self.assertIs(a.__weakref__, a_ref)\n\n def test_dataclass_derived_weakref_slot(self):\n class A:\n pass\n\n @dataclass(slots=True, weakref_slot=True)\n class B(A):\n pass\n\n self.assertEqual(B.__slots__, ())\n B()\n\n def test_dataclass_derived_generic(self):\n T = typing.TypeVar('T')\n\n @dataclass(slots=True, weakref_slot=True)\n class A(typing.Generic[T]):\n pass\n self.assertEqual(A.__slots__, ('__weakref__',))\n self.assertTrue(A.__weakref__)\n A()\n\n @dataclass(slots=True, weakref_slot=True)\n class B[T2]:\n pass\n self.assertEqual(B.__slots__, ('__weakref__',))\n self.assertTrue(B.__weakref__)\n B()\n\n def test_dataclass_derived_generic_from_base(self):\n T = typing.TypeVar('T')\n\n class RawBase: ...\n\n @dataclass(slots=True, weakref_slot=True)\n class C1(typing.Generic[T], RawBase):\n pass\n self.assertEqual(C1.__slots__, ())\n self.assertTrue(C1.__weakref__)\n C1()\n @dataclass(slots=True, weakref_slot=True)\n class C2(RawBase, typing.Generic[T]):\n pass\n self.assertEqual(C2.__slots__, ())\n self.assertTrue(C2.__weakref__)\n C2()\n\n @dataclass(slots=True, weakref_slot=True)\n class D[T2](RawBase):\n pass\n self.assertEqual(D.__slots__, ())\n self.assertTrue(D.__weakref__)\n D()\n\n def test_dataclass_derived_generic_from_slotted_base(self):\n T = typing.TypeVar('T')\n\n class WithSlots:\n __slots__ = ('a', 'b')\n\n @dataclass(slots=True, weakref_slot=True)\n class E1(WithSlots, Generic[T]):\n pass\n self.assertEqual(E1.__slots__, ('__weakref__',))\n self.assertTrue(E1.__weakref__)\n E1()\n @dataclass(slots=True, weakref_slot=True)\n class E2(Generic[T], WithSlots):\n pass\n self.assertEqual(E2.__slots__, ('__weakref__',))\n self.assertTrue(E2.__weakref__)\n E2()\n\n @dataclass(slots=True, weakref_slot=True)\n class F[T2](WithSlots):\n pass\n self.assertEqual(F.__slots__, ('__weakref__',))\n self.assertTrue(F.__weakref__)\n F()\n\n def test_dataclass_derived_generic_from_slotted_base_with_weakref(self):\n T = typing.TypeVar('T')\n\n class WithWeakrefSlot:\n __slots__ = ('__weakref__',)\n\n @dataclass(slots=True, weakref_slot=True)\n class G1(WithWeakrefSlot, Generic[T]):\n pass\n self.assertEqual(G1.__slots__, ())\n self.assertTrue(G1.__weakref__)\n G1()\n @dataclass(slots=True, weakref_slot=True)\n class G2(Generic[T], WithWeakrefSlot):\n pass\n self.assertEqual(G2.__slots__, ())\n self.assertTrue(G2.__weakref__)\n G2()\n\n @dataclass(slots=True, weakref_slot=True)\n class H[T2](WithWeakrefSlot):\n pass\n self.assertEqual(H.__slots__, ())\n self.assertTrue(H.__weakref__)\n H()\n\n def test_dataclass_slot_dict(self):\n class WithDictSlot:\n __slots__ = ('__dict__',)\n\n @dataclass(slots=True)\n class A(WithDictSlot): ...\n\n self.assertEqual(A.__slots__, ())\n self.assertEqual(A().__dict__, {})\n A()\n\n @support.cpython_only\n def test_dataclass_slot_dict_ctype(self):\n # https://github.com/python/cpython/issues/123935\n # Skips test if `_testcapi` is not present:\n _testcapi = import_helper.import_module('_testcapi')\n\n @dataclass(slots=True)\n class HasDictOffset(_testcapi.HeapCTypeWithDict):\n __dict__: dict = {}\n self.assertNotEqual(_testcapi.HeapCTypeWithDict.__dictoffset__, 0)\n self.assertEqual(HasDictOffset.__slots__, ())\n\n @dataclass(slots=True)\n class DoesNotHaveDictOffset(_testcapi.HeapCTypeWithWeakref):\n __dict__: dict = {}\n self.assertEqual(_testcapi.HeapCTypeWithWeakref.__dictoffset__, 0)\n self.assertEqual(DoesNotHaveDictOffset.__slots__, ('__dict__',))\n\n @support.cpython_only\n def test_slots_with_wrong_init_subclass(self):\n # TODO: This test is for a kinda-buggy behavior.\n # Ideally, it should be fixed and `__init_subclass__`\n # should be fully supported in the future versions.\n # See https://github.com/python/cpython/issues/91126\n class WrongSuper:\n def __init_subclass__(cls, arg):\n pass\n\n with self.assertRaisesRegex(\n TypeError,\n \"missing 1 required positional argument: 'arg'\",\n ):\n @dataclass(slots=True)\n class WithWrongSuper(WrongSuper, arg=1):\n pass\n\n class CorrectSuper:\n args = []\n def __init_subclass__(cls, arg=\"default\"):\n cls.args.append(arg)\n\n @dataclass(slots=True)\n class WithCorrectSuper(CorrectSuper):\n pass\n\n # __init_subclass__ is called twice: once for `WithCorrectSuper`\n # and once for `WithCorrectSuper__slots__` new class\n # that we create internally.\n self.assertEqual(CorrectSuper.args, [\"default\", \"default\"])\n\n def test_original_class_is_gced(self):\n # gh-135228: Make sure when we replace the class with slots=True, the original class\n # gets garbage collected.\n def make_simple():\n @dataclass(slots=True)\n class SlotsTest:\n pass\n\n return SlotsTest\n\n # See https://github.com/python/cpython/issues/135228#issuecomment-3755979059\n def make_frozen():\n @dataclass(frozen=True, slots=True)\n class SlotsTest:\n pass\n\n return SlotsTest\n\n def make_with_annotations():\n @dataclass(slots=True)\n class SlotsTest:\n x: int\n\n return SlotsTest\n\n def make_with_annotations_and_method():\n @dataclass(slots=True)\n class SlotsTest:\n x: int\n\n def method(self) -> int:\n return self.x\n\n return SlotsTest\n\n def make_with_forwardref():\n @dataclass(slots=True)\n class SlotsTest:\n x: undefined\n y: list[undefined]\n\n return SlotsTest\n\n for make in (make_simple, make_frozen, make_with_annotations, make_with_annotations_and_method, make_with_forwardref):\n with self.subTest(make=make):\n C = make()\n support.gc_collect()\n candidates = [cls for cls in object.__subclasses__() if cls.__name__ == 'SlotsTest'\n and cls.__firstlineno__ == make.__code__.co_firstlineno + 1]\n self.assertEqual(candidates, [C])\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestSlots","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_26.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestDescriptors(unittest.TestCase):\n def test_set_name(self):\n # See bpo-33141.\n\n # Create a descriptor.\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n def __get__(self, instance, owner):\n if instance is not None:\n return 1\n return self\n\n # This is the case of just normal descriptor behavior, no\n # dataclass code is involved in initializing the descriptor.\n @dataclass\n class C:\n c: int=D()\n self.assertEqual(C.c.name, 'cx')\n\n # Now test with a default value and init=False, which is the\n # only time this is really meaningful. If not using\n # init=False, then the descriptor will be overwritten, anyway.\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n self.assertEqual(C().c, 1)\n\n def test_non_descriptor(self):\n # PEP 487 says __set_name__ should work on non-descriptors.\n # Create a descriptor.\n\n class D:\n def __set_name__(self, owner, name):\n self.name = name + 'x'\n\n @dataclass\n class C:\n c: int=field(default=D(), init=False)\n self.assertEqual(C.c.name, 'cx')\n\n def test_lookup_on_instance(self):\n # See bpo-33175.\n class D:\n pass\n\n d = D()\n # Create an attribute on the instance, not type.\n d.__set_name__ = Mock()\n\n # Make sure d.__set_name__ is not called.\n @dataclass\n class C:\n i: int=field(default=d, init=False)\n\n self.assertEqual(d.__set_name__.call_count, 0)\n\n def test_lookup_on_class(self):\n # See bpo-33175.\n class D:\n pass\n D.__set_name__ = Mock()\n\n # Make sure D.__set_name__ is called.\n @dataclass\n class C:\n i: int=field(default=D(), init=False)\n\n self.assertEqual(D.__set_name__.call_count, 1)\n\n def test_init_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_getting_field_calls_get(self):\n class D:\n pass\n\n D.__set__ = Mock()\n D.__get__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__get__ is called.\n D.__get__.reset_mock()\n value = c.i\n self.assertEqual(D.__get__.call_count, 1)\n\n def test_setting_field_calls_set(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D = D()\n\n c = C(5)\n\n # Make sure D.__set__ is called.\n D.__set__.reset_mock()\n c.i = 10\n self.assertEqual(D.__set__.call_count, 1)\n\n def test_setting_uninitialized_descriptor_field(self):\n class D:\n pass\n\n D.__set__ = Mock()\n\n @dataclass\n class C:\n i: D\n\n # D.__set__ is not called because there's no D instance to call it on\n D.__set__.reset_mock()\n c = C(5)\n self.assertEqual(D.__set__.call_count, 0)\n\n # D.__set__ still isn't called after setting i to an instance of D\n # because descriptors don't behave like that when stored as instance vars\n c.i = D()\n c.i = 5\n self.assertEqual(D.__set__.call_count, 0)\n\n def test_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n return 100\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n c = C()\n self.assertEqual(c.i, 100)\n\n c = C(5)\n self.assertEqual(c.i, 5)\n\n def test_no_default_value(self):\n class D:\n def __get__(self, instance: Any, owner: object) -> int:\n if instance is None:\n raise AttributeError()\n\n return instance._x\n\n def __set__(self, instance: Any, value: int) -> None:\n instance._x = value\n\n @dataclass\n class C:\n i: D = D()\n\n with self.assertRaisesRegex(TypeError, 'missing 1 required positional argument'):\n c = C()\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestDescriptors","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_27.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestMakeDataclass(unittest.TestCase):\n def test_simple(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace={'add_one': lambda self: self.x + 1})\n c = C(10)\n self.assertEqual((c.x, c.y), (10, 5))\n self.assertEqual(c.add_one(), 11)\n\n\n def test_no_mutate_namespace(self):\n # Make sure a provided namespace isn't mutated.\n ns = {}\n C = make_dataclass('C',\n [('x', int),\n ('y', int, field(default=5))],\n namespace=ns)\n self.assertEqual(ns, {})\n\n def test_base(self):\n class Base1:\n pass\n class Base2:\n pass\n C = make_dataclass('C',\n [('x', int)],\n bases=(Base1, Base2))\n c = C(2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n def test_base_dataclass(self):\n @dataclass\n class Base1:\n x: int\n class Base2:\n pass\n C = make_dataclass('C',\n [('y', int)],\n bases=(Base1, Base2))\n with self.assertRaisesRegex(TypeError, 'required positional'):\n c = C(2)\n c = C(1, 2)\n self.assertIsInstance(c, C)\n self.assertIsInstance(c, Base1)\n self.assertIsInstance(c, Base2)\n\n self.assertEqual((c.x, c.y), (1, 2))\n\n def test_init_var(self):\n def post_init(self, y):\n self.x *= y\n\n C = make_dataclass('C',\n [('x', int),\n ('y', InitVar[int]),\n ],\n namespace={'__post_init__': post_init},\n )\n c = C(2, 3)\n self.assertEqual(vars(c), {'x': 6})\n self.assertEqual(len(fields(c)), 1)\n\n def test_class_var(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ])\n c = C(1)\n self.assertEqual(vars(c), {'x': 1})\n self.assertEqual(len(fields(c)), 1)\n self.assertEqual(C.y, 10)\n self.assertEqual(C.z, 20)\n\n def test_other_params(self):\n C = make_dataclass('C',\n [('x', int),\n ('y', ClassVar[int], 10),\n ('z', ClassVar[int], field(default=20)),\n ],\n init=False)\n # Make sure we have a repr, but no init.\n self.assertNotIn('__init__', vars(C))\n self.assertIn('__repr__', vars(C))\n\n # Make sure random other params don't work.\n with self.assertRaisesRegex(TypeError, 'unexpected keyword argument'):\n C = make_dataclass('C',\n [],\n xxinit=False)\n\n def test_no_types(self):\n C = make_dataclass('Point', ['x', 'y', 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': typing.Any,\n 'y': typing.Any,\n 'z': typing.Any})\n\n C = make_dataclass('Point', ['x', ('y', int), 'z'])\n c = C(1, 2, 3)\n self.assertEqual(vars(c), {'x': 1, 'y': 2, 'z': 3})\n self.assertEqual(C.__annotations__, {'x': typing.Any,\n 'y': int,\n 'z': typing.Any})\n\n def test_no_types_get_annotations(self):\n C = make_dataclass('C', ['x', ('y', int), 'z'])\n\n self.assertEqual(\n annotationlib.get_annotations(C, format=annotationlib.Format.VALUE),\n {'x': typing.Any, 'y': int, 'z': typing.Any},\n )\n self.assertEqual(\n annotationlib.get_annotations(\n C, format=annotationlib.Format.FORWARDREF),\n {'x': typing.Any, 'y': int, 'z': typing.Any},\n )\n self.assertEqual(\n annotationlib.get_annotations(\n C, format=annotationlib.Format.STRING),\n {'x': 'typing.Any', 'y': 'int', 'z': 'typing.Any'},\n )\n\n def test_no_types_no_typing_import(self):\n with import_helper.CleanImport('typing'):\n self.assertNotIn('typing', sys.modules)\n C = make_dataclass('C', ['x', ('y', int)])\n\n self.assertNotIn('typing', sys.modules)\n self.assertEqual(\n C.__annotate__(annotationlib.Format.FORWARDREF),\n {\n 'x': annotationlib.ForwardRef('Any', module='typing'),\n 'y': int,\n },\n )\n self.assertNotIn('typing', sys.modules)\n\n for field in fields(C):\n if field.name == \"x\":\n self.assertEqual(field.type, annotationlib.ForwardRef('Any', module='typing'))\n else:\n self.assertEqual(field.name, \"y\")\n self.assertIs(field.type, int)\n\n def test_module_attr(self):\n self.assertEqual(ByMakeDataClass.__module__, __name__)\n self.assertEqual(ByMakeDataClass(1).__module__, __name__)\n self.assertEqual(WrongModuleMakeDataclass.__module__, \"custom\")\n Nested = make_dataclass('Nested', [])\n self.assertEqual(Nested.__module__, __name__)\n self.assertEqual(Nested().__module__, __name__)\n\n def test_pickle_support(self):\n for klass in [ByMakeDataClass, ManualModuleMakeDataClass]:\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n self.assertEqual(\n pickle.loads(pickle.dumps(klass, proto)),\n klass,\n )\n self.assertEqual(\n pickle.loads(pickle.dumps(klass(1), proto)),\n klass(1),\n )\n\n def test_cannot_be_pickled(self):\n for klass in [WrongNameMakeDataclass, WrongModuleMakeDataclass]:\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(proto=proto):\n with self.assertRaises(pickle.PickleError):\n pickle.dumps(klass, proto)\n with self.assertRaises(pickle.PickleError):\n pickle.dumps(klass(1), proto)\n\n def test_invalid_type_specification(self):\n for bad_field in [(),\n (1, 2, 3, 4),\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'Invalid field: '):\n make_dataclass('C', ['a', bad_field])\n\n # And test for things with no len().\n for bad_field in [float,\n lambda x:x,\n ]:\n with self.subTest(bad_field=bad_field):\n with self.assertRaisesRegex(TypeError, r'has no len\\(\\)'):\n make_dataclass('C', ['a', bad_field])\n\n def test_duplicate_field_names(self):\n for field in ['a', 'ab']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'Field name duplicated'):\n make_dataclass('C', [field, 'a', field])\n\n def test_keyword_field_names(self):\n for field in ['for', 'async', 'await', 'as']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must not be keywords'):\n make_dataclass('C', [field, 'a'])\n\n def test_non_identifier_field_names(self):\n for field in ['()', 'x,y', '*', '2@3', '', 'little johnny tables']:\n with self.subTest(field=field):\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', ['a', field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field])\n with self.assertRaisesRegex(TypeError, 'must be valid identifiers'):\n make_dataclass('C', [field, 'a'])\n\n def test_underscore_field_names(self):\n # Unlike namedtuple, it's okay if dataclass field names have\n # an underscore.\n make_dataclass('C', ['_', '_a', 'a_a', 'a_'])\n\n def test_funny_class_names_names(self):\n # No reason to prevent weird class names, since\n # types.new_class allows them.\n for classname in ['()', 'x,y', '*', '2@3', '']:\n with self.subTest(classname=classname):\n C = make_dataclass(classname, ['a', 'b'])\n self.assertEqual(C.__name__, classname)\n\n def test_dataclass_decorator_default(self):\n C = make_dataclass('C', [('x', int)], decorator=dataclass)\n c = C(10)\n self.assertEqual(c.x, 10)\n\n def test_dataclass_custom_decorator(self):\n def custom_dataclass(cls, *args, **kwargs):\n dc = dataclass(cls, *args, **kwargs)\n dc.__custom__ = True\n return dc\n\n C = make_dataclass('C', [('x', int)], decorator=custom_dataclass)\n c = C(10)\n self.assertEqual(c.x, 10)\n self.assertEqual(c.__custom__, True)\n\n def test_empty_annotation_string(self):\n @dataclass\n class DataclassWithEmptyTypeAnnotation:\n x: \"\"\n\n c = DataclassWithEmptyTypeAnnotation(10)\n self.assertEqual(c.x, 10)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestMakeDataclass","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_28.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestReplace(unittest.TestCase):\n def test(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual(c1.x, 3)\n self.assertEqual(c1.y, 2)\n\n def test_frozen(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n z: int = field(init=False, default=10)\n t: int = field(init=False, default=100)\n\n c = C(1, 2)\n c1 = replace(c, x=3)\n self.assertEqual((c.x, c.y, c.z, c.t), (1, 2, 10, 100))\n self.assertEqual((c1.x, c1.y, c1.z, c1.t), (3, 2, 10, 100))\n\n\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, x=3, z=20, t=50)\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, z=20)\n replace(c, x=3, z=20, t=50)\n\n # Make sure the result is still frozen.\n with self.assertRaisesRegex(FrozenInstanceError, \"cannot assign to field 'x'\"):\n c1.x = 3\n\n # Make sure we can't replace an attribute that doesn't exist,\n # if we're also replacing one that does exist. Test this\n # here, because setting attributes on frozen instances is\n # handled slightly differently from non-frozen ones.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'a'\"):\n c1 = replace(c, x=20, a=5)\n\n def test_invalid_field_name(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n c = C(1, 2)\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an unexpected \"\n \"keyword argument 'z'\"):\n c1 = replace(c, z=3)\n\n def test_invalid_object(self):\n @dataclass(frozen=True)\n class C:\n x: int\n y: int\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(C, x=3)\n\n with self.assertRaisesRegex(TypeError, 'dataclass instance'):\n replace(0, x=3)\n\n def test_no_init(self):\n @dataclass\n class C:\n x: int\n y: int = field(init=False, default=10)\n\n c = C(1)\n c.y = 20\n\n # Make sure y gets the default value.\n c1 = replace(c, x=5)\n self.assertEqual((c1.x, c1.y), (5, 10))\n\n # Trying to replace y is an error.\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, x=2, y=30)\n\n with self.assertRaisesRegex(TypeError, 'init=False'):\n replace(c, y=30)\n\n def test_classvar(self):\n @dataclass\n class C:\n x: int\n y: ClassVar[int] = 1000\n\n c = C(1)\n d = C(2)\n\n self.assertIs(c.y, d.y)\n self.assertEqual(c.y, 1000)\n\n # Trying to replace y is an error: can't replace ClassVars.\n with self.assertRaisesRegex(TypeError, r\"__init__\\(\\) got an \"\n \"unexpected keyword argument 'y'\"):\n replace(c, y=30)\n\n replace(c, x=5)\n\n def test_initvar_is_specified(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int]\n\n def __post_init__(self, y):\n self.x *= y\n\n c = C(1, 10)\n self.assertEqual(c.x, 10)\n with self.assertRaisesRegex(TypeError, r\"InitVar 'y' must be \"\n r\"specified with replace\\(\\)\"):\n replace(c, x=3)\n c = replace(c, x=3, y=5)\n self.assertEqual(c.x, 15)\n\n def test_initvar_with_default_value(self):\n @dataclass\n class C:\n x: int\n y: InitVar[int] = None\n z: InitVar[int] = 42\n\n def __post_init__(self, y, z):\n if y is not None:\n self.x += y\n if z is not None:\n self.x += z\n\n c = C(x=1, y=10, z=1)\n self.assertEqual(replace(c), C(x=12))\n self.assertEqual(replace(c, y=4), C(x=12, y=4, z=42))\n self.assertEqual(replace(c, y=4, z=1), C(x=12, y=4, z=1))\n\n def test_recursive_repr(self):\n @dataclass\n class C:\n f: \"C\"\n\n c = C(None)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr..C(f=...)\")\n\n def test_recursive_repr_two_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: \"C\"\n\n c = C(None, None)\n c.f = c\n c.g = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_two_attrs\"\n \"..C(f=..., g=...)\")\n\n def test_recursive_repr_indirection(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n c.f = d\n d.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection\"\n \"..C(f=TestReplace.test_recursive_repr_indirection\"\n \"..D(f=...))\")\n\n def test_recursive_repr_indirection_two(self):\n @dataclass\n class C:\n f: \"D\"\n\n @dataclass\n class D:\n f: \"E\"\n\n @dataclass\n class E:\n f: \"C\"\n\n c = C(None)\n d = D(None)\n e = E(None)\n c.f = d\n d.f = e\n e.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_indirection_two\"\n \"..C(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..D(f=TestReplace.test_recursive_repr_indirection_two\"\n \"..E(f=...)))\")\n\n def test_recursive_repr_misc_attrs(self):\n @dataclass\n class C:\n f: \"C\"\n g: int\n\n c = C(None, 1)\n c.f = c\n self.assertEqual(repr(c), \"TestReplace.test_recursive_repr_misc_attrs\"\n \"..C(f=..., g=1)\")\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestReplace","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_29.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestAbstract(unittest.TestCase):\n def test_abc_implementation(self):\n class Ordered(abc.ABC):\n @abc.abstractmethod\n def __lt__(self, other):\n pass\n\n @abc.abstractmethod\n def __le__(self, other):\n pass\n\n @dataclass(order=True)\n class Date(Ordered):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertFalse(inspect.isabstract(Date))\n self.assertGreater(Date(2020,12,25), Date(2020,8,31))\n\n def test_maintain_abc(self):\n class A(abc.ABC):\n @abc.abstractmethod\n def foo(self):\n pass\n\n @dataclass\n class Date(A):\n year: int\n month: 'Month'\n day: 'int'\n\n self.assertTrue(inspect.isabstract(Date))\n msg = \"class Date without an implementation for abstract method 'foo'\"\n self.assertRaisesRegex(TypeError, msg, Date)\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestAbstract","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_30.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestMatchArgs(unittest.TestCase):\n def test_match_args(self):\n @dataclass\n class C:\n a: int\n self.assertEqual(C(42).__match_args__, ('a',))\n\n def test_explicit_match_args(self):\n ma = ()\n @dataclass\n class C:\n a: int\n __match_args__ = ma\n self.assertIs(C(42).__match_args__, ma)\n\n def test_bpo_43764(self):\n @dataclass(repr=False, eq=False, init=False)\n class X:\n a: int\n b: int\n c: int\n self.assertEqual(X.__match_args__, (\"a\", \"b\", \"c\"))\n\n def test_match_args_argument(self):\n @dataclass(match_args=False)\n class X:\n a: int\n self.assertNotIn('__match_args__', X.__dict__)\n\n @dataclass(match_args=False)\n class Y:\n a: int\n __match_args__ = ('b',)\n self.assertEqual(Y.__match_args__, ('b',))\n\n @dataclass(match_args=False)\n class Z(Y):\n z: int\n self.assertEqual(Z.__match_args__, ('b',))\n\n # Ensure parent dataclass __match_args__ is seen, if child class\n # specifies match_args=False.\n @dataclass\n class A:\n a: int\n z: int\n @dataclass(match_args=False)\n class B(A):\n b: int\n self.assertEqual(B.__match_args__, ('a', 'z'))\n\n def test_make_dataclasses(self):\n C = make_dataclass('C', [('x', int), ('y', int)])\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=True)\n self.assertEqual(C.__match_args__, ('x', 'y'))\n\n C = make_dataclass('C', [('x', int), ('y', int)], match_args=False)\n self.assertNotIn('__match__args__', C.__dict__)\n\n C = make_dataclass('C', [('x', int), ('y', int)], namespace={'__match_args__': ('z',)})\n self.assertEqual(C.__match_args__, ('z',))\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestMatchArgs","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dataclasses","pep":"557","introduced_in":"3.7","form":"modern","file":"dataclasses/modern_31.py","code":"from dataclasses import *\nimport abc\nimport annotationlib\nimport io\nimport pickle\nimport inspect\nimport builtins\nimport types\nimport weakref\nimport traceback\nimport sys\nimport textwrap\nimport unittest\nfrom unittest.mock import Mock\nfrom typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict\nfrom typing import get_type_hints\nfrom collections import deque, OrderedDict, namedtuple, defaultdict\nfrom copy import deepcopy\nfrom functools import total_ordering, wraps\nimport typing\nimport dataclasses\nfrom test import support\nfrom test.support import cpython_only, import_helper\n\n\nclass TestKeywordArgs(unittest.TestCase):\n def test_no_classvar_kwarg(self):\n msg = 'field a is a ClassVar but specifies kw_only'\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=True)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass(kw_only=True)\n class A:\n a: ClassVar[int] = field(kw_only=False)\n\n def test_field_marked_as_kwonly(self):\n #######################\n # Using dataclass(kw_only=True)\n @dataclass(kw_only=True)\n class A:\n a: int\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=True)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Using dataclass(kw_only=False)\n @dataclass(kw_only=False)\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass(kw_only=False)\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n #######################\n # Not specifying dataclass(kw_only)\n @dataclass\n class A:\n a: int\n self.assertFalse(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n @dataclass\n class A:\n a: int = field(kw_only=False)\n self.assertFalse(fields(A)[0].kw_only)\n\n def test_match_args(self):\n # kw fields don't show up in __match_args__.\n @dataclass(kw_only=True)\n class C:\n a: int\n self.assertEqual(C(a=42).__match_args__, ())\n\n @dataclass\n class C:\n a: int\n b: int = field(kw_only=True)\n self.assertEqual(C(42, b=10).__match_args__, ('a',))\n\n def test_KW_ONLY(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n\n @dataclass(kw_only=True)\n class B:\n a: int\n _: KW_ONLY\n b: int\n c: int\n B(a=3, b=4, c=5)\n msg = \"takes 1 positional argument but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n B(3, 4, 5)\n\n # Explicitly make a field that follows KW_ONLY be non-keyword-only.\n @dataclass\n class C:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=False)\n c = C(1, 2, b=3)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(1, b=3, c=2)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n c = C(c=2, b=3, a=1)\n self.assertEqual(c.a, 1)\n self.assertEqual(c.b, 3)\n self.assertEqual(c.c, 2)\n\n def test_KW_ONLY_as_string(self):\n @dataclass\n class A:\n a: int\n _: 'dataclasses.KW_ONLY'\n b: int\n c: int\n A(3, c=5, b=4)\n msg = \"takes 2 positional arguments but 4 were given\"\n with self.assertRaisesRegex(TypeError, msg):\n A(3, 4, 5)\n\n def test_KW_ONLY_twice(self):\n msg = \"'Y' is KW_ONLY, but KW_ONLY has already been specified\"\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n Y: KW_ONLY\n b: int\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n Y: KW_ONLY\n c: int\n\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n X: KW_ONLY\n b: int\n c: int\n Y: KW_ONLY\n\n # But this usage is okay, since it's not using KW_ONLY.\n @dataclass\n class NoDuplicateKwOnlyAnnotation:\n a: int\n _: KW_ONLY\n b: int\n c: int = field(kw_only=True)\n\n # And if inheriting, it's okay.\n @dataclass\n class BaseUsesKwOnly:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class SubclassUsesKwOnly(BaseUsesKwOnly):\n _: KW_ONLY\n d: int\n\n # Make sure the error is raised in a derived class.\n with self.assertRaisesRegex(TypeError, msg):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: int\n c: int\n @dataclass\n class B(A):\n X: KW_ONLY\n d: int\n Y: KW_ONLY\n\n\n def test_post_init(self):\n @dataclass\n class A:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n raise CustomError(f'{b=} {d=}')\n with self.assertRaisesRegex(CustomError, 'b=3 d=4'):\n A(1, c=2, b=3, d=4)\n\n @dataclass\n class B:\n a: int\n _: KW_ONLY\n b: InitVar[int]\n c: int\n d: InitVar[int]\n def __post_init__(self, b, d):\n self.a = b\n self.c = d\n b = B(1, c=2, b=3, d=4)\n self.assertEqual(asdict(b), {'a': 3, 'c': 4})\n\n def test_defaults(self):\n # For kwargs, make sure we can have defaults after non-defaults.\n @dataclass\n class A:\n a: int = 0\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n a = A(d=4, b=3)\n self.assertEqual(a.a, 0)\n self.assertEqual(a.b, 3)\n self.assertEqual(a.c, 1)\n self.assertEqual(a.d, 4)\n\n # Make sure we still check for non-kwarg non-defaults not following\n # defaults.\n err_regex = \"non-default argument 'z' follows default argument 'a'\"\n with self.assertRaisesRegex(TypeError, err_regex):\n @dataclass\n class A:\n a: int = 0\n z: int\n _: KW_ONLY\n b: int\n c: int = 1\n d: int\n\n def test_make_dataclass(self):\n A = make_dataclass(\"A\", ['a'], kw_only=True)\n self.assertTrue(fields(A)[0].kw_only)\n\n B = make_dataclass(\"B\",\n ['a', ('b', int, field(kw_only=False))],\n kw_only=True)\n self.assertTrue(fields(B)[0].kw_only)\n self.assertFalse(fields(B)[1].kw_only)\n\n def test_deferred_annotations(self):\n @dataclass\n class A:\n x: undefined\n y: ClassVar[undefined]\n\n fs = fields(A)\n self.assertEqual(len(fs), 1)\n self.assertEqual(fs[0].name, 'x')\n","source":"cpython_tests","origin":"Lib/test/test_dataclasses/__init__.py::TestKeywordArgs","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"dict-union","pep":"584","introduced_in":"3.9","form":"modern","file":"dict-union/modern_01.py","code":"import collections\nimport collections.abc\nimport gc\nimport pickle\nimport random\nimport re\nimport string\nimport sys\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import import_helper\nfrom test import mapping_tests\n\n\ndef test_merge_operator(self):\n\n a = {0: 0, 1: 1, 2: 1}\n b = {1: 1, 2: 2, 3: 3}\n\n c = a.copy()\n c |= b\n\n self.assertEqual(a | b, {0: 0, 1: 1, 2: 2, 3: 3})\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n c = b.copy()\n c |= a\n\n self.assertEqual(b | a, {1: 1, 2: 1, 3: 3, 0: 0})\n self.assertEqual(c, {1: 1, 2: 1, 3: 3, 0: 0})\n\n c = a.copy()\n c |= [(1, 1), (2, 2), (3, 3)]\n\n self.assertEqual(c, {0: 0, 1: 1, 2: 2, 3: 3})\n\n self.assertIs(a.__or__(None), NotImplemented)\n self.assertIs(a.__or__(()), NotImplemented)\n self.assertIs(a.__or__(\"BAD\"), NotImplemented)\n self.assertIs(a.__or__(\"\"), NotImplemented)\n\n self.assertRaises(TypeError, a.__ior__, None)\n self.assertEqual(a.__ior__(()), {0: 0, 1: 1, 2: 1})\n self.assertRaises(ValueError, a.__ior__, \"BAD\")\n self.assertEqual(a.__ior__(\"\"), {0: 0, 1: 1, 2: 1})\n","source":"cpython_tests","origin":"Lib/test/test_dict.py::DictTest.test_merge_operator","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"exception-notes","pep":"678","introduced_in":"3.11","form":"modern","file":"exception-notes/modern_01.py","code":"import copy\nimport os\nimport sys\nimport unittest\nimport pickle\nimport weakref\nimport errno\nfrom codecs import BOM_UTF8\nfrom itertools import product\nfrom textwrap import dedent\nfrom test.support import (captured_stderr, check_impl_detail,\n cpython_only, gc_collect,\n no_tracing, script_helper,\n SuppressCrashReport,\n force_not_colorized)\nfrom test.support.import_helper import import_module\nfrom test.support.os_helper import TESTFN, unlink\nfrom test.support.warnings_helper import check_warnings\nfrom test import support\n\n\ndef test_notes(self):\n for e in [BaseException(1), Exception(2), ValueError(3)]:\n with self.subTest(e=e):\n self.assertNotHasAttr(e, '__notes__')\n e.add_note(\"My Note\")\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n with self.assertRaises(TypeError):\n e.add_note(42)\n self.assertEqual(e.__notes__, [\"My Note\"])\n\n e.add_note(\"Your Note\")\n self.assertEqual(e.__notes__, [\"My Note\", \"Your Note\"])\n\n del e.__notes__\n self.assertNotHasAttr(e, '__notes__')\n\n e.add_note(\"Our Note\")\n self.assertEqual(e.__notes__, [\"Our Note\"])\n\n e.__notes__ = 42\n self.assertEqual(e.__notes__, 42)\n\n with self.assertRaises(TypeError):\n e.add_note(\"will not work\")\n self.assertEqual(e.__notes__, 42)\n","source":"cpython_tests","origin":"Lib/test/test_exceptions.py::ExceptionTests.test_notes","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"frozendict","pep":"814","introduced_in":"3.15","form":"modern","file":"frozendict/modern_01.py","code":"import collections\nimport collections.abc\nimport gc\nimport pickle\nimport random\nimport re\nimport string\nimport sys\nimport unittest\nimport weakref\nfrom test import support\nfrom test.support import import_helper\nfrom test import mapping_tests\n\n\nclass FrozenDictTests(unittest.TestCase):\n def test_constructor(self):\n # frozendict.__init__() has no effect\n d = frozendict(a=1, b=2, c=3)\n d.__init__(x=1)\n self.assertEqual(d, frozendict(a=1, b=2, c=3))\n\n # dict constructor cannot be used on frozendict\n with self.assertRaises(TypeError):\n dict.__init__(d, x=1)\n\n # Avoid copy if it's frozendict type\n d2 = frozendict(d)\n self.assertIs(d2, d)\n d2 = FrozenDict(d)\n self.assertIsNot(d2, d)\n self.assertEqual(d2, d)\n\n def test_copy(self):\n d = frozendict(x=1, y=2)\n d2 = d.copy()\n self.assertIs(d2, d)\n\n d = FrozenDict(x=1, y=2)\n d2 = d.copy()\n self.assertIsNot(d2, d)\n self.assertEqual(d2, frozendict(x=1, y=2))\n self.assertEqual(type(d2), frozendict)\n\n def test_merge(self):\n # test \"a | b\" operator\n self.assertEqual(frozendict(x=1) | frozendict(y=2),\n frozendict({'x': 1, 'y': 2}))\n self.assertEqual(frozendict(x=1) | dict(y=2),\n frozendict({'x': 1, 'y': 2}))\n self.assertEqual(frozendict(x=1, y=2) | frozendict(y=5),\n frozendict({'x': 1, 'y': 5}))\n self.assertEqual(FrozenDict(x=1, y=2) | FrozenDict(y=5),\n frozendict({'x': 1, 'y': 5}))\n\n fd = frozendict(x=1, y=2)\n self.assertIs(fd | frozendict(), fd)\n self.assertIs(fd | {}, fd)\n self.assertIs(frozendict() | fd, fd)\n\n fd = FrozenDict(x=1, y=2)\n self.assertEqual(fd | frozendict(), fd)\n self.assertEqual(fd | {}, fd)\n self.assertEqual(frozendict() | fd, fd)\n\n # gh-149676: Test hash(frozendict | frozendict)\n a = frozendict({\"a\": 1})\n b = frozendict({\"b\": 2})\n self.assertEqual(hash(a | b), hash(frozendict({\"a\": 1, \"b\": 2})))\n\n def test_update(self):\n # test \"a |= b\" operator\n d = frozendict(x=1)\n copy = d\n self.assertIs(copy, d)\n d |= frozendict(y=2)\n self.assertIsNot(copy, d)\n self.assertEqual(d, frozendict({'x': 1, 'y': 2}))\n self.assertEqual(copy, frozendict({'x': 1}))\n\n def test_items_xor(self):\n # test \"a ^ b\" operator on items views\n res = frozendict(a=1, b=2).items() ^ frozendict(b=2, c=3).items()\n self.assertEqual(res, {('a', 1), ('c', 3)})\n\n def test_repr(self):\n d = frozendict()\n self.assertEqual(repr(d), \"frozendict()\")\n\n d = frozendict(x=1, y=2)\n self.assertEqual(repr(d), \"frozendict({'x': 1, 'y': 2})\")\n\n d = FrozenDict(x=1, y=2)\n self.assertEqual(repr(d), \"FrozenDict({'x': 1, 'y': 2})\")\n\n def test_hash(self):\n # hash() doesn't rely on the items order\n self.assertEqual(hash(frozendict(x=1, y=2)),\n hash(frozendict(y=2, x=1)))\n\n # Check that hash() computes the hash of (key, value) pairs\n cases = [\n frozendict(a=False, b=True, c=True),\n frozendict(a=True, b=False, c=True),\n frozendict(a=True, b=True, c=False),\n frozendict({False: \"a\", \"b\": True, \"c\": True}),\n frozendict({\"a\": \"b\", False: True, True: \"c\"}),\n ]\n hashes = {hash(fd) for fd in cases}\n self.assertEqual(len(hashes), len(cases))\n\n fd = frozendict(x=[1], y=[2])\n with self.assertRaisesRegex(TypeError, \"unhashable type: 'list'\"):\n hash(fd)\n\n @support.cpython_only\n def test_hash_cpython(self):\n # Check that hash(frozendict) implementation is:\n # hash(frozenset(fd.items()))\n for fd in (\n frozendict(),\n frozendict(x=1, y=2),\n frozendict(y=2, x=1),\n frozendict(a=False, b=True, c=True),\n frozendict.fromkeys('abc'),\n ):\n with self.subTest(fd=fd):\n self.assertEqual(hash(fd), hash(frozenset(fd.items())))\n\n def test_fromkeys(self):\n self.assertEqual(frozendict.fromkeys('abc'),\n frozendict(a=None, b=None, c=None))\n\n # Subclass which overrides the constructor\n created = frozendict(x=1)\n class FrozenDictSubclass(frozendict):\n def __new__(cls, *args, **kwargs):\n if args or kwargs:\n return super().__new__(cls, *args, **kwargs)\n else:\n return created\n\n fd = FrozenDictSubclass.fromkeys(\"abc\")\n self.assertEqual(fd, frozendict(x=1, a=None, b=None, c=None))\n self.assertEqual(type(fd), FrozenDictSubclass)\n self.assertEqual(created, frozendict(x=1))\n\n fd = FrozenDictSubclass.fromkeys(frozendict(y=2))\n self.assertEqual(fd, frozendict(x=1, y=None))\n self.assertEqual(type(fd), FrozenDictSubclass)\n self.assertEqual(created, frozendict(x=1))\n\n # Dict subclass with a constructor which returns a frozendict\n # by default\n class DictSubclass(dict):\n def __new__(cls, *args, **kwargs):\n if args or kwargs:\n return super().__new__(cls, *args, **kwargs)\n else:\n return created\n\n fd = DictSubclass.fromkeys(\"abc\")\n self.assertEqual(fd, frozendict(x=1, a=None, b=None, c=None))\n self.assertEqual(type(fd), DictSubclass)\n self.assertEqual(created, frozendict(x=1))\n\n # Subclass which doesn't override the constructor\n class FrozenDictSubclass2(frozendict):\n pass\n\n fd = FrozenDictSubclass2.fromkeys(\"abc\")\n self.assertEqual(fd, frozendict(a=None, b=None, c=None))\n self.assertEqual(type(fd), FrozenDictSubclass2)\n\n def test_pickle(self):\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n for fd in (\n frozendict(),\n frozendict(x=1, y=2),\n FrozenDict(x=1, y=2),\n FrozenDictSlots(x=1, y=2),\n ):\n if type(fd) == FrozenDict:\n fd.attr = 123\n if type(fd) == FrozenDictSlots:\n fd.slot_attr = 456\n with self.subTest(fd=fd, proto=proto):\n if proto >= 2:\n p = pickle.dumps(fd, proto)\n fd2 = pickle.loads(p)\n self.assertEqual(fd2, fd)\n self.assertEqual(type(fd2), type(fd))\n if type(fd) == FrozenDict:\n self.assertEqual(fd2.attr, 123)\n if type(fd) == FrozenDictSlots:\n self.assertEqual(fd2.slot_attr, 456)\n else:\n # protocol 0 and 1 don't support frozendict\n with self.assertRaises(TypeError):\n pickle.dumps(fd, proto)\n\n def test_pickle_iter(self):\n fd = frozendict(c=1, b=2, a=3, d=4, e=5, f=6)\n for method_name in (None, 'keys', 'values', 'items'):\n if method_name is not None:\n meth = getattr(fd, method_name)\n else:\n meth = lambda: fd\n expected = list(meth())[1:]\n for proto in range(pickle.HIGHEST_PROTOCOL + 1):\n with self.subTest(method_name=method_name, protocol=proto):\n it = iter(meth())\n next(it)\n p = pickle.dumps(it, proto)\n unpickled = pickle.loads(p)\n self.assertEqual(list(unpickled), expected)\n self.assertEqual(list(it), expected)\n\n def test_unhashable_key(self):\n d = frozendict(a=1)\n key = [1, 2, 3]\n\n def check_unhashable_key():\n msg = \"cannot use 'list' as a frozendict key (unhashable type: 'list')\"\n return self.assertRaisesRegex(TypeError, re.escape(msg))\n\n with check_unhashable_key():\n key in d\n with check_unhashable_key():\n d[key]\n with check_unhashable_key():\n d.get(key)\n\n # Only TypeError exception is overridden,\n # other exceptions are left unchanged.\n class HashError:\n def __hash__(self):\n raise KeyError('error')\n\n key2 = HashError()\n with self.assertRaises(KeyError):\n key2 in d\n with self.assertRaises(KeyError):\n d[key2]\n with self.assertRaises(KeyError):\n d.get(key2)\n","source":"cpython_tests","origin":"Lib/test/test_dict.py::FrozenDictTests","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"numeric-underscores","pep":"515","introduced_in":"3.6","form":"modern","file":"numeric-underscores/modern_01.py","code":"import sys\nimport unittest\nfrom unittest import mock\nfrom test import support\nfrom test.support.numbers import (\n VALID_UNDERSCORE_LITERALS,\n INVALID_UNDERSCORE_LITERALS,\n)\n\n\nclass IntStrDigitLimitsTests(unittest.TestCase):\n\n int_class = int # Override this in subclasses to reuse the suite.\n\n def setUp(self):\n super().setUp()\n self._previous_limit = sys.get_int_max_str_digits()\n sys.set_int_max_str_digits(2048)\n\n def tearDown(self):\n sys.set_int_max_str_digits(self._previous_limit)\n super().tearDown()\n\n def test_disabled_limit(self):\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n self.assertLess(sys.get_int_max_str_digits(), 20_000)\n with support.adjust_int_max_str_digits(0):\n self.assertEqual(sys.get_int_max_str_digits(), 0)\n i = self.int_class('1' * 20_000)\n str(i)\n self.assertGreater(sys.get_int_max_str_digits(), 0)\n\n def test_max_str_digits_edge_cases(self):\n \"\"\"Ignore the +/- sign and space padding.\"\"\"\n int_class = self.int_class\n maxdigits = sys.get_int_max_str_digits()\n\n int_class('1' * maxdigits)\n int_class(' ' + '1' * maxdigits)\n int_class('1' * maxdigits + ' ')\n int_class('+' + '1' * maxdigits)\n int_class('-' + '1' * maxdigits)\n self.assertEqual(len(str(10 ** (maxdigits - 1))), maxdigits)\n\n def check(self, i, base=None):\n with self.assertRaises(ValueError):\n if base is None:\n self.int_class(i)\n else:\n self.int_class(i, base)\n\n def test_max_str_digits(self):\n maxdigits = sys.get_int_max_str_digits()\n\n self.check('1' * (maxdigits + 1))\n self.check(' ' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1) + ' ')\n self.check('+' + '1' * (maxdigits + 1))\n self.check('-' + '1' * (maxdigits + 1))\n self.check('1' * (maxdigits + 1))\n\n i = 10 ** maxdigits\n with self.assertRaises(ValueError):\n str(i)\n\n def test_denial_of_service_prevented_int_to_str(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 50_000, maxdigits # A test prerequisite.\n\n huge_int = int(f'0x{\"c\"*65_000}', base=16) # 78268 decimal digits.\n digits = 78_268\n with (\n support.adjust_int_max_str_digits(digits),\n support.Stopwatch() as sw_convert):\n huge_decimal = str(huge_int)\n self.assertEqual(len(huge_decimal), digits)\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if sw_convert.seconds < sw_convert.clock_info.resolution * 2:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{sw_convert.seconds} seconds.')\n\n # We test with the limit almost at the size needed to check performance.\n # The performant limit check is slightly fuzzy, give it a some room.\n with support.adjust_int_max_str_digits(int(.995 * digits)):\n with (\n self.assertRaises(ValueError) as err,\n support.Stopwatch() as sw_fail_huge):\n str(huge_int)\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(sw_fail_huge.seconds, sw_convert.seconds/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge_int = int(f'0x{\"c\"*500_000}', base=16) # 602060 digits.\n with (\n self.assertRaises(ValueError) as err,\n support.Stopwatch() as sw_fail_extra_huge):\n # If not limited, 8 seconds said Zen based cloud VM.\n str(extra_huge_int)\n self.assertIn('conversion', str(err.exception))\n self.assertLess(sw_fail_extra_huge.seconds, sw_convert.seconds/2)\n\n def test_denial_of_service_prevented_str_to_int(self):\n \"\"\"Regression test: ensure we fail before performing O(N**2) work.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n assert maxdigits < 100_000, maxdigits # A test prerequisite.\n\n digits = 133700\n huge = '8'*digits\n with (\n support.adjust_int_max_str_digits(digits),\n support.Stopwatch() as sw_convert):\n int(huge)\n # Ensuring that we chose a slow enough conversion to measure.\n # It takes 0.1 seconds on a Zen based cloud VM in an opt build.\n # Some OSes have a low res 1/64s timer, skip if hard to measure.\n if sw_convert.seconds < sw_convert.clock_info.resolution * 2:\n raise unittest.SkipTest('\"slow\" conversion took only '\n f'{sw_convert.seconds} seconds.')\n\n with support.adjust_int_max_str_digits(digits - 1):\n with (\n self.assertRaises(ValueError) as err,\n support.Stopwatch() as sw_fail_huge):\n int(huge)\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(sw_fail_huge.seconds, sw_convert.seconds/2)\n\n # Now we test that a conversion that would take 30x as long also fails\n # in a similarly fast fashion.\n extra_huge = '7'*1_200_000\n with (\n self.assertRaises(ValueError) as err,\n support.Stopwatch() as sw_fail_extra_huge):\n # If not limited, 8 seconds in the Zen based cloud VM.\n int(extra_huge)\n self.assertIn('conversion', str(err.exception))\n self.assertLessEqual(sw_fail_extra_huge.seconds, sw_convert.seconds/2)\n\n def test_power_of_two_bases_unlimited(self):\n \"\"\"The limit does not apply to power of 2 bases.\"\"\"\n maxdigits = sys.get_int_max_str_digits()\n\n for base in (2, 4, 8, 16, 32):\n with self.subTest(base=base):\n self.int_class('1' * (maxdigits + 1), base)\n assert maxdigits < 100_000\n self.int_class('1' * 100_000, base)\n\n def test_underscores_ignored(self):\n maxdigits = sys.get_int_max_str_digits()\n\n triples = maxdigits // 3\n s = '111' * triples\n s_ = '1_11' * triples\n self.int_class(s) # succeeds\n self.int_class(s_) # succeeds\n self.check(f'{s}111')\n self.check(f'{s_}_111')\n\n def test_sign_not_counted(self):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '5' * max_digits\n i = int_class(s)\n pos_i = int_class(f'+{s}')\n assert i == pos_i\n neg_i = int_class(f'-{s}')\n assert -pos_i == neg_i\n str(pos_i)\n str(neg_i)\n\n def _other_base_helper(self, base):\n int_class = self.int_class\n max_digits = sys.get_int_max_str_digits()\n s = '2' * max_digits\n i = int_class(s, base)\n if base > 10:\n with self.assertRaises(ValueError):\n str(i)\n elif base < 10:\n str(i)\n with self.assertRaises(ValueError) as err:\n int_class(f'{s}1', base)\n\n def test_int_from_other_bases(self):\n base = 3\n with self.subTest(base=base):\n self._other_base_helper(base)\n base = 36\n with self.subTest(base=base):\n self._other_base_helper(base)\n\n def test_int_max_str_digits_is_per_interpreter(self):\n # Changing the limit in one interpreter does not change others.\n code = \"\"\"if 1:\n # Subinterpreters maintain and enforce their own limit\n import sys\n sys.set_int_max_str_digits(2323)\n try:\n int('3'*3333)\n except ValueError:\n pass\n else:\n raise AssertionError('Expected a int max str digits ValueError.')\n \"\"\"\n with support.adjust_int_max_str_digits(4000):\n before_value = sys.get_int_max_str_digits()\n self.assertEqual(support.run_in_subinterp(code), 0,\n 'subinterp code failure, check stderr.')\n after_value = sys.get_int_max_str_digits()\n self.assertEqual(before_value, after_value)\n","source":"cpython_tests","origin":"Lib/test/test_int.py::IntStrDigitLimitsTests","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"numeric-underscores","pep":"515","introduced_in":"3.6","form":"modern","file":"numeric-underscores/modern_02.py","code":"import sys\nimport unittest\nfrom unittest import mock\nfrom test import support\nfrom test.support.numbers import (\n VALID_UNDERSCORE_LITERALS,\n INVALID_UNDERSCORE_LITERALS,\n)\n\n\nclass PyLongModuleTests(unittest.TestCase):\n # Tests of the functions in _pylong.py. Those get used when the\n # number of digits in the input values are large enough.\n\n def setUp(self):\n super().setUp()\n self._previous_limit = sys.get_int_max_str_digits()\n sys.set_int_max_str_digits(0)\n\n def tearDown(self):\n sys.set_int_max_str_digits(self._previous_limit)\n super().tearDown()\n\n def _test_pylong_int_to_decimal(self, n, suffix):\n s = str(n)\n self.assertEqual(s[-10:], suffix)\n s2 = str(-n)\n self.assertEqual(s2, '-' + s)\n s3 = '%d' % n\n self.assertEqual(s3, s)\n s4 = b'%d' % n\n self.assertEqual(s4, s.encode('ascii'))\n\n def test_pylong_int_to_decimal(self):\n self._test_pylong_int_to_decimal((1 << 100_000), '9883109376')\n self._test_pylong_int_to_decimal((1 << 100_000) - 1, '9883109375')\n self._test_pylong_int_to_decimal(10**30_000, '0000000000')\n self._test_pylong_int_to_decimal(10**30_000 - 1, '9999999999')\n self._test_pylong_int_to_decimal(3**60_000, '9313200001')\n\n @support.requires_resource('cpu')\n def test_pylong_int_to_decimal_2(self):\n self._test_pylong_int_to_decimal(2**1_000_000, '2747109376')\n self._test_pylong_int_to_decimal(10**300_000, '0000000000')\n self._test_pylong_int_to_decimal(3**600_000, '3132000001')\n\n def test_pylong_int_divmod(self):\n n = (1 << 100_000)\n a, b = divmod(n*3 + 1, n)\n assert a == 3 and b == 1\n\n @support.cpython_only # tests implementation details of CPython.\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n def test_pylong_int_divmod_crash(self):\n # Regression test for https://github.com/python/cpython/issues/142554.\n bad_int_divmod = lambda a, b: (1,)\n # 'k' chosen such that divmod(2**(2*k), 2**k) uses _pylong.int_divmod()\n k = 10_000\n a, b = (1 << (2 * k)), (1 << k)\n with mock.patch.object(_pylong, \"int_divmod\", wraps=bad_int_divmod):\n msg = r\"tuple of length 2 is required from int_divmod\\(\\)\"\n self.assertRaisesRegex(ValueError, msg, divmod, a, b)\n\n def test_pylong_str_to_int(self):\n v1 = 1 << 100_000\n s = str(v1)\n v2 = int(s)\n assert v1 == v2\n v3 = int(' -' + s)\n assert -v1 == v3\n v4 = int(' +' + s + ' ')\n assert v1 == v4\n with self.assertRaises(ValueError) as err:\n int(s + 'z')\n with self.assertRaises(ValueError) as err:\n int(s + '_')\n with self.assertRaises(ValueError) as err:\n int('_' + s)\n\n @support.cpython_only # tests implementation details of CPython.\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @mock.patch.object(_pylong, \"int_to_decimal_string\")\n def test_pylong_misbehavior_error_path_to_str(\n self, mock_int_to_str):\n with support.adjust_int_max_str_digits(20_000):\n big_value = int('7'*19_999)\n mock_int_to_str.return_value = None # not a str\n with self.assertRaises(TypeError) as ctx:\n str(big_value)\n self.assertIn('_pylong.int_to_decimal_string did not',\n str(ctx.exception))\n mock_int_to_str.side_effect = RuntimeError(\"testABC\")\n with self.assertRaises(RuntimeError):\n str(big_value)\n\n @support.cpython_only # tests implementation details of CPython.\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @mock.patch.object(_pylong, \"int_from_string\")\n def test_pylong_misbehavior_error_path_from_str(\n self, mock_int_from_str):\n big_value = '7'*19_999\n with support.adjust_int_max_str_digits(20_000):\n mock_int_from_str.return_value = b'not an int'\n with self.assertRaises(TypeError) as ctx:\n int(big_value)\n self.assertIn('_pylong.int_from_string did not',\n str(ctx.exception))\n\n mock_int_from_str.side_effect = RuntimeError(\"test123\")\n with self.assertRaises(RuntimeError):\n int(big_value)\n\n def test_pylong_roundtrip(self):\n from random import randrange, getrandbits\n bits = 5000\n while bits <= 1_000_000:\n bits += randrange(-100, 101) # break bitlength patterns\n hibit = 1 << (bits - 1)\n n = hibit | getrandbits(bits - 1)\n assert n.bit_length() == bits\n sn = str(n)\n self.assertNotStartsWith(sn, '0')\n self.assertEqual(n, int(sn))\n bits <<= 1\n\n @support.requires_resource('cpu')\n @unittest.skipUnless(_decimal, \"C _decimal module required\")\n def test_pylong_roundtrip_huge(self):\n # k blocks of 1234567890\n k = 1_000_000 # so 10 million digits in all\n tentoten = 10**10\n n = 1234567890 * ((tentoten**k - 1) // (tentoten - 1))\n sn = \"1234567890\" * k\n self.assertEqual(n, int(sn))\n self.assertEqual(sn, str(n))\n\n @support.requires_resource('cpu')\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n @unittest.skipUnless(_decimal, \"C _decimal module required\")\n def test_whitebox_dec_str_to_int_inner_failsafe(self):\n # While I believe the number of GUARD digits in this function is\n # always enough so that no more than one correction step is ever\n # needed, the code has a \"failsafe\" path that takes over if I'm\n # wrong about that. We have no input that reaches that block.\n # Here we test a contrived input that _does_ reach that block,\n # provided the number of guard digits is reduced to 1.\n sn = \"9\" * 2000156\n n = 10**len(sn) - 1\n orig_spread = _pylong._spread.copy()\n _pylong._spread.clear()\n try:\n self.assertEqual(n, _pylong._dec_str_to_int_inner(sn, GUARD=1))\n self.assertIn(999, _pylong._spread)\n finally:\n _pylong._spread.clear()\n _pylong._spread.update(orig_spread)\n\n @unittest.skipUnless(_pylong, \"pylong module required\")\n @unittest.skipUnless(_decimal, \"C _decimal module required\")\n def test_whitebox_dec_str_to_int_inner_monster(self):\n # I don't think anyone has enough RAM to build a string long enough\n # for this function to complain. So lie about the string length.\n\n class LyingStr(str):\n def __len__(self):\n return int((1 << 47) / _pylong._LOG_10_BASE_256)\n\n liar = LyingStr(\"42\")\n # We have to pass the liar directly to the complaining function. If we\n # just try `int(liar)`, earlier layers will replace it with plain old\n # \"43\".\n # Embedding `len(liar)` into the f-string failed on the WASI testbot\n # (don't know what that is):\n # OverflowError: cannot fit 'int' into an index-sized integer\n # So a random stab at worming around that.\n self.assertRaisesRegex(ValueError,\n f\"^cannot convert string of len {liar.__len__()} to int$\",\n _pylong._dec_str_to_int_inner,\n liar)\n\n @unittest.skipUnless(_pylong, \"_pylong module required\")\n def test_pylong_compute_powers(self):\n # Basic sanity tests. See end of _pylong.py for manual heavy tests.\n def consumer(w, base, limit, need_hi):\n seen = set()\n need = set()\n def inner(w):\n if w <= limit or w in seen:\n return\n seen.add(w)\n lo = w >> 1\n hi = w - lo\n need.add(hi if need_hi else lo)\n inner(lo)\n inner(hi)\n inner(w)\n d = _pylong.compute_powers(w, base, limit, need_hi=need_hi)\n self.assertEqual(d.keys(), need)\n for k, v in d.items():\n self.assertEqual(v, base ** k)\n\n for base in 2, 5:\n for need_hi in False, True:\n for limit in 1, 11:\n for w in range(250, 550):\n consumer(w, base, limit, need_hi)\n","source":"cpython_tests","origin":"Lib/test/test_int.py::PyLongModuleTests","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"tarfile-filter","pep":"706","introduced_in":"3.12","form":"modern","file":"tarfile-filter/modern_01.py","code":"import errno\nimport sys\nimport os\nimport io\nfrom hashlib import sha256\nfrom contextlib import contextmanager, ExitStack\nfrom random import Random\nimport pathlib\nimport shutil\nimport re\nimport warnings\nimport stat\nimport time\nimport unittest\nimport unittest.mock\nimport tarfile\nfrom test import archiver_tests\nfrom test import support\nfrom test.support import os_helper\nfrom test.support import script_helper\nfrom test.support import warnings_helper\n\n\nclass TestExtractionFilters(unittest.TestCase):\n\n # A temporary directory for the extraction results.\n # All files that \"escape\" the destination path should still end\n # up in this directory.\n outerdir = pathlib.Path(TEMPDIR) / 'outerdir'\n\n # The destination for the extraction, within `outerdir`\n destdir = outerdir / 'dest'\n\n @classmethod\n def setUpClass(cls):\n # Posix and Windows have different pathname resolution:\n # either symlink or a '..' component resolve first.\n # Let's see which we are on.\n if os_helper.can_symlink():\n testpath = os.path.join(TEMPDIR, 'resolution_test')\n os.mkdir(testpath)\n\n # testpath/current links to `.` which is all of:\n # - `testpath`\n # - `testpath/current`\n # - `testpath/current/current`\n # - etc.\n os.symlink('.', os.path.join(testpath, 'current'))\n\n # we'll test where `testpath/current/../file` ends up\n with open(os.path.join(testpath, 'current', '..', 'file'), 'w'):\n pass\n\n if os.path.exists(os.path.join(testpath, 'file')):\n # Windows collapses 'current\\..' to '.' first, leaving\n # 'testpath\\file'\n cls.dotdot_resolves_early = True\n elif os.path.exists(os.path.join(testpath, '..', 'file')):\n # Posix resolves 'current' to '.' first, leaving\n # 'testpath/../file'\n cls.dotdot_resolves_early = False\n else:\n raise AssertionError('Could not determine link resolution')\n else:\n cls.dotdot_resolves_early = False\n\n @contextmanager\n def check_context(self, tar, filter, *, check_flag=True):\n \"\"\"Extracts `tar` to `self.destdir` and allows checking the result\n\n If an error occurs, it must be checked using `expect_exception`\n\n Otherwise, all resulting files must be checked using `expect_file`,\n except the destination directory itself and parent directories of\n other files.\n When checking directories, do so before their contents.\n\n A file called 'flag' is made in outerdir (i.e. outside destdir)\n before extraction; it should not be altered nor should its contents\n be read/copied.\n \"\"\"\n with os_helper.temp_dir(self.outerdir):\n flag_path = self.outerdir / 'flag'\n flag_path.write_text('capture me')\n try:\n tar.extractall(self.destdir, filter=filter)\n except Exception as exc:\n self.raised_exception = exc\n self.reraise_exception = True\n self.expected_paths = set()\n else:\n self.raised_exception = None\n self.reraise_exception = False\n self.expected_paths = set(self.outerdir.glob('**/*'))\n self.expected_paths.discard(self.destdir)\n self.expected_paths.discard(flag_path)\n try:\n yield self\n finally:\n tar.close()\n if self.reraise_exception:\n raise self.raised_exception\n self.assertEqual(self.expected_paths, set())\n if check_flag:\n self.assertEqual(flag_path.read_text(), 'capture me')\n else:\n assert filter == 'fully_trusted'\n\n def expect_file(self, name, type=None, symlink_to=None, mode=None,\n size=None, content=None):\n \"\"\"Check a single file. See check_context.\"\"\"\n if self.raised_exception:\n raise self.raised_exception\n # use normpath() rather than resolve() so we don't follow symlinks\n path = pathlib.Path(os.path.normpath(self.destdir / name))\n self.assertIn(path, self.expected_paths)\n self.expected_paths.remove(path)\n if mode is not None and os_helper.can_chmod() and os.name != 'nt':\n got = stat.filemode(stat.S_IMODE(path.stat().st_mode))\n self.assertEqual(got, mode)\n if type is None and isinstance(name, str) and name.endswith('/'):\n type = tarfile.DIRTYPE\n if symlink_to is not None:\n got = (self.destdir / name).readlink()\n expected = pathlib.Path(symlink_to)\n # The symlink might be the same (textually) as what we expect,\n # but some systems change the link to an equivalent path, so\n # we fall back to samefile().\n try:\n if expected != got:\n self.assertTrue(got.samefile(expected))\n except Exception as e:\n # attach a note, so it's shown even if `samefile` fails\n e.add_note(f'{expected=}, {got=}')\n raise\n elif type == tarfile.REGTYPE or type is None:\n self.assertTrue(path.is_file())\n elif type == tarfile.DIRTYPE:\n self.assertTrue(path.is_dir())\n elif type == tarfile.FIFOTYPE:\n self.assertTrue(path.is_fifo())\n elif type == tarfile.SYMTYPE:\n self.assertTrue(path.is_symlink())\n else:\n raise NotImplementedError(type)\n if size is not None:\n self.assertEqual(path.stat().st_size, size)\n if content is not None:\n self.assertEqual(path.read_text(), content)\n for parent in path.parents:\n self.expected_paths.discard(parent)\n\n def expect_any_tree(self, name):\n \"\"\"Check a directory; forget about its contents.\"\"\"\n tree_path = (self.destdir / name).resolve()\n self.expect_file(tree_path, type=tarfile.DIRTYPE)\n self.expected_paths = {\n p for p in self.expected_paths\n if tree_path not in p.parents\n }\n\n def expect_exception(self, exc_type, message_re='.'):\n with self.assertRaisesRegex(exc_type, message_re):\n if self.raised_exception is not None:\n raise self.raised_exception\n self.reraise_exception = False\n return self.raised_exception\n\n def test_benign_file(self):\n with ArchiveMaker() as arc:\n arc.add('benign.txt')\n for filter in 'fully_trusted', 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_file('benign.txt')\n\n def test_absolute(self):\n # Test handling a member with an absolute path\n # Inspired by 'absolute1' in https://github.com/jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add(self.outerdir / 'escaped.evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('../escaped.evil')\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n if str(self.outerdir).startswith('/'):\n # We strip leading slashes, as e.g. GNU tar does\n # (without --absolute-filenames).\n outerdir_stripped = str(self.outerdir).lstrip('/')\n self.expect_file(f'{outerdir_stripped}/escaped.evil')\n else:\n # On this system, absolute paths don't have leading\n # slashes.\n # So, there's nothing to strip. We refuse to unpack\n # to an absolute path, nonetheless.\n self.expect_exception(\n tarfile.AbsolutePathError,\n \"\"\"['\"].*escaped.evil['\"] has an absolute path\"\"\")\n\n def test_parent_dir_out_and_back(self):\n # Test a member that leaves the destination and comes back.\n # The containment check looks at the resolved path, which stays\n # inside, but the intermediate directories are created from the\n # name as given, which does not.\n with ArchiveMaker() as arc:\n arc.add(f'../escaped.evil/../{self.destdir.name}/sub/file',\n content='content')\n\n for filter in 'tar', 'data':\n with self.subTest(filter):\n with self.check_context(arc.open(), filter):\n self.expect_file('sub/file', content='content')\n\n @symlink_test\n def test_parent_symlink(self):\n # Test interplaying symlinks\n # Inspired by 'dirsymlink2a' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n\n # `current` links to `.` which is both:\n # - the destination directory\n # - `current` itself\n arc.add('current', symlink_to='.')\n\n # effectively points to ./../\n if self.dotdot_resolves_early and os_helper.can_symlink():\n arc.add('parent', symlink_to='current/../..')\n else:\n arc.add('parent', symlink_to='current/..')\n\n arc.add('parent/evil')\n\n if os_helper.can_symlink():\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('current', symlink_to='.')\n if self.dotdot_resolves_early:\n self.expect_file('parent', symlink_to='current/../..')\n else:\n self.expect_file('parent', symlink_to='current/..')\n self.expect_file('../evil')\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"\"\"'parent/evil' would be extracted to ['\"].*evil['\"], \"\"\"\n + \"which is outside the destination\")\n\n with self.check_context(arc.open(), 'data'):\n if self.dotdot_resolves_early:\n # 'current/../..' normalises to '..', which is rejected.\n self.expect_exception(\n tarfile.LinkOutsideDestinationError,\n \"\"\"'parent' would link to ['\"].*outerdir['\"], \"\"\"\n + \"which is outside the destination\")\n else:\n # 'current/..' normalises to '.'; the rewritten link is\n # created and 'parent/evil' lands harmlessly inside the\n # destination.\n self.expect_file('current', symlink_to='.')\n self.expect_file('parent', symlink_to='.')\n self.expect_file('evil')\n\n else:\n # No symlink support. The symlinks are ignored.\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('parent/evil')\n with self.check_context(arc.open(), 'tar'):\n self.expect_file('parent/evil')\n with self.check_context(arc.open(), 'data'):\n self.expect_file('parent/evil')\n\n @symlink_test\n @os_helper.skip_unless_symlink\n def test_realpath_limit_attack(self):\n # (CVE-2025-4517)\n\n with ArchiveMaker() as arc:\n # populate the symlinks and dirs that expand in os.path.realpath()\n # The component length is chosen so that in common cases, the unexpanded\n # path fits in PATH_MAX, but it overflows when the final symlink\n # is expanded\n steps = \"abcdefghijklmnop\"\n if sys.platform == 'win32':\n component = 'd' * 25\n elif 'PC_PATH_MAX' in os.pathconf_names:\n max_path_len = os.pathconf(self.outerdir.parent, \"PC_PATH_MAX\")\n path_sep_len = 1\n dest_len = len(str(self.destdir)) + path_sep_len\n component_len = (max_path_len - dest_len) // (len(steps) + path_sep_len)\n component = 'd' * component_len\n else:\n raise NotImplementedError(\"Need to guess component length for {sys.platform}\")\n path = \"\"\n step_path = \"\"\n for i in steps:\n arc.add(os.path.join(path, component), type=tarfile.DIRTYPE,\n mode='drwxrwxrwx')\n arc.add(os.path.join(path, i), symlink_to=component)\n path = os.path.join(path, component)\n step_path = os.path.join(step_path, i)\n # create the final symlink that exceeds PATH_MAX and simply points\n # to the top dir.\n # this link will never be expanded by\n # os.path.realpath(strict=False), nor anything after it.\n linkpath = os.path.join(*steps, \"l\"*254)\n parent_segments = [\"..\"] * len(steps)\n arc.add(linkpath, symlink_to=os.path.join(*parent_segments))\n # make a symlink outside to keep the tar command happy\n arc.add(\"escape\", symlink_to=os.path.join(linkpath, \"..\"))\n # use the symlinks above, that are not checked, to create a hardlink\n # to a file outside of the destination path\n arc.add(\"flaglink\", hardlink_to=os.path.join(\"escape\", \"flag\"))\n # now that we have the hardlink we can overwrite the file\n arc.add(\"flaglink\", content='overwrite')\n # we can also create new files as well!\n arc.add(\"escape/newfile\", content='new')\n\n with (self.subTest('fully_trusted'),\n self.check_context(arc.open(), filter='fully_trusted',\n check_flag=False)):\n if sys.platform == 'win32':\n self.expect_exception((FileNotFoundError, FileExistsError))\n elif self.raised_exception:\n # Cannot symlink/hardlink: tarfile falls back to getmember()\n self.expect_exception(KeyError)\n # Otherwise, this block should never enter.\n else:\n self.expect_any_tree(component)\n self.expect_file('flaglink', content='overwrite')\n self.expect_file('../newfile', content='new')\n self.expect_file('escape', type=tarfile.SYMTYPE)\n self.expect_file('a', symlink_to=component)\n\n for filter in 'tar', 'data':\n with self.subTest(filter), self.check_context(arc.open(), filter=filter):\n exc = self.expect_exception((OSError, KeyError))\n if isinstance(exc, OSError):\n if sys.platform == 'win32':\n # 3: ERROR_PATH_NOT_FOUND\n # 5: ERROR_ACCESS_DENIED\n # 206: ERROR_FILENAME_EXCED_RANGE\n self.assertIn(exc.winerror, (3, 5, 206))\n else:\n self.assertEqual(exc.errno, errno.ENAMETOOLONG)\n\n @symlink_test\n def test_parent_symlink2(self):\n # Test interplaying symlinks\n # Inspired by 'dirsymlink2b' in jwilk/traversal-archives\n\n with ArchiveMaker() as arc:\n\n # `current` links to `.` which is both the destination directory\n # and `current` itself\n arc.add('current', symlink_to='.')\n\n # `current/parent` is also available as `./parent`,\n # and effectively points to `./../`\n arc.add('current/parent', symlink_to='..')\n\n arc.add('parent/evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n if os_helper.can_symlink():\n self.expect_file('current', symlink_to='.')\n self.expect_file('parent', symlink_to='..')\n self.expect_file('../evil')\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'tar'):\n if os_helper.can_symlink():\n # Fail when extracting a file outside destination\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'data'):\n if os_helper.can_symlink():\n if self.dotdot_resolves_early:\n # Fail when extracting a file outside destination\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n # Fail as soon as we have a symlink outside the destination\n self.expect_exception(\n tarfile.LinkOutsideDestinationError,\n \"'current/parent' would link to \"\n + \"\"\"['\"].*outerdir['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('current/')\n self.expect_file('parent/evil')\n\n @symlink_test\n def test_absolute_symlink(self):\n # Test symlink to an absolute path\n # Inspired by 'dirsymlink' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('parent', symlink_to=self.outerdir)\n arc.add('parent/evil')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n if os_helper.can_symlink():\n self.expect_file('parent', symlink_to=self.outerdir)\n self.expect_file('../evil')\n else:\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'tar'):\n if os_helper.can_symlink():\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'parent/evil' would be extracted to \"\n + \"\"\"['\"].*evil['\"], which is outside \"\"\"\n + \"the destination\")\n else:\n self.expect_file('parent/evil')\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.AbsoluteLinkError,\n \"'parent' is a link to an absolute path\")\n\n @symlink_test\n @os_helper.skip_unless_symlink\n def test_symlink_target_seperator_rewrite_on_windows(self):\n with ArchiveMaker() as arc:\n arc.add('link', symlink_to=\"relative/test/path\")\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('link', type=tarfile.SYMTYPE)\n link_path = os.path.normpath(self.destdir / \"link\")\n link_target = os.readlink(link_path)\n if os.name == \"nt\":\n self.assertEqual(link_target, \"relative\\\\test\\\\path\")\n else:\n self.assertEqual(link_target, \"relative/test/path\")\n\n def test_absolute_hardlink(self):\n # Test hardlink to an absolute path\n # Inspired by 'dirsymlink' in https://github.com/jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('parent', hardlink_to=self.outerdir / 'foo')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_exception(KeyError, \".*foo. not found\")\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_exception(KeyError, \".*foo. not found\")\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.AbsoluteLinkError,\n \"'parent' is a link to an absolute path\")\n\n @symlink_test\n def test_sly_relative0(self):\n # Inspired by 'relative0' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n # points to `../../tmp/moo`\n arc.add('../moo', symlink_to='..//tmp/moo')\n\n try:\n with self.check_context(arc.open(), filter='fully_trusted'):\n if os_helper.can_symlink():\n if isinstance(self.raised_exception, FileExistsError):\n # XXX TarFile happens to fail creating a parent\n # directory.\n # This might be a bug, but fixing it would hurt\n # security.\n # Note that e.g. GNU `tar` rejects '..' components,\n # so you could argue this is an invalid archive and we\n # just raise an bad type of exception.\n self.expect_exception(FileExistsError)\n else:\n self.expect_file('../moo', symlink_to='..//tmp/moo')\n else:\n # The symlink can't be extracted and is ignored\n pass\n except FileExistsError:\n pass\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'../moo' would be extracted to \"\n + \"'.*moo', which is outside \"\n + \"the destination\")\n\n @symlink_test\n def test_sly_relative2(self):\n # Inspired by 'relative2' in jwilk/traversal-archives\n with ArchiveMaker() as arc:\n arc.add('tmp/')\n arc.add('tmp/../../moo', symlink_to='tmp/../..//tmp/moo')\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('tmp', type=tarfile.DIRTYPE)\n if os_helper.can_symlink():\n self.expect_file('../moo', symlink_to='tmp/../../tmp/moo')\n\n for filter in 'tar', 'data':\n with self.check_context(arc.open(), filter):\n self.expect_exception(\n tarfile.OutsideDestinationError,\n \"'tmp/../../moo' would be extracted to \"\n + \"\"\"['\"].*moo['\"], which is outside the \"\"\"\n + \"destination\")\n\n @symlink_test\n @os_helper.skip_unless_symlink\n def test_normpath_realpath_mismatch(self):\n # The link-target check must validate the value that will actually\n # be written to disk (the normalised linkname), not the original.\n # Here 'a' is a symlink to a deep nonexistent path, so realpath()\n # of 'a/../../...' stays inside the destination while normpath()\n # collapses 'a/..' lexically and escapes.\n depth = len(self.destdir.parts) + 5\n deep = '/'.join(f'p{i}' for i in range(depth))\n sneaky = 'a/' + '../' * depth + 'flag'\n for kind in 'symlink_to', 'hardlink_to':\n with self.subTest(kind):\n with ArchiveMaker() as arc:\n arc.add('a', symlink_to=deep)\n arc.add('escape', **{kind: sneaky})\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.LinkOutsideDestinationError)\n\n @symlink_test\n @os_helper.skip_unless_symlink\n def test_symlink_trailing_slash(self):\n # A trailing slash on a symlink member's name must not cause the\n # link target to be resolved relative to the wrong directory.\n with ArchiveMaker() as arc:\n t = tarfile.TarInfo('x/')\n t.type = tarfile.SYMTYPE\n t.linkname = '..'\n arc.tar_w.addfile(t)\n arc.add('x/escaped', content='hi')\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(tarfile.LinkOutsideDestinationError)\n\n @symlink_test\n @os_helper.skip_unless_symlink\n def test_link_at_destination(self):\n # A link member whose name resolves to the destination directory\n # itself must be rejected: otherwise the destination is replaced\n # by a symlink and later members can be redirected through it.\n for name in '', '.', './':\n with ArchiveMaker() as arc:\n t = tarfile.TarInfo(name)\n t.type = tarfile.SYMTYPE\n t.linkname = '.'\n arc.tar_w.addfile(t)\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(tarfile.OutsideDestinationError)\n\n @symlink_test\n @os_helper.skip_unless_symlink\n def test_empty_name_symlink_chain(self):\n # Regression test for a chain of empty-named symlinks that\n # incrementally redirects the destination outwards.\n with ArchiveMaker() as arc:\n for name, target in [('', ''), ('a/', '..'),\n ('', 'dummy'), ('', 'a'),\n ('b/', '..'),\n ('', 'dummy'), ('', 'a/b')]:\n t = tarfile.TarInfo(name)\n t.type = tarfile.SYMTYPE\n t.linkname = target\n arc.tar_w.addfile(t)\n arc.add('escaped', content='hi')\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(tarfile.FilterError)\n\n @symlink_test\n def test_deep_symlink(self):\n # Test that symlinks and hardlinks inside a directory\n # point to the correct file (`target` of size 3).\n # If links aren't supported we get a copy of the file.\n with ArchiveMaker() as arc:\n arc.add('targetdir/target', size=3)\n # a hardlink's linkname is relative to the archive\n arc.add('linkdir/hardlink', hardlink_to=os.path.join(\n 'targetdir', 'target'))\n # a symlink's linkname is relative to the link's directory\n arc.add('linkdir/symlink', symlink_to=os.path.join(\n '..', 'targetdir', 'target'))\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n self.expect_file('targetdir/target', size=3)\n self.expect_file('linkdir/hardlink', size=3)\n if os_helper.can_symlink():\n self.expect_file('linkdir/symlink', size=3,\n symlink_to='../targetdir/target')\n else:\n self.expect_file('linkdir/symlink', size=3)\n\n @symlink_test\n def test_chains(self):\n # Test chaining of symlinks/hardlinks.\n # Symlinks are created before the files they point to.\n with ArchiveMaker() as arc:\n arc.add('linkdir/symlink', symlink_to='hardlink')\n arc.add('symlink2', symlink_to=os.path.join(\n 'linkdir', 'hardlink2'))\n arc.add('targetdir/target', size=3)\n arc.add('linkdir/hardlink', hardlink_to=os.path.join('targetdir', 'target'))\n arc.add('linkdir/hardlink2', hardlink_to=os.path.join('linkdir', 'symlink'))\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n self.expect_file('targetdir/target', size=3)\n self.expect_file('linkdir/hardlink', size=3)\n self.expect_file('linkdir/hardlink2', size=3)\n if os_helper.can_symlink():\n self.expect_file('linkdir/symlink', size=3,\n symlink_to='hardlink')\n self.expect_file('symlink2', size=3,\n symlink_to='linkdir/hardlink2')\n else:\n self.expect_file('linkdir/symlink', size=3)\n self.expect_file('symlink2', size=3)\n\n @symlink_test\n def test_sneaky_hardlink_fallback(self):\n # (CVE-2025-4330)\n # Test that when hardlink extraction falls back to extracting members\n # from the archive, the extracted member is (re-)filtered.\n with ArchiveMaker() as arc:\n # Create a directory structure so the c/escape symlink stays\n # inside the path\n arc.add(\"a/t/dummy\")\n # Create b/ directory\n arc.add(\"b/\")\n # Point \"c\" to the bottom of the tree in \"a\"\n arc.add(\"c\", symlink_to=os.path.join(\"a\", \"t\"))\n # link to non-existant location under \"a\"\n arc.add(\"c/escape\", symlink_to=os.path.join(\"..\", \"..\",\n \"link_here\"))\n # Move \"c\" to point to \"b\" (\"c/escape\" no longer exists)\n arc.add(\"c\", symlink_to=\"b\")\n # Attempt to create a hard link to \"c/escape\". Since it doesn't\n # exist it will attempt to extract \"cescape\" but at \"boom\".\n arc.add(\"boom\", hardlink_to=os.path.join(\"c\", \"escape\"))\n\n with self.check_context(arc.open(), 'data'):\n if not os_helper.can_symlink():\n # When 'c/escape' is extracted, 'c' is a regular\n # directory, and 'c/escape' *would* point outside\n # the destination if symlinks were allowed.\n self.expect_exception(\n tarfile.LinkOutsideDestinationError)\n elif sys.platform == \"win32\":\n # On Windows, 'c/escape' points outside the destination\n self.expect_exception(tarfile.LinkOutsideDestinationError)\n else:\n e = self.expect_exception(\n tarfile.LinkFallbackError,\n \"link 'boom' would be extracted as a copy of \"\n + \"'c/escape', which was rejected\")\n self.assertIsInstance(e.__cause__,\n tarfile.LinkOutsideDestinationError)\n for filter in 'tar', 'fully_trusted':\n with self.subTest(filter), self.check_context(arc.open(), filter):\n if not os_helper.can_symlink():\n if filter == 'fully_trusted' or sys.platform == \"win32\":\n self.expect_file(\"a/t/dummy\")\n self.expect_file(\"b/\")\n self.expect_file(\"c/\")\n else:\n self.expect_exception(\n tarfile.LinkFallbackError,\n \"link 'boom' would be extracted as a copy of \"\n + \"'c/escape', which was rejected\")\n else:\n self.expect_file(\"a/t/dummy\")\n self.expect_file(\"b/\")\n self.expect_file(\"a/t/escape\", symlink_to='../../link_here')\n self.expect_file(\"boom\", symlink_to='../../link_here')\n self.expect_file(\"c\", symlink_to='b')\n\n @symlink_test\n def test_sneaky_hardlink_fallback_deep(self):\n # (CVE-2026-11940)\n with ArchiveMaker() as arc:\n arc.add(\"a/b/s\", symlink_to=os.path.join(\"..\", \"escape\"))\n arc.add(\"s\", hardlink_to=os.path.join(\"a\", \"b\", \"s\"))\n\n with self.check_context(arc.open(), 'data'):\n e = self.expect_exception(\n tarfile.LinkFallbackError,\n \"link 's' would be extracted as a copy of \"\n + \"'a/b/s', which was rejected\")\n self.assertIsInstance(e.__cause__,\n tarfile.LinkOutsideDestinationError)\n\n for filter in 'tar', 'fully_trusted':\n with self.subTest(filter), self.check_context(arc.open(), filter):\n if not os_helper.can_symlink():\n self.expect_file(\"a/\")\n self.expect_file(\"a/b/\")\n else:\n self.expect_file(\"a/b/s\", symlink_to=os.path.join('..', 'escape'))\n self.expect_file(\"s\", symlink_to=os.path.join('..', 'escape'))\n\n @symlink_test\n def test_exfiltration_via_symlink(self):\n # (CVE-2025-4138)\n # Test changing symlinks that result in a symlink pointing outside\n # the extraction directory, unless prevented by 'data' filter's\n # normalization.\n with ArchiveMaker() as arc:\n arc.add(\"escape\", symlink_to=os.path.join('link', 'link', '..', '..', 'link-here'))\n arc.add(\"link\", symlink_to='./')\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter):\n if os_helper.can_symlink():\n self.expect_file(\"link\", symlink_to='./')\n if filter == 'data':\n self.expect_file(\"escape\", symlink_to='link-here')\n else:\n self.expect_file(\"escape\",\n symlink_to='link/link/../../link-here')\n else:\n # Nothing is extracted.\n pass\n\n @symlink_test\n def test_chmod_outside_dir(self):\n # (CVE-2024-12718)\n # Test that members used for delayed updates of directory metadata\n # are (re-)filtered.\n with ArchiveMaker() as arc:\n # \"pwn\" is a veeeery innocent symlink:\n arc.add(\"a/pwn\", symlink_to='.')\n # But now \"pwn\" is also a directory, so it's scheduled to have its\n # metadata updated later:\n arc.add(\"a/pwn/\", mode='drwxrwxrwx')\n # Oops, \"pwn\" is not so innocent any more:\n arc.add(\"a/pwn\", symlink_to='x/../')\n # Newly created symlink points to the dest dir,\n # so it's OK for the \"data\" filter.\n arc.add('a/x', symlink_to=('../'))\n # But now \"pwn\" points outside the dest dir\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter) as cc:\n if not os_helper.can_symlink():\n self.expect_file(\"a/pwn/\")\n elif filter == 'data':\n self.expect_file(\"a/x\", symlink_to='../')\n self.expect_file(\"a/pwn\", symlink_to='.')\n else:\n self.expect_file(\"a/x\", symlink_to='../')\n self.expect_file(\"a/pwn\", symlink_to='x/../')\n if sys.platform != \"win32\":\n st_mode = cc.outerdir.stat().st_mode\n self.assertNotEqual(st_mode & 0o777, 0o777)\n\n @symlink_test\n @unittest.skipUnless(hasattr(os, 'chown'), \"missing os.chown\")\n @unittest.skipUnless(hasattr(os, 'lchown'), \"missing os.lchown\")\n @unittest.skipUnless(hasattr(os, 'geteuid'), \"missing os.geteuid\")\n @support.subTests('link_type', (tarfile.SYMTYPE, tarfile.LNKTYPE))\n def test_chown_links_on_extract(self, link_type):\n with ArchiveMaker() as arc:\n arc.add(\"test.txt\",\n uid=1337, gid=1337, uname=\"\", gname=\"\", mode='-rwxr-xr-x')\n arc.add(\"link\",\n type=link_type,\n linkname='test.txt',\n uid=1337, gid=1337, uname=\"\", gname=\"\", mode='-rwxr-xr-x')\n\n with (\n os_helper.temp_dir() as tmpdir,\n arc.open() as tar,\n unittest.mock.patch(\"os.chown\") as mock_chown,\n unittest.mock.patch(\"os.lchown\") as mock_lchown,\n unittest.mock.patch(\"os.geteuid\") as mock_geteuid,\n ):\n # Set UID to 0 so chown() is attempted.\n mock_geteuid.return_value = 0\n tar.extract(\"link\", path=tmpdir, filter='data')\n extract_path = os.path.join(tmpdir, \"link\")\n\n if link_type == tarfile.SYMTYPE:\n mock_chown.assert_not_called()\n mock_lchown.assert_called_once_with(extract_path, -1, -1)\n else:\n mock_chown.assert_has_calls([\n unittest.mock.call(extract_path, -1, -1),\n unittest.mock.call(extract_path, -1, -1)\n ])\n mock_lchown.assert_not_called()\n\n @symlink_test\n @unittest.skipUnless(hasattr(os, 'chown'), \"missing os.chown\")\n @unittest.skipUnless(hasattr(os, 'lchown'), \"missing os.lchown\")\n @unittest.skipUnless(hasattr(os, 'geteuid'), \"missing os.geteuid\")\n @support.subTests('link_type', (tarfile.SYMTYPE, tarfile.LNKTYPE))\n def test_chown_links_on_extractall(self, link_type):\n with ArchiveMaker() as arc:\n arc.add(\"test.txt\",\n uid=1337, gid=1337, uname=\"\", gname=\"\", mode='-rwxr-xr-x')\n arc.add(\"link\",\n type=link_type,\n linkname='test.txt',\n uid=1337, gid=1337, uname=\"\", gname=\"\", mode='-rwxr-xr-x')\n\n with (\n os_helper.temp_dir() as tmpdir,\n arc.open() as tar,\n unittest.mock.patch(\"os.chown\") as mock_chown,\n unittest.mock.patch(\"os.lchown\") as mock_lchown,\n unittest.mock.patch(\"os.geteuid\") as mock_geteuid,\n ):\n # Set UID to 0 so chown() is attempted.\n mock_geteuid.return_value = 0\n tar.extractall(path=tmpdir, filter='data')\n extract_link_path = os.path.join(tmpdir, \"link\")\n extract_file_path = os.path.join(tmpdir, \"test.txt\")\n\n if link_type == tarfile.SYMTYPE:\n mock_chown.assert_called_once_with(extract_file_path, -1, -1)\n mock_lchown.assert_called_once_with(extract_link_path, -1, -1)\n else:\n mock_chown.assert_has_calls([\n unittest.mock.call(extract_file_path, -1, -1),\n unittest.mock.call(extract_link_path, -1, -1)\n ])\n mock_lchown.assert_not_called()\n\n def test_extract_filters_target(self):\n # Test that when extract() falls back to extracting (rather than\n # linking) a hardlink target, it filters the target.\n with ArchiveMaker() as arc:\n arc.add(\"target\")\n arc.add(\"link\", hardlink_to=\"target\")\n def testing_filter(member, path):\n if member.name == 'target':\n # target: set read-only\n return member.replace(mode=stat.S_IRUSR)\n # link: don't overwrite the mode\n return member.replace(mode=None)\n tempdir = pathlib.Path(TEMPDIR) / 'extract'\n with os_helper.temp_dir(tempdir), arc.open() as tar:\n tar.extract(\"link\", path=tempdir, filter=testing_filter)\n path = tempdir / 'link'\n if os_helper.can_chmod():\n self.assertFalse(path.stat().st_mode & stat.S_IWUSR)\n\n @symlink_test\n def test_extract_filters_target_none(self):\n # Test that when extract() falls back to extracting (rather than\n # linking) a hardlink target, the member is skipped if the filter\n # returns None.\n with ArchiveMaker() as arc:\n arc.add('a/b/s', symlink_to='../escape')\n arc.add('q', hardlink_to='a/b/s')\n def filter_unsafe_members(member, path):\n try:\n return tarfile.data_filter(member, path)\n except tarfile.FilterError as error:\n return None\n with self.check_context(arc.open(), filter_unsafe_members):\n if os_helper.can_symlink():\n self.expect_file('a/b/s', symlink_to='../escape')\n else:\n self.expect_file('a/b/') # symlink is not extracted\n\n def test_link_fallback_normalizes(self):\n # Make sure hardlink fallbacks work for non-normalized paths for all\n # filters\n with ArchiveMaker() as arc:\n arc.add(\"dir/\")\n arc.add(\"dir/../afile\")\n arc.add(\"link1\", hardlink_to='dir/../afile')\n arc.add(\"link2\", hardlink_to='dir/../dir/../afile')\n\n for filter in 'tar', 'data', 'fully_trusted':\n with self.check_context(arc.open(), filter) as cc:\n self.expect_file(\"dir/\")\n self.expect_file(\"afile\")\n self.expect_file(\"link1\")\n self.expect_file(\"link2\")\n\n def test_modes(self):\n # Test how file modes are extracted\n # (Note that the modes are ignored on platforms without working chmod)\n with ArchiveMaker() as arc:\n arc.add('all_bits', mode='?rwsrwsrwt')\n arc.add('perm_bits', mode='?rwxrwxrwx')\n arc.add('exec_group_other', mode='?rw-rwxrwx')\n arc.add('read_group_only', mode='?---r-----')\n arc.add('no_bits', mode='?---------')\n arc.add('dir/', mode='?---rwsrwt')\n arc.add('dir_all_bits/', mode='?rwsrwsrwt')\n\n # On some systems, setting the uid, gid, and/or sticky bit is a no-ops.\n # Check which bits we can set, so we can compare tarfile machinery to\n # a simple chmod.\n tmp_filename = os.path.join(TEMPDIR, \"tmp.file\")\n with open(tmp_filename, 'w'):\n pass\n try:\n new_mode = (os.stat(tmp_filename).st_mode\n | stat.S_ISVTX | stat.S_ISGID | stat.S_ISUID)\n try:\n os.chmod(tmp_filename, new_mode)\n except OSError as exc:\n if exc.errno == getattr(errno, \"EFTYPE\", 0):\n # gh-108948: On FreeBSD, regular users cannot set\n # the sticky bit.\n self.skipTest(\"chmod() failed with EFTYPE: \"\n \"regular users cannot set sticky bit\")\n else:\n raise\n\n got_mode = os.stat(tmp_filename).st_mode\n _t_file = 't' if (got_mode & stat.S_ISVTX) else 'x'\n _suid_file = 's' if (got_mode & stat.S_ISUID) else 'x'\n _sgid_file = 's' if (got_mode & stat.S_ISGID) else 'x'\n finally:\n os.unlink(tmp_filename)\n\n os.mkdir(tmp_filename)\n new_mode = (os.stat(tmp_filename).st_mode\n | stat.S_ISVTX | stat.S_ISGID | stat.S_ISUID)\n os.chmod(tmp_filename, new_mode)\n got_mode = os.stat(tmp_filename).st_mode\n _t_dir = 't' if (got_mode & stat.S_ISVTX) else 'x'\n _suid_dir = 's' if (got_mode & stat.S_ISUID) else 'x'\n _sgid_dir = 's' if (got_mode & stat.S_ISGID) else 'x'\n os.rmdir(tmp_filename)\n\n with self.check_context(arc.open(), 'fully_trusted'):\n self.expect_file('all_bits',\n mode=f'?rw{_suid_file}rw{_sgid_file}rw{_t_file}')\n self.expect_file('perm_bits', mode='?rwxrwxrwx')\n self.expect_file('exec_group_other', mode='?rw-rwxrwx')\n self.expect_file('read_group_only', mode='?---r-----')\n self.expect_file('no_bits', mode='?---------')\n self.expect_file('dir/', mode=f'?---rw{_sgid_dir}rw{_t_dir}')\n self.expect_file('dir_all_bits/',\n mode=f'?rw{_suid_dir}rw{_sgid_dir}rw{_t_dir}')\n\n with self.check_context(arc.open(), 'tar'):\n self.expect_file('all_bits', mode='?rwxr-xr-x')\n self.expect_file('perm_bits', mode='?rwxr-xr-x')\n self.expect_file('exec_group_other', mode='?rw-r-xr-x')\n self.expect_file('read_group_only', mode='?---r-----')\n self.expect_file('no_bits', mode='?---------')\n self.expect_file('dir/', mode='?---r-xr-x')\n self.expect_file('dir_all_bits/', mode='?rwxr-xr-x')\n\n with self.check_context(arc.open(), 'data'):\n normal_dir_mode = stat.filemode(stat.S_IMODE(\n self.outerdir.stat().st_mode))\n self.expect_file('all_bits', mode='?rwxr-xr-x')\n self.expect_file('perm_bits', mode='?rwxr-xr-x')\n self.expect_file('exec_group_other', mode='?rw-r--r--')\n self.expect_file('read_group_only', mode='?rw-r-----')\n self.expect_file('no_bits', mode='?rw-------')\n self.expect_file('dir/', mode=normal_dir_mode)\n self.expect_file('dir_all_bits/', mode=normal_dir_mode)\n\n def test_pipe(self):\n # Test handling of a special file\n with ArchiveMaker() as arc:\n arc.add('foo', type=tarfile.FIFOTYPE)\n\n for filter in 'fully_trusted', 'tar':\n with self.check_context(arc.open(), filter):\n if hasattr(os, 'mkfifo'):\n self.expect_file('foo', type=tarfile.FIFOTYPE)\n else:\n # The pipe can't be extracted and is skipped.\n pass\n\n with self.check_context(arc.open(), 'data'):\n self.expect_exception(\n tarfile.SpecialFileError,\n \"'foo' is a special file\")\n\n def test_special_files(self):\n # Creating device files is tricky. Instead of attempting that let's\n # only check the filter result.\n for special_type in tarfile.FIFOTYPE, tarfile.CHRTYPE, tarfile.BLKTYPE:\n tarinfo = tarfile.TarInfo('foo')\n tarinfo.type = special_type\n trusted = tarfile.fully_trusted_filter(tarinfo, '')\n self.assertIs(trusted, tarinfo)\n tar = tarfile.tar_filter(tarinfo, '')\n self.assertEqual(tar.type, special_type)\n with self.assertRaises(tarfile.SpecialFileError) as cm:\n tarfile.data_filter(tarinfo, '')\n self.assertIsInstance(cm.exception.tarinfo, tarfile.TarInfo)\n self.assertEqual(cm.exception.tarinfo.name, 'foo')\n\n def test_fully_trusted_filter(self):\n # The 'fully_trusted' filter returns the original TarInfo objects.\n with tarfile.TarFile.open(tarname) as tar:\n for tarinfo in tar.getmembers():\n filtered = tarfile.fully_trusted_filter(tarinfo, '')\n self.assertIs(filtered, tarinfo)\n\n def test_tar_filter(self):\n # The 'tar' filter returns TarInfo objects with the same name/type.\n # (It can also fail for particularly \"evil\" input, but we don't have\n # that in the test archive.)\n with tarfile.TarFile.open(tarname, encoding=\"iso8859-1\") as tar:\n for tarinfo in tar.getmembers():\n try:\n filtered = tarfile.tar_filter(tarinfo, '')\n except UnicodeEncodeError:\n continue\n self.assertIs(filtered.name, tarinfo.name)\n self.assertIs(filtered.type, tarinfo.type)\n\n def test_data_filter(self):\n # The 'data' filter either raises, or returns TarInfo with the same\n # name/type.\n with tarfile.TarFile.open(tarname, encoding=\"iso8859-1\") as tar:\n for tarinfo in tar.getmembers():\n try:\n filtered = tarfile.data_filter(tarinfo, '')\n except (tarfile.FilterError, UnicodeEncodeError):\n continue\n self.assertIs(filtered.name, tarinfo.name)\n self.assertIs(filtered.type, tarinfo.type)\n\n @unittest.skipIf(sys.platform == 'win32', 'requires native bytes paths')\n def test_filter_unencodable(self):\n # Sanity check using a valid path.\n tarinfo = tarfile.TarInfo(os_helper.TESTFN)\n filtered = tarfile.tar_filter(tarinfo, '')\n self.assertIs(filtered.name, tarinfo.name)\n filtered = tarfile.data_filter(tarinfo, '')\n self.assertIs(filtered.name, tarinfo.name)\n\n tarinfo = tarfile.TarInfo('test\\x00')\n self.assertRaises(ValueError, tarfile.tar_filter, tarinfo, '')\n self.assertRaises(ValueError, tarfile.data_filter, tarinfo, '')\n tarinfo = tarfile.TarInfo('\\ud800')\n self.assertRaises(UnicodeEncodeError, tarfile.tar_filter, tarinfo, '')\n self.assertRaises(UnicodeEncodeError, tarfile.data_filter, tarinfo, '')\n\n @unittest.skipIf(sys.platform == 'win32', 'requires native bytes paths')\n def test_extract_unencodable(self):\n # Create a member with name \\xed\\xa0\\x80 which is UTF-8 encoded\n # lone surrogate \\ud800.\n with ArchiveMaker(encoding='ascii', errors='surrogateescape') as arc:\n arc.add('\\udced\\udca0\\udc80')\n with os_helper.temp_cwd() as tmp:\n tar = arc.open(encoding='utf-8', errors='surrogatepass',\n errorlevel=1)\n self.assertEqual(tar.getnames(), ['\\ud800'])\n with self.assertRaises(UnicodeEncodeError):\n tar.extractall()\n self.assertEqual(os.listdir(), [])\n\n tar = arc.open(encoding='utf-8', errors='surrogatepass',\n errorlevel=0, debug=1)\n with support.captured_stderr() as stderr:\n tar.extractall()\n self.assertEqual(os.listdir(), [])\n self.assertIn('tarfile: UnicodeEncodeError ', stderr.getvalue())\n\n def test_change_default_filter_on_instance(self):\n tar = tarfile.TarFile(tarname, 'r')\n def strict_filter(tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n tar.extraction_filter = strict_filter\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_on_class(self):\n def strict_filter(tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n tar = tarfile.TarFile(tarname, 'r')\n with support.swap_attr(tarfile.TarFile, 'extraction_filter',\n staticmethod(strict_filter)):\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_on_subclass(self):\n class TarSubclass(tarfile.TarFile):\n def extraction_filter(self, tarinfo, path):\n if tarinfo.name == 'ustar/regtype':\n return tarinfo\n else:\n return None\n\n tar = TarSubclass(tarname, 'r')\n with self.check_context(tar, None):\n self.expect_file('ustar/regtype')\n\n def test_change_default_filter_to_string(self):\n tar = tarfile.TarFile(tarname, 'r')\n tar.extraction_filter = 'data'\n with self.check_context(tar, None):\n self.expect_exception(TypeError)\n\n def test_custom_filter(self):\n def custom_filter(tarinfo, path):\n self.assertIs(path, self.destdir)\n if tarinfo.name == 'move_this':\n return tarinfo.replace(name='moved')\n if tarinfo.name == 'ignore_this':\n return None\n return tarinfo\n\n with ArchiveMaker() as arc:\n arc.add('move_this')\n arc.add('ignore_this')\n arc.add('keep')\n with self.check_context(arc.open(), custom_filter):\n self.expect_file('moved')\n self.expect_file('keep')\n\n def test_bad_filter_name(self):\n with ArchiveMaker() as arc:\n arc.add('foo')\n with self.check_context(arc.open(), 'bad filter name'):\n self.expect_exception(ValueError)\n\n def test_stateful_filter(self):\n # Stateful filters should be possible.\n # (This doesn't really test tarfile. Rather, it demonstrates\n # that third parties can implement a stateful filter.)\n class StatefulFilter:\n def __enter__(self):\n self.num_files_processed = 0\n return self\n\n def __call__(self, tarinfo, path):\n try:\n tarinfo = tarfile.data_filter(tarinfo, path)\n except tarfile.FilterError:\n return None\n self.num_files_processed += 1\n return tarinfo\n\n def __exit__(self, *exc_info):\n self.done = True\n\n with ArchiveMaker() as arc:\n arc.add('good')\n arc.add('bad', symlink_to='/')\n arc.add('good')\n with StatefulFilter() as custom_filter:\n with self.check_context(arc.open(), custom_filter):\n self.expect_file('good')\n self.assertEqual(custom_filter.num_files_processed, 2)\n self.assertEqual(custom_filter.done, True)\n\n def test_errorlevel(self):\n def extracterror_filter(tarinfo, path):\n raise tarfile.ExtractError('failed with ExtractError')\n def filtererror_filter(tarinfo, path):\n raise tarfile.FilterError('failed with FilterError')\n def oserror_filter(tarinfo, path):\n raise OSError('failed with OSError')\n def tarerror_filter(tarinfo, path):\n raise tarfile.TarError('failed with base TarError')\n def valueerror_filter(tarinfo, path):\n raise ValueError('failed with ValueError')\n\n with ArchiveMaker() as arc:\n arc.add('file')\n\n # If errorlevel is 0, errors affected by errorlevel are ignored\n\n with self.check_context(arc.open(errorlevel=0), extracterror_filter):\n pass\n\n with self.check_context(arc.open(errorlevel=0), filtererror_filter):\n pass\n\n with self.check_context(arc.open(errorlevel=0), oserror_filter):\n pass\n\n with self.check_context(arc.open(errorlevel=0), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=0), valueerror_filter):\n self.expect_exception(ValueError)\n\n # If 1, all fatal errors are raised\n\n with self.check_context(arc.open(errorlevel=1), extracterror_filter):\n pass\n\n with self.check_context(arc.open(errorlevel=1), filtererror_filter):\n self.expect_exception(tarfile.FilterError)\n\n with self.check_context(arc.open(errorlevel=1), oserror_filter):\n self.expect_exception(OSError)\n\n with self.check_context(arc.open(errorlevel=1), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=1), valueerror_filter):\n self.expect_exception(ValueError)\n\n # If 2, all non-fatal errors are raised as well.\n\n with self.check_context(arc.open(errorlevel=2), extracterror_filter):\n self.expect_exception(tarfile.ExtractError)\n\n with self.check_context(arc.open(errorlevel=2), filtererror_filter):\n self.expect_exception(tarfile.FilterError)\n\n with self.check_context(arc.open(errorlevel=2), oserror_filter):\n self.expect_exception(OSError)\n\n with self.check_context(arc.open(errorlevel=2), tarerror_filter):\n self.expect_exception(tarfile.TarError)\n\n with self.check_context(arc.open(errorlevel=2), valueerror_filter):\n self.expect_exception(ValueError)\n\n # We only handle ExtractionError, FilterError & OSError specially.\n\n with self.check_context(arc.open(errorlevel='boo!'), filtererror_filter):\n self.expect_exception(TypeError) # errorlevel is not int\n\n @support.subTests('format', [tarfile.GNU_FORMAT, tarfile.PAX_FORMAT])\n def test_getmembers_big_size(self, format):\n # gh-151981: A loop in seek() for streaming files tried to read the\n # declared number of blocks even at EOF\n tinfo = tarfile.TarInfo(\"huge-file\")\n tinfo.size = 1 << 64\n bio = io.BytesIO()\n # Write header without data\n bio.write(tinfo.tobuf(format))\n\n # Reset & try to get contents\n bio.seek(0)\n with tarfile.open(fileobj=bio, mode=\"r|\") as tar:\n with self.assertRaises(tarfile.ReadError):\n tar.getmembers()\n","source":"cpython_tests","origin":"Lib/test/test_tarfile.py::TestExtractionFilters","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"tarfile-filter","pep":"706","introduced_in":"3.12","form":"modern","file":"tarfile-filter/modern_02.py","code":"import errno\nimport sys\nimport os\nimport io\nfrom hashlib import sha256\nfrom contextlib import contextmanager, ExitStack\nfrom random import Random\nimport pathlib\nimport shutil\nimport re\nimport warnings\nimport stat\nimport time\nimport unittest\nimport unittest.mock\nimport tarfile\nfrom test import archiver_tests\nfrom test import support\nfrom test.support import os_helper\nfrom test.support import script_helper\nfrom test.support import warnings_helper\n\n\nclass NoneInfoExtractTests(ReadTest):\n # These mainly check that all kinds of members are extracted successfully\n # if some metadata is None.\n # Some of the methods do additional spot checks.\n\n # We also test that the default filters can deal with None.\n\n extraction_filter = None\n\n @classmethod\n def setUpClass(cls):\n tar = tarfile.open(tarname, mode='r', encoding=\"iso8859-1\")\n cls.control_dir = pathlib.Path(TEMPDIR) / \"extractall_ctrl\"\n tar.errorlevel = 0\n with ExitStack() as cm:\n if cls.extraction_filter is None:\n cm.enter_context(warnings.catch_warnings(\n action=\"ignore\", category=DeprecationWarning))\n tar.extractall(cls.control_dir, filter=cls.extraction_filter)\n tar.close()\n cls.control_paths = set(\n p.relative_to(cls.control_dir)\n for p in pathlib.Path(cls.control_dir).glob('**/*'))\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.control_dir)\n\n def check_files_present(self, directory):\n got_paths = set(\n p.relative_to(directory)\n for p in pathlib.Path(directory).glob('**/*'))\n if self.extraction_filter in (None, 'data'):\n # The 'data' filter is expected to reject special files\n for path in 'ustar/fifotype', 'ustar/blktype', 'ustar/chrtype':\n got_paths.discard(pathlib.Path(path))\n self.assertEqual(self.control_paths, got_paths)\n\n @contextmanager\n def extract_with_none(self, *attr_names):\n DIR = pathlib.Path(TEMPDIR) / \"extractall_none\"\n self.tar.errorlevel = 0\n for member in self.tar.getmembers():\n for attr_name in attr_names:\n setattr(member, attr_name, None)\n with os_helper.temp_dir(DIR):\n self.tar.extractall(DIR, filter='fully_trusted')\n self.check_files_present(DIR)\n yield DIR\n\n def test_extractall_none_mtime(self):\n # mtimes of extracted files should be later than 'now' -- the mtime\n # of a previously created directory.\n now = pathlib.Path(TEMPDIR).stat().st_mtime\n with self.extract_with_none('mtime') as DIR:\n for path in pathlib.Path(DIR).glob('**/*'):\n with self.subTest(path=path):\n try:\n mtime = path.stat().st_mtime\n except OSError:\n # Some systems can't stat symlinks, ignore those\n if not path.is_symlink():\n raise\n else:\n self.assertGreaterEqual(path.stat().st_mtime, now)\n\n def test_extractall_none_mode(self):\n # modes of directories and regular files should match the mode\n # of a \"normally\" created directory or regular file\n dir_mode = pathlib.Path(TEMPDIR).stat().st_mode\n regular_file = pathlib.Path(TEMPDIR) / 'regular_file'\n regular_file.write_text('')\n regular_file_mode = regular_file.stat().st_mode\n with self.extract_with_none('mode') as DIR:\n for path in pathlib.Path(DIR).glob('**/*'):\n with self.subTest(path=path):\n if path.is_dir():\n self.assertEqual(path.stat().st_mode, dir_mode)\n elif path.is_file():\n self.assertEqual(path.stat().st_mode,\n regular_file_mode)\n\n def test_extractall_none_uid(self):\n with self.extract_with_none('uid'):\n pass\n\n def test_extractall_none_gid(self):\n with self.extract_with_none('gid'):\n pass\n\n def test_extractall_none_uname(self):\n with self.extract_with_none('uname'):\n pass\n\n def test_extractall_none_gname(self):\n with self.extract_with_none('gname'):\n pass\n\n def test_extractall_none_ownership(self):\n with self.extract_with_none('uid', 'gid', 'uname', 'gname'):\n pass\n","source":"cpython_tests","origin":"Lib/test/test_tarfile.py::NoneInfoExtractTests","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_01.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS\nfrom test.support.os_helper import EnvironmentVarGuard, FakePath\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\nfrom test.support.script_helper import assert_python_ok\n\n\nclass ZoneInfoCacheTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n def setUp(self):\n self.klass.clear_cache()\n super().setUp()\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @property\n def tzpath(self):\n return [self.zoneinfo_data.tzpath]\n\n def test_ephemeral_zones(self):\n self.assertIs(\n self.klass(\"America/Los_Angeles\"), self.klass(\"America/Los_Angeles\")\n )\n\n def test_strong_refs(self):\n tz0 = self.klass(\"Australia/Sydney\")\n tz1 = self.klass(\"Australia/Sydney\")\n\n self.assertIs(tz0, tz1)\n\n def test_no_cache(self):\n\n tz0 = self.klass(\"Europe/Lisbon\")\n tz1 = self.klass.no_cache(\"Europe/Lisbon\")\n\n self.assertIsNot(tz0, tz1)\n\n def test_cache_reset_tzpath(self):\n \"\"\"Test that the cache persists when tzpath has been changed.\n\n The PEP specifies that as long as a reference exists to one zone\n with a given key, the primary constructor must continue to return\n the same object.\n \"\"\"\n zi0 = self.klass(\"America/Los_Angeles\")\n with self.tzpath_context([]):\n zi1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIs(zi0, zi1)\n\n def test_clear_cache_explicit_none(self):\n la0 = self.klass(\"America/Los_Angeles\")\n self.klass.clear_cache(only_keys=None)\n la1 = self.klass(\"America/Los_Angeles\")\n\n self.assertIsNot(la0, la1)\n\n def test_clear_cache_one_key(self):\n \"\"\"Tests that you can clear a single key from the cache.\"\"\"\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n\n self.klass.clear_cache(only_keys=[\"America/Los_Angeles\"])\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n\n self.assertIsNot(la0, la1)\n self.assertIs(dub0, dub1)\n\n def test_clear_cache_two_keys(self):\n la0 = self.klass(\"America/Los_Angeles\")\n dub0 = self.klass(\"Europe/Dublin\")\n tok0 = self.klass(\"Asia/Tokyo\")\n\n self.klass.clear_cache(\n only_keys=[\"America/Los_Angeles\", \"Europe/Dublin\"]\n )\n\n la1 = self.klass(\"America/Los_Angeles\")\n dub1 = self.klass(\"Europe/Dublin\")\n tok1 = self.klass(\"Asia/Tokyo\")\n\n self.assertIsNot(la0, la1)\n self.assertIsNot(dub0, dub1)\n self.assertIs(tok0, tok1)\n\n def test_clear_cache_refleak(self):\n class Stringy(str):\n allow_comparisons = True\n def __eq__(self, other):\n if not self.allow_comparisons:\n raise CustomError\n return super().__eq__(other)\n __hash__ = str.__hash__\n\n key = Stringy(\"America/Los_Angeles\")\n self.klass(key)\n key.allow_comparisons = False\n try:\n # Note: This is try/except rather than assertRaises because\n # there is no guarantee that the key is even still in the cache,\n # or that the key for the cache is the original `key` object.\n self.klass.clear_cache(only_keys=\"America/Los_Angeles\")\n except CustomError:\n pass\n\n def test_weak_cache_descriptor_use_after_free(self):\n class BombDescriptor:\n def __get__(self, obj, owner):\n return {}\n\n class EvilZoneInfo(self.klass):\n pass\n\n # Must be set after the class creation.\n EvilZoneInfo._weak_cache = BombDescriptor()\n\n key = \"America/Los_Angeles\"\n zone1 = EvilZoneInfo(key)\n self.assertEqual(str(zone1), key)\n\n EvilZoneInfo.clear_cache()\n zone2 = EvilZoneInfo(key)\n self.assertEqual(str(zone2), key)\n self.assertIsNot(zone2, zone1)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ZoneInfoCacheTest","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_02.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS\nfrom test.support.os_helper import EnvironmentVarGuard, FakePath\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\nfrom test.support.script_helper import assert_python_ok\n\n\nclass TzPathTest(TzPathUserMixin, ZoneInfoTestBase):\n module = py_zoneinfo\n\n @staticmethod\n @contextlib.contextmanager\n def python_tzpath_context(value):\n with EnvironmentVarGuard() as env:\n env[\"PYTHONTZPATH\"] = value\n yield\n\n def test_env_variable(self):\n \"\"\"Tests that the environment variable works with reset_tzpath.\"\"\"\n new_paths = [\n (\"\", []),\n (f\"{DRIVE}/etc/zoneinfo\", [f\"{DRIVE}/etc/zoneinfo\"]),\n (f\"{DRIVE}/a/b/c{os.pathsep}{DRIVE}/d/e/f\", [f\"{DRIVE}/a/b/c\", f\"{DRIVE}/d/e/f\"]),\n ]\n\n for new_path_var, expected_result in new_paths:\n with self.python_tzpath_context(new_path_var):\n with self.subTest(tzpath=new_path_var):\n self.module.reset_tzpath()\n tzpath = self.module.TZPATH\n self.assertSequenceEqual(tzpath, expected_result)\n\n def test_env_variable_relative_paths(self):\n test_cases = [\n [(\"path/to/somewhere\",), ()],\n [\n (f\"{DRIVE}/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (f\"{DRIVE}/usr/share/zoneinfo\",),\n ],\n [(\"../relative/path\",), ()],\n [\n (f\"{DRIVE}/usr/share/zoneinfo\", \"../relative/path\",),\n (f\"{DRIVE}/usr/share/zoneinfo\",),\n ],\n [(\"path/to/somewhere\", \"../relative/path\",), ()],\n [\n (\n f\"{DRIVE}/usr/share/zoneinfo\",\n \"path/to/somewhere\",\n \"../relative/path\",\n ),\n (f\"{DRIVE}/usr/share/zoneinfo\",),\n ],\n ]\n\n for input_paths, expected_paths in test_cases:\n path_var = os.pathsep.join(input_paths)\n with self.python_tzpath_context(path_var):\n with self.subTest(\"warning\", path_var=path_var):\n # Note: Per PEP 615 the warning is implementation-defined\n # behavior, other implementations need not warn.\n with self.assertWarns(self.module.InvalidTZPathWarning) as w:\n self.module.reset_tzpath()\n self.assertEqual(w.warnings[0].filename, __file__)\n\n tzpath = self.module.TZPATH\n with self.subTest(\"filtered\", path_var=path_var):\n self.assertSequenceEqual(tzpath, expected_paths)\n\n def test_env_variable_relative_paths_warning_location(self):\n path_var = \"path/to/somewhere\"\n\n with self.python_tzpath_context(path_var):\n with CleanImport(\"zoneinfo\", \"zoneinfo._tzpath\"):\n with self.assertWarns(RuntimeWarning) as w:\n import zoneinfo\n InvalidTZPathWarning = zoneinfo.InvalidTZPathWarning\n self.assertIsInstance(w.warnings[0].message, InvalidTZPathWarning)\n # It should represent the current file:\n self.assertEqual(w.warnings[0].filename, __file__)\n\n def test_reset_tzpath_kwarg(self):\n self.module.reset_tzpath(to=[f\"{DRIVE}/a/b/c\"])\n\n self.assertSequenceEqual(self.module.TZPATH, (f\"{DRIVE}/a/b/c\",))\n\n def test_reset_tzpath_relative_paths(self):\n bad_values = [\n (\"path/to/somewhere\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\",),\n (\"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"../relative/path\",),\n (\"path/to/somewhere\", \"../relative/path\",),\n (\"/usr/share/zoneinfo\", \"path/to/somewhere\", \"../relative/path\",),\n (FakePath(\"path/to/somewhere\"),)\n ]\n for input_paths in bad_values:\n with self.subTest(input_paths=input_paths):\n with self.assertRaises(ValueError):\n self.module.reset_tzpath(to=input_paths)\n\n def test_tzpath_type_error(self):\n bad_values = [\n \"/etc/zoneinfo:/usr/share/zoneinfo\",\n b\"/etc/zoneinfo:/usr/share/zoneinfo\",\n 0,\n (b\"/bytes/path\", \"/valid/path\"),\n (FakePath(b\"/bytes/path\"),),\n (0,),\n ]\n\n for bad_value in bad_values:\n with self.subTest(value=bad_value):\n with self.assertRaises(TypeError):\n self.module.reset_tzpath(bad_value)\n\n def test_tzpath_attribute(self):\n tzpath_0 = [f\"{DRIVE}/one\", f\"{DRIVE}/two\"]\n tzpath_1 = [f\"{DRIVE}/three\"]\n tzpath_pathlike = (FakePath(f\"{DRIVE}/usr/share/zoneinfo\"),)\n\n with self.tzpath_context(tzpath_0):\n query_0 = self.module.TZPATH\n\n with self.tzpath_context(tzpath_1):\n query_1 = self.module.TZPATH\n\n with self.tzpath_context(tzpath_pathlike):\n query_pathlike = self.module.TZPATH\n\n self.assertSequenceEqual(tzpath_0, query_0)\n self.assertSequenceEqual(tzpath_1, query_1)\n self.assertSequenceEqual(tuple([os.fspath(p) for p in tzpath_pathlike]), query_pathlike)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TzPathTest","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_03.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS\nfrom test.support.os_helper import EnvironmentVarGuard, FakePath\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\nfrom test.support.script_helper import assert_python_ok\n\n\nclass TestModule(ZoneInfoTestBase):\n module = py_zoneinfo\n\n @property\n def zoneinfo_data(self):\n return ZONEINFO_DATA\n\n @cached_property\n def _UTC_bytes(self):\n zone_file = self.zoneinfo_data.path_from_key(\"UTC\")\n with open(zone_file, \"rb\") as f:\n return f.read()\n\n def touch_zone(self, key, tz_root):\n \"\"\"Creates a valid TZif file at key under the zoneinfo root tz_root.\n\n tz_root must exist, but all folders below that will be created.\n \"\"\"\n if not os.path.exists(tz_root):\n raise FileNotFoundError(f\"{tz_root} does not exist.\")\n\n root_dir, *tail = key.rsplit(\"/\", 1)\n if tail: # If there's no tail, then the first component isn't a dir\n os.makedirs(os.path.join(tz_root, root_dir), exist_ok=True)\n\n zonefile_path = os.path.join(tz_root, key)\n with open(zonefile_path, \"wb\") as f:\n f.write(self._UTC_bytes)\n\n def test_getattr_error(self):\n with self.assertRaises(AttributeError):\n self.module.NOATTRIBUTE\n\n def test_dir_contains_all(self):\n \"\"\"dir(self.module) should at least contain everything in __all__.\"\"\"\n module_all_set = set(self.module.__all__)\n module_dir_set = set(dir(self.module))\n\n difference = module_all_set - module_dir_set\n\n self.assertFalse(difference)\n\n def test_dir_unique(self):\n \"\"\"Test that there are no duplicates in dir(self.module)\"\"\"\n module_dir = dir(self.module)\n module_unique = set(module_dir)\n\n self.assertCountEqual(module_dir, module_unique)\n\n def test_available_timezones(self):\n with self.tzpath_context([self.zoneinfo_data.tzpath]):\n self.assertTrue(self.zoneinfo_data.keys) # Sanity check\n\n available_keys = self.module.available_timezones()\n zoneinfo_keys = set(self.zoneinfo_data.keys)\n\n # If tzdata is not present, zoneinfo_keys == available_keys,\n # otherwise it should be a subset.\n union = zoneinfo_keys & available_keys\n self.assertEqual(zoneinfo_keys, union)\n\n def test_available_timezones_weirdzone(self):\n with tempfile.TemporaryDirectory() as td:\n # Make a fictional zone at \"Mars/Olympus_Mons\"\n self.touch_zone(\"Mars/Olympus_Mons\", td)\n\n with self.tzpath_context([td]):\n available_keys = self.module.available_timezones()\n self.assertIn(\"Mars/Olympus_Mons\", available_keys)\n\n def test_folder_exclusions(self):\n expected = {\n \"America/Los_Angeles\",\n \"America/Santiago\",\n \"America/Indiana/Indianapolis\",\n \"UTC\",\n \"Europe/Paris\",\n \"Europe/London\",\n \"Asia/Tokyo\",\n \"Australia/Sydney\",\n }\n\n base_tree = list(expected)\n posix_tree = [f\"posix/{x}\" for x in base_tree]\n right_tree = [f\"right/{x}\" for x in base_tree]\n\n cases = [\n (\"base_tree\", base_tree),\n (\"base_and_posix\", base_tree + posix_tree),\n (\"base_and_right\", base_tree + right_tree),\n (\"all_trees\", base_tree + right_tree + posix_tree),\n ]\n\n with tempfile.TemporaryDirectory() as td:\n for case_name, tree in cases:\n tz_root = os.path.join(td, case_name)\n os.mkdir(tz_root)\n\n for key in tree:\n self.touch_zone(key, tz_root)\n\n with self.tzpath_context([tz_root]):\n with self.subTest(case_name):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n\n def test_exclude_posixrules(self):\n expected = {\n \"America/New_York\",\n \"Europe/London\",\n }\n\n tree = list(expected) + [\"posixrules\"]\n\n with tempfile.TemporaryDirectory() as td:\n for key in tree:\n self.touch_zone(key, td)\n\n with self.tzpath_context([td]):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n\n def test_exclude_localtime(self):\n expected = {\n \"America/New_York\",\n \"Europe/London\",\n }\n\n tree = list(expected) + [\"localtime\"]\n\n with tempfile.TemporaryDirectory() as td:\n for key in tree:\n self.touch_zone(key, td)\n\n with self.tzpath_context([td]):\n actual = self.module.available_timezones()\n self.assertEqual(actual, expected)\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::TestModule","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_04.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS\nfrom test.support.os_helper import EnvironmentVarGuard, FakePath\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\nfrom test.support.script_helper import assert_python_ok\n\n\nclass MiscTests(unittest.TestCase):\n def test_pydatetime(self):\n # Test that zoneinfo works if the C implementation of datetime\n # is not available and the Python implementation of datetime is used.\n # The Python implementation of zoneinfo should be used in thet case.\n #\n # Run the test in a subprocess, as importing _zoneinfo with\n # _datettime disabled causes crash in the previously imported\n # _zoneinfo.\n assert_python_ok('-c', '''if 1:\n import sys\n sys.modules['_datetime'] = None\n import datetime\n import zoneinfo\n tzinfo = zoneinfo.ZoneInfo('Europe/London')\n datetime.datetime(2025, 10, 26, 2, 0, tzinfo=tzinfo)\n ''',\n PYTHONTZPATH=str(ZONEINFO_DATA.tzpath))\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::MiscTests","origin_revision":"v3.15.0","license":"PSF-2.0"} {"cut":"val","version":"3.15","idiom_id":"zoneinfo","pep":"615","introduced_in":"3.9","form":"modern","file":"zoneinfo/modern_05.py","code":"from __future__ import annotations\nimport base64\nimport contextlib\nimport dataclasses\nimport importlib.metadata\nimport io\nimport json\nimport os\nimport pathlib\nimport pickle\nimport re\nimport shutil\nimport struct\nimport tempfile\nimport unittest\nfrom datetime import date, datetime, time, timedelta, timezone\nfrom functools import cached_property\nfrom test.support import MISSING_C_DOCSTRINGS\nfrom test.support.os_helper import EnvironmentVarGuard, FakePath\nfrom test.test_zoneinfo import _support as test_support\nfrom test.test_zoneinfo._support import TZPATH_TEST_LOCK, ZoneInfoTestBase\nfrom test.support.import_helper import import_module, CleanImport\nfrom test.support.script_helper import assert_python_ok\n\n\nclass ExtensionBuiltTest(unittest.TestCase):\n \"\"\"Smoke test to ensure that the C and Python extensions are both tested.\n\n Because the intention is for the Python and C versions of ZoneInfo to\n behave identically, these tests necessarily rely on implementation details,\n so the tests may need to be adjusted if the implementations change. Do not\n rely on these tests as an indication of stable properties of these classes.\n \"\"\"\n\n def test_cache_location(self):\n # The pure Python version stores caches on attributes, but the C\n # extension stores them in C globals (at least for now)\n self.assertNotHasAttr(c_zoneinfo.ZoneInfo, \"_weak_cache\")\n self.assertHasAttr(py_zoneinfo.ZoneInfo, \"_weak_cache\")\n\n def test_gc_tracked(self):\n import gc\n\n self.assertTrue(gc.is_tracked(py_zoneinfo.ZoneInfo))\n self.assertTrue(gc.is_tracked(c_zoneinfo.ZoneInfo))\n","source":"cpython_tests","origin":"Lib/test/test_zoneinfo/test_zoneinfo.py::ExtensionBuiltTest","origin_revision":"v3.15.0","license":"PSF-2.0"}