summaryrefslogtreecommitdiffstats
path: root/Lib
diff options
context:
space:
mode:
authorAntoine Pitrou <solipsis@pitrou.net>2011-10-04 07:23:04 (GMT)
committerAntoine Pitrou <solipsis@pitrou.net>2011-10-04 07:23:04 (GMT)
commitffd41d9f101e31973b8713e884c95118fceb6f59 (patch)
tree3b549e20b5cf09244789f6e6f67a7dce2fad75b4 /Lib
parent1efb33a6823b94739e59d6e2fe92e8e703a7fc7d (diff)
downloadcpython-ffd41d9f101e31973b8713e884c95118fceb6f59.zip
cpython-ffd41d9f101e31973b8713e884c95118fceb6f59.tar.gz
cpython-ffd41d9f101e31973b8713e884c95118fceb6f59.tar.bz2
Issue #7689: Allow pickling of dynamically created classes when their
metaclass is registered with copyreg. Patch by Nicolas M. ThiƩry and Craig Citro.
Diffstat (limited to 'Lib')
-rw-r--r--Lib/pickle.py18
-rw-r--r--Lib/test/pickletester.py21
2 files changed, 30 insertions, 9 deletions
diff --git a/Lib/pickle.py b/Lib/pickle.py
index 32ae02b..c770ff8 100644
--- a/Lib/pickle.py
+++ b/Lib/pickle.py
@@ -299,20 +299,20 @@ class _Pickler:
f(self, obj) # Call unbound method with explicit self
return
- # Check for a class with a custom metaclass; treat as regular class
- try:
- issc = issubclass(t, type)
- except TypeError: # t is not a class (old Boost; see SF #502085)
- issc = 0
- if issc:
- self.save_global(obj)
- return
-
# Check copyreg.dispatch_table
reduce = dispatch_table.get(t)
if reduce:
rv = reduce(obj)
else:
+ # Check for a class with a custom metaclass; treat as regular class
+ try:
+ issc = issubclass(t, type)
+ except TypeError: # t is not a class (old Boost; see SF #502085)
+ issc = False
+ if issc:
+ self.save_global(obj)
+ return
+
# Check for a __reduce_ex__ method, fall back to __reduce__
reduce = getattr(obj, "__reduce_ex__", None)
if reduce:
diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py
index c2ed0d2..a22acc0 100644
--- a/Lib/test/pickletester.py
+++ b/Lib/test/pickletester.py
@@ -121,6 +121,19 @@ class metaclass(type):
class use_metaclass(object, metaclass=metaclass):
pass
+class pickling_metaclass(type):
+ def __eq__(self, other):
+ return (type(self) == type(other) and
+ self.reduce_args == other.reduce_args)
+
+ def __reduce__(self):
+ return (create_dynamic_class, self.reduce_args)
+
+def create_dynamic_class(name, bases):
+ result = pickling_metaclass(name, bases, dict())
+ result.reduce_args = (name, bases)
+ return result
+
# DATA0 .. DATA2 are the pickles we expect under the various protocols, for
# the object returned by create_data().
@@ -695,6 +708,14 @@ class AbstractPickleTests(unittest.TestCase):
b = self.loads(s)
self.assertEqual(a.__class__, b.__class__)
+ def test_dynamic_class(self):
+ a = create_dynamic_class("my_dynamic_class", (object,))
+ copyreg.pickle(pickling_metaclass, pickling_metaclass.__reduce__)
+ for proto in protocols:
+ s = self.dumps(a, proto)
+ b = self.loads(s)
+ self.assertEqual(a, b)
+
def test_structseq(self):
import time
import os