bpo-32873: Treat type variables and special typing forms as immutable… · python/cpython@d0e04c8
@@ -1057,20 +1057,20 @@ class C(B[int]):
10571057self.assertEqual(x.foo, 42)
10581058self.assertEqual(x.bar, 'abc')
10591059self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
1060-samples = [Any, Union, Tuple, Callable, ClassVar]
1060+samples = [Any, Union, Tuple, Callable, ClassVar,
1061+Union[int, str], ClassVar[List], Tuple[int, ...], Callable[[str], bytes]]
10611062for s in samples:
10621063for proto in range(pickle.HIGHEST_PROTOCOL + 1):
10631064z = pickle.dumps(s, proto)
10641065x = pickle.loads(z)
10651066self.assertEqual(s, x)
1066-more_samples = [List, typing.Iterable, typing.Type]
1067+more_samples = [List, typing.Iterable, typing.Type, List[int],
1068+typing.Type[typing.Mapping]]
10671069for s in more_samples:
10681070for proto in range(pickle.HIGHEST_PROTOCOL + 1):
10691071z = pickle.dumps(s, proto)
10701072x = pickle.loads(z)
1071-self.assertEqual(repr(s), repr(x)) # TODO: fix this
1072-# see also comment in test_copy_and_deepcopy
1073-# the issue is typing/#512
1073+self.assertEqual(s, x)
1074107410751075def test_copy_and_deepcopy(self):
10761076T = TypeVar('T')
@@ -1082,7 +1082,27 @@ class Node(Generic[T]): ...
10821082Union['T', int], List['T'], typing.Mapping['T', int]]
10831083for t in things + [Any]:
10841084self.assertEqual(t, copy(t))
1085-self.assertEqual(repr(t), repr(deepcopy(t))) # Use repr() because of TypeVars
1085+self.assertEqual(t, deepcopy(t))
1086+1087+def test_immutability_by_copy_and_pickle(self):
1088+# Special forms like Union, Any, etc., generic aliases to containers like List,
1089+# Mapping, etc., and type variabcles are considered immutable by copy and pickle.
1090+global TP, TPB, TPV # for pickle
1091+TP = TypeVar('TP')
1092+TPB = TypeVar('TPB', bound=int)
1093+TPV = TypeVar('TPV', bytes, str)
1094+for X in [TP, TPB, TPV, List, typing.Mapping, ClassVar, typing.Iterable,
1095+Union, Any, Tuple, Callable]:
1096+self.assertIs(copy(X), X)
1097+self.assertIs(deepcopy(X), X)
1098+self.assertIs(pickle.loads(pickle.dumps(X)), X)
1099+# Check that local type variables are copyable.
1100+TL = TypeVar('TL')
1101+TLB = TypeVar('TLB', bound=int)
1102+TLV = TypeVar('TLV', bytes, str)
1103+for X in [TL, TLB, TLV]:
1104+self.assertIs(copy(X), X)
1105+self.assertIs(deepcopy(X), X)
1086110610871107def test_copy_generic_instances(self):
10881108T = TypeVar('T')