Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-32873: Treat type variables and special typing forms as immutable by copy and pickle #6216

Merged
merged 5 commits into from
Mar 26, 2018
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
25 changes: 19 additions & 6 deletions Lib/test/test_typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -1057,20 +1057,20 @@ class C(B[int]):
self.assertEqual(x.foo, 42)
self.assertEqual(x.bar, 'abc')
self.assertEqual(x.__dict__, {'foo': 42, 'bar': 'abc'})
samples = [Any, Union, Tuple, Callable, ClassVar]
samples = [Any, Union, Tuple, Callable, ClassVar,
Union[int, str], ClassVar[List], Tuple[int, ...], Callable[[str], bytes]]
for s in samples:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z = pickle.dumps(s, proto)
x = pickle.loads(z)
self.assertEqual(s, x)
more_samples = [List, typing.Iterable, typing.Type]
more_samples = [List, typing.Iterable, typing.Type, List[int],
typing.Type[typing.Mapping]]
for s in more_samples:
for proto in range(pickle.HIGHEST_PROTOCOL + 1):
z = pickle.dumps(s, proto)
x = pickle.loads(z)
self.assertEqual(repr(s), repr(x)) # TODO: fix this
# see also comment in test_copy_and_deepcopy
# the issue is typing/#512
self.assertEqual(s, x)

def test_copy_and_deepcopy(self):
T = TypeVar('T')
Expand All @@ -1082,7 +1082,20 @@ class Node(Generic[T]): ...
Union['T', int], List['T'], typing.Mapping['T', int]]
for t in things + [Any]:
self.assertEqual(t, copy(t))
self.assertEqual(repr(t), repr(deepcopy(t))) # Use repr() because of TypeVars
self.assertEqual(t, deepcopy(t))

def test_immutability_by_copy_and_pickle(self):
# Special forms like Union, Any, etc., generic aliases to containers like List,
# Mapping, etc., and type variabcles are considered immutable by copy and pickle.
global TP, TPB, TPV # for pickle
TP = TypeVar('TP')
TPB = TypeVar('TPB', bound=int)
TPV = TypeVar('TPV', bytes, str)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't see TPB and TPV mentioned in the for-loop below?

for X in [TP, List, typing.Mapping, ClassVar, typing.Iterable,
Union, Any, Tuple, Callable]:
self.assertIs(copy(X), X)
self.assertIs(deepcopy(X), X)
self.assertIs(pickle.loads(pickle.dumps(X)), X)

def test_copy_generic_instances(self):
T = TypeVar('T')
Expand Down
23 changes: 21 additions & 2 deletions Lib/typing.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,10 @@ def __hash__(self):
def __repr__(self):
return 'typing.' + self._name

def __copy__(self):
def __reduce__(self):
return self._name

def __deepcopy__(self, memo):
return self # Special forms are immutable.

def __call__(self, *args, **kwds):
Expand Down Expand Up @@ -496,6 +499,10 @@ def __repr__(self):
return f'ForwardRef({self.__forward_arg__!r})'


def _find_name(mod, name):
return getattr(sys.modules[mod], name)


class TypeVar(_Final, _root=True):
"""Type variable.

Expand Down Expand Up @@ -539,7 +546,7 @@ def longest(x: A, y: A) -> A:
"""

__slots__ = ('__name__', '__bound__', '__constraints__',
'__covariant__', '__contravariant__')
'__covariant__', '__contravariant__', '_def_mod')

def __init__(self, name, *constraints, bound=None,
covariant=False, contravariant=False):
Expand All @@ -558,6 +565,7 @@ def __init__(self, name, *constraints, bound=None,
self.__bound__ = _type_check(bound, "Bound must be a type.")
else:
self.__bound__ = None
self._def_mod = sys._getframe(1).f_globals['__name__'] # for pickling
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the type variable is defined in some non-global scope (even inside a class) this won't work. I think that's fine (we need to support those type variables but they don't need to be picklable) but I wonder if this deserves at least a mention in the docstring.

I also notice that for the same reason a type variable defined in some non-global scope cannot be copy()'s, but it can be deepcopy()'d. That seems a little weird.


def __getstate__(self):
return {'name': self.__name__,
Expand All @@ -582,6 +590,12 @@ def __repr__(self):
prefix = '~'
return prefix + self.__name__

def __reduce__(self):
return (_find_name, (self._def_mod, self.__name__))

def __deepcopy__(self, memo):
return self


# Special typing constructs Union, Optional, Generic, Callable and Tuple
# use three special attributes for internal bookkeeping of generic types:
Expand Down Expand Up @@ -724,6 +738,11 @@ def __subclasscheck__(self, cls):
raise TypeError("Subscripted generics cannot be used with"
" class and instance checks")

def __reduce__(self):
if self._special:
return self._name
return super().__reduce__()


class _VariadicGenericAlias(_GenericAlias, _root=True):
"""Same as _GenericAlias above but for variadic aliases. Currently,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
Treat type variables and special typing forms as immutable by copy and
pickle. This fixes several minor issues and inconsistencies, and improves
backwards compatibility with Python 3.6.