Issue #25665: Make NamedTuple picklable. · python/typing@3819cbc (original) (raw)
2 files changed
lines changed
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1163,6 +1163,14 @@ def test_basics(self): | ||
1163 | 1163 | assert Emp._fields == ('name', 'id') |
1164 | 1164 | assert Emp._field_types == dict(name=str, id=int) |
1165 | 1165 | |
1166 | +def test_pickle(self): | |
1167 | +global Emp # pickle wants to reference the class by name | |
1168 | +Emp = NamedTuple('Emp', [('name', str), ('id', int)]) | |
1169 | +jane = Emp('jane', 37) | |
1170 | +z = pickle.dumps(jane) | |
1171 | +jane2 = pickle.loads(z) | |
1172 | +assert jane == jane2 | |
1173 | + | |
1166 | 1174 | |
1167 | 1175 | class IOTests(TestCase): |
1168 | 1176 |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1479,6 +1479,11 @@ def NamedTuple(typename, fields): | ||
1479 | 1479 | fields = [(n, t) for n, t in fields] |
1480 | 1480 | cls = collections.namedtuple(typename, [n for n, t in fields]) |
1481 | 1481 | cls._field_types = dict(fields) |
1482 | +# Set the module to the caller's module (otherwise it'd be 'typing'). | |
1483 | +try: | |
1484 | +cls.__module__ = sys._getframe(1).f_globals.get('__name__', '__main__') | |
1485 | +except (AttributeError, ValueError): | |
1486 | +pass | |
1482 | 1487 | return cls |
1483 | 1488 | |
1484 | 1489 |