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

Fix class cell in __new__ for metaclasses #468

Merged
merged 2 commits into from
May 8, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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: 7 additions & 1 deletion dill/_dill.py
Original file line number Diff line number Diff line change
Expand Up @@ -1589,7 +1589,13 @@ def save_cell(pickler, obj):
log.info("# Ce3")
return
if is_dill(pickler, child=True):
postproc = next(iter(pickler._postproc.values()), None)
if id(f) in pickler._postproc:
# Already seen. Add to its postprocessing.
postproc = pickler._postproc[id(f)]
else:
# Haven't seen it. Add to the highest possible object and set its
# value as late as possible to prevent cycle.
postproc = next(iter(pickler._postproc.values()), None)
mmckerns marked this conversation as resolved.
Show resolved Hide resolved
if postproc is not None:
log.info("Ce2: %s" % obj)
# _CELL_REF is defined in _shims.py to support older versions of
Expand Down
27 changes: 27 additions & 0 deletions tests/test_classdef.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,32 @@ def test_slots():
assert dill.pickles(Y.y)
assert dill.copy(y).y == value

def test_metaclass():
class metaclass_with_new(type):
def __new__(mcls, name, bases, ns, **kwds):
cls = super().__new__(mcls, name, bases, ns, **kwds)
mmckerns marked this conversation as resolved.
Show resolved Hide resolved
assert mcls is not None
assert cls.method(mcls)
return cls
def method(cls, mcls):
return isinstance(cls, mcls)

if dill._dill.PY3:
l = locals()
exec("""class subclass_with_new(metaclass=metaclass_with_new):
def __new__(cls):
self = super().__new__(cls)
return self""", None, l)
subclass_with_new = l['subclass_with_new']
else:
class subclass_with_new:
__metaclass__ = metaclass_with_new
def __new__(cls):
self = super().__new__(cls)
return self

assert dill.copy(subclass_with_new())


if __name__ == '__main__':
test_class_instances()
Expand All @@ -227,3 +253,4 @@ def test_slots():
test_array_subclass()
test_method_decorator()
test_slots()
test_metaclass()