0

I have a standard Bunch class:

class Bunch(dict):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.__dict__ = self

This results in an attribute error:

a = Bunch(b=1)
a = copy.deepcopy(a)
a.b

Which does not make sense to me. The deepcopy() function destroys the functionality of Bunch.

But the really weird part is that adding more complexity fixes it, seemingly by accident:

I am using Jupyter Lab to run things. The following works without error:

a = Bunch(b=1)
%store a
%store -r a
a = copy.deepcopy(a)
a.b

Why?

Florian Dietz
  • 877
  • 9
  • 20
  • The reason for the original problem is that `deepcopy()` doesn't know that it should keep `__dict__` as a reference to `self`. – Barmar Jul 22 '20 at 15:43
  • Part of the "magic" of storemagic is that it detects circular references and recreates them. But I'm not sure why that magic persists. – Barmar Jul 22 '20 at 15:44
  • Shouldn't deepcopy() also detect circular references like this? Isn't that the whole point of the algorithm? – Florian Dietz Jul 22 '20 at 21:30
  • You may be right. The documentation mentions that it keeps track of which objects it has copied to prevent getting into a recursive loop. Anyway, I think you may need to provide a custom `__deepcopy__` method for your class. – Barmar Jul 22 '20 at 21:35
  • See https://docs.python.org/3.8/library/copy.html – Barmar Jul 22 '20 at 21:35

0 Answers0