Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
0.7.0
=====

- Correctly serialize dynamically defined classes that have a `__slots__`
attribute.
([issue #225](https://github.com/cloudpipe/cloudpickle/issues/225))


0.6.1
=====

Expand Down
12 changes: 12 additions & 0 deletions cloudpickle/cloudpickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@
import importlib
import itertools
import traceback
import six
from functools import partial


Expand Down Expand Up @@ -500,6 +501,17 @@ def save_dynamic_class(self, obj):
# doc can't participate in a cycle with the original class.
type_kwargs = {'__doc__': clsdict.pop('__doc__', None)}

if hasattr(obj, "__slots__"):
type_kwargs['__slots__'] = obj.__slots__
# pickle string length optimization: member descriptors of obj are
# created automatically from obj's __slots__ attribute, no need to
# save them in obj's state
if isinstance(obj.__slots__, six.string_types):
clsdict.pop(obj.__slots__)
else:
for k in obj.__slots__:
clsdict.pop(k, None)

# If type overrides __dict__ as a property, include it in the type kwargs.
# In Python 2, we can't set this attribute after construction.
__dict__ = clsdict.pop('__dict__', None)
Expand Down
17 changes: 17 additions & 0 deletions tests/cloudpickle_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1310,6 +1310,23 @@ def g(x):

self.assertEqual(f2.__annotations__, f.__annotations__)

def test_instance_with_slots(self):
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lg2m, thank you so much for taking this on!

for slots in [["registered_attribute"], "registered_attribute"]:
class ClassWithSlots(object):
__slots__ = slots

def __init__(self):
self.registered_attribute = 42

initial_obj = ClassWithSlots()
depickled_obj = pickle_depickle(
initial_obj, protocol=self.protocol)

for obj in [initial_obj, depickled_obj]:
self.assertEqual(obj.registered_attribute, 42)
with pytest.raises(AttributeError):
obj.non_registered_attribute = 1


class Protocol2CloudPickleTest(CloudPickleTest):

Expand Down