Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

A temporary quick fix for dataclass serialization (#500) #503

Merged
merged 4 commits into from
Jul 21, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
62 changes: 38 additions & 24 deletions dill/_dill.py
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,10 @@ def get_file_type(*args, **kwargs):
from collections import OrderedDict

import inspect
import dataclasses

from pickle import GLOBAL


### Shims for different versions of Python and dill
class Sentinel(object):
Expand Down Expand Up @@ -1826,30 +1830,13 @@ def save_dictproxy(pickler, obj):
pickler.save_reduce(DictProxyType, (mapping,), obj=obj)
log.info("# Mp")
return
elif not IS_PYPY:
if not OLD33:
@register(DictProxyType)
def save_dictproxy(pickler, obj):
log.info("Mp: %s" % obj)
pickler.save_reduce(DictProxyType, (obj.copy(),), obj=obj)
log.info("# Mp")
return
else:
# The following function is based on 'saveDictProxy' from spickle
# Copyright (c) 2011 by science+computing ag
# License: http://www.apache.org/licenses/LICENSE-2.0
@register(DictProxyType)
def save_dictproxy(pickler, obj):
log.info("Dp: %s" % obj)
attr = obj.get('__dict__')
#pickler.save_reduce(_create_dictproxy, (attr,'nested'), obj=obj)
if type(attr) == GetSetDescriptorType and attr.__name__ == "__dict__" \
and getattr(attr.__objclass__, "__dict__", None) == obj:
pickler.save_reduce(getattr, (attr.__objclass__,"__dict__"),obj=obj)
log.info("# Dp")
return
# all bad below... so throw ReferenceError or TypeError
raise ReferenceError("%s does not reference a class __dict__" % obj)
else:
@register(DictProxyType)
def save_dictproxy(pickler, obj):
log.info("Mp: %s" % obj)
pickler.save_reduce(DictProxyType, (obj.copy(),), obj=obj)
log.info("# Mp")
return

@register(SliceType)
def save_slice(pickler, obj):
Expand Down Expand Up @@ -2258,6 +2245,33 @@ def save_capsule(pickler, obj):
else:
_testcapsule = None


#############################
# A quick fix for issue #500
# This should be removed when a better solution is found.

if hasattr(dataclasses, "_HAS_DEFAULT_FACTORY_CLASS"):
@register(dataclasses._HAS_DEFAULT_FACTORY_CLASS)
def save_dataclasses_HAS_DEFAULT_FACTORY_CLASS(pickler, obj):
pickler.write(GLOBAL + b"dataclasses\n_HAS_DEFAULT_FACTORY\n")

if hasattr(dataclasses, "MISSING"):
@register(type(dataclasses.MISSING))
def save_dataclasses_MISSING_TYPE(pickler, obj):
pickler.write(GLOBAL + b"dataclasses\nMISSING\n")

if hasattr(dataclasses, "KW_ONLY"):
@register(type(dataclasses.KW_ONLY))
def save_dataclasses_KW_ONLY_TYPE(pickler, obj):
pickler.write(GLOBAL + b"dataclasses\nKW_ONLY\n")

if hasattr(dataclasses, "_FIELD_BASE"):
@register(dataclasses._FIELD_BASE)
def save_dataclasses_FIELD_BASE(pickler, obj):
pickler.write(GLOBAL + b"dataclasses\n" + obj.name.encode() + b"\n")

#############################

# quick sanity checking
def pickles(obj,exact=False,safe=False,**kwds):
"""
Expand Down
35 changes: 35 additions & 0 deletions tests/test_dataclasses.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/env python
#
# Author: Mike McKerns (mmckerns @caltech and @uqfoundation)
# Author: Anirudh Vegesana (avegesan@cs.stanford.edu)
# Copyright (c) 2022 The Uncertainty Quantification Foundation.
# License: 3-clause BSD. The full license text is available at:
# - https://github.com/uqfoundation/dill/blob/master/LICENSE
"""
test pickling a dataclass
"""

import dill
import dataclasses

def test_dataclasses():
# Issue #500
@dataclasses.dataclass
class A:
x: int
y: str

@dataclasses.dataclass
class B:
a: A

a = A(1, "test")
before = B(a)
save = dill.dumps(before)
after = dill.loads(save)
assert before != after # classes don't match
assert before == B(A(**dataclasses.asdict(after.a)))
assert dataclasses.asdict(before) == dataclasses.asdict(after)

if __name__ == '__main__':
test_dataclasses()
6 changes: 5 additions & 1 deletion tests/test_dictviews.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
# - https://github.com/uqfoundation/dill/blob/master/LICENSE

import dill
from dill._dill import OLD310, MAPPING_PROXY_TRICK
from dill._dill import OLD310, MAPPING_PROXY_TRICK, DictProxyType

def test_dictproxy():
assert dill.copy(DictProxyType({'a': 2}))

def test_dictviews():
x = {'a': 1}
Expand All @@ -31,5 +34,6 @@ def test_dictproxy_trick():
assert dict(seperate_views[1]) == new_x

if __name__ == '__main__':
test_dictproxy()
test_dictviews()
test_dictproxy_trick()