(original) (raw)
changeset: 99213:8a32d44b8359 parent: 99211:312a2220100c parent: 99212:33df0056c148 user: Guido van Rossum guido@dropbox.com date: Thu Nov 19 08:16:52 2015 -0800 files: Lib/test/test_typing.py Lib/typing.py description: Issue #25665: Make NamedTuple picklable. (Merge 3.5->3.6) diff -r 312a2220100c -r 8a32d44b8359 Lib/test/test_typing.py --- a/Lib/test/test_typing.py Wed Nov 18 21:19:18 2015 -0800 +++ b/Lib/test/test_typing.py Thu Nov 19 08:16:52 2015 -0800 @@ -1163,6 +1163,14 @@ 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): diff -r 312a2220100c -r 8a32d44b8359 Lib/typing.py --- a/Lib/typing.py Wed Nov 18 21:19:18 2015 -0800 +++ b/Lib/typing.py Thu Nov 19 08:16:52 2015 -0800 @@ -1479,6 +1479,11 @@ 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 /guido@dropbox.com