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 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
39 changes: 39 additions & 0 deletions dill/_dill.py
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,10 @@ def get_file_type(*args, **kwargs):
singletontypes = []

import inspect
import dataclasses

from pickle import GLOBAL


### Shims for different versions of Python and dill
class Sentinel(object):
Expand Down Expand Up @@ -2024,6 +2028,41 @@ 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):
logger.trace(pickler, "DcHDF: %s", obj)
pickler.write(GLOBAL + b"dataclasses\n_HAS_DEFAULT_FACTORY\n")
logger.trace(pickler, "# DcHDF")

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

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

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

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

# quick sanity checking
def pickles(obj,exact=False,safe=False,**kwds):
"""
Expand Down
13 changes: 13 additions & 0 deletions dill/_objects.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import collections
import codecs
import struct
import dataclasses
import datetime
import calendar
import weakref
Expand Down Expand Up @@ -493,6 +494,18 @@ class _Struct(ctypes.Structure):
d['PyCapsuleType'] = _testcapsule
del _testcapsule

if hasattr(dataclasses, '_HAS_DEFAULT_FACTORY'):
x['DataclassesHasDefaultFactoryType'] = dataclasses._HAS_DEFAULT_FACTORY

if hasattr(dataclasses, 'MISSING'):
x['DataclassesMissingType'] = dataclasses.MISSING

if hasattr(dataclasses, 'KW_ONLY'):
x['DataclassesKWOnlyType'] = dataclasses.KW_ONLY

if hasattr(dataclasses, '_FIELD_BASE'):
x['DataclassesFieldBaseType'] = dataclasses._FIELD

# -- cleanup ----------------------------------------------------------------
a.update(d) # registered also succeed
if sys.platform[:3] == 'win':
Expand Down
35 changes: 35 additions & 0 deletions dill/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()