[Python-checkins] bpo-38405: Make nested subclasses of typing.NamedTuple pickleable. (GH-16641)
Serhiy Storchaka
webhook-mailer at python.org
Tue Oct 8 09:29:58 EDT 2019
https://github.com/python/cpython/commit/13abda41003daf599587991d8291f0dacf6e9519
commit: 13abda41003daf599587991d8291f0dacf6e9519
branch: master
author: Serhiy Storchaka <storchaka at gmail.com>
committer: GitHub <noreply at github.com>
date: 2019-10-08T16:29:52+03:00
summary:
bpo-38405: Make nested subclasses of typing.NamedTuple pickleable. (GH-16641)
files:
A Misc/NEWS.d/next/Library/2019-10-08-11-18-40.bpo-38405.0-7e7s.rst
M Lib/test/test_typing.py
M Lib/typing.py
diff --git a/Lib/test/test_typing.py b/Lib/test/test_typing.py
index 97e6d88ebf70c..49417efe5111b 100644
--- a/Lib/test/test_typing.py
+++ b/Lib/test/test_typing.py
@@ -3468,6 +3468,9 @@ class D(UserName):
class NamedTupleTests(BaseTestCase):
+ class NestedEmployee(NamedTuple):
+ name: str
+ cool: int
def test_basics(self):
Emp = NamedTuple('Emp', [('name', str), ('id', int)])
@@ -3587,14 +3590,25 @@ def test_namedtuple_errors(self):
with self.assertRaises(TypeError):
NamedTuple('Emp', fields=[('name', str), ('id', int)])
- def test_pickle(self):
+ def test_copy_and_pickle(self):
global Emp # pickle wants to reference the class by name
- Emp = NamedTuple('Emp', [('name', str), ('id', int)])
- jane = Emp('jane', 37)
- for proto in range(pickle.HIGHEST_PROTOCOL + 1):
- z = pickle.dumps(jane, proto)
- jane2 = pickle.loads(z)
- self.assertEqual(jane2, jane)
+ Emp = NamedTuple('Emp', [('name', str), ('cool', int)])
+ for cls in Emp, CoolEmployee, self.NestedEmployee:
+ with self.subTest(cls=cls):
+ jane = cls('jane', 37)
+ for proto in range(pickle.HIGHEST_PROTOCOL + 1):
+ z = pickle.dumps(jane, proto)
+ jane2 = pickle.loads(z)
+ self.assertEqual(jane2, jane)
+ self.assertIsInstance(jane2, cls)
+
+ jane2 = copy(jane)
+ self.assertEqual(jane2, jane)
+ self.assertIsInstance(jane2, cls)
+
+ jane2 = deepcopy(jane)
+ self.assertEqual(jane2, jane)
+ self.assertIsInstance(jane2, cls)
class TypedDictTests(BaseTestCase):
diff --git a/Lib/typing.py b/Lib/typing.py
index 2c75a76964873..0e842ff9f2048 100644
--- a/Lib/typing.py
+++ b/Lib/typing.py
@@ -1593,7 +1593,7 @@ def _make_nmtuple(name, types):
'_fields', '_field_defaults', '_field_types',
'_make', '_replace', '_asdict', '_source')
-_special = ('__module__', '__name__', '__qualname__', '__annotations__')
+_special = ('__module__', '__name__', '__annotations__')
class NamedTupleMeta(type):
diff --git a/Misc/NEWS.d/next/Library/2019-10-08-11-18-40.bpo-38405.0-7e7s.rst b/Misc/NEWS.d/next/Library/2019-10-08-11-18-40.bpo-38405.0-7e7s.rst
new file mode 100644
index 0000000000000..ee346a30ec416
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2019-10-08-11-18-40.bpo-38405.0-7e7s.rst
@@ -0,0 +1 @@
+Nested subclasses of :class:`typing.NamedTuple` are now pickleable.
More information about the Python-checkins
mailing list