Commit 557d1eb0 authored by Guido van Rossum's avatar Guido van Rossum

Issue #25665: Make NamedTuple picklable.

parent 05e3090e
......@@ -1163,6 +1163,14 @@ class NamedTupleTests(TestCase):
assert Emp._fields == ('name', 'id')
assert Emp._field_types == dict(name=str, id=int)
def test_pickle(self):
global Emp # pickle wants to reference the class by name
Emp = NamedTuple('Emp', [('name', str), ('id', int)])
jane = Emp('jane', 37)
z = pickle.dumps(jane)
jane2 = pickle.loads(z)
assert jane == jane2
class IOTests(TestCase):
......
......@@ -1479,6 +1479,11 @@ def NamedTuple(typename, fields):
fields = [(n, t) for n, t in fields]
cls = collections.namedtuple(typename, [n for n, t in fields])
cls._field_types = dict(fields)
# Set the module to the caller's module (otherwise it'd be 'typing').
try:
cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__')
except (AttributeError, ValueError):
pass
return cls
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment