Isue #5084: unpickling now interns the attribute names of pickled objects,
saving memory and avoiding growth in size of subsequent pickles. Proposal
and original patch by Jake McGuire.
diff --git a/Lib/pickle.py b/Lib/pickle.py
index abed1ca..8c5d51f 100644
--- a/Lib/pickle.py
+++ b/Lib/pickle.py
@@ -1221,7 +1221,15 @@
state, slotstate = state
if state:
try:
- inst.__dict__.update(state)
+ d = inst.__dict__
+ try:
+ for k, v in state.iteritems():
+ d[intern(k)] = v
+ # keys in state don't have to be strings
+ # don't blow up, but don't go out of our way
+ except TypeError:
+ d.update(state)
+
except RuntimeError:
# XXX In restricted execution, the instance's __dict__
# is not accessible. Use the old way of unpickling
diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py
index 4ffa702..bc0be1f 100644
--- a/Lib/test/pickletester.py
+++ b/Lib/test/pickletester.py
@@ -938,6 +938,20 @@
"Failed protocol %d: %r != %r"
% (proto, obj, loaded))
+ def test_attribute_name_interning(self):
+ # Test that attribute names of pickled objects are interned when
+ # unpickling.
+ for proto in protocols:
+ x = C()
+ x.foo = 42
+ x.bar = "hello"
+ s = self.dumps(x, proto)
+ y = self.loads(s)
+ x_keys = sorted(x.__dict__)
+ y_keys = sorted(y.__dict__)
+ for x_key, y_key in zip(x_keys, y_keys):
+ self.assertIs(x_key, y_key)
+
# Test classes for reduce_ex