I need to define my own deepcopy function for one of my classes. The documentation says that the function __deepcopy__() is passed a memo dictionary for tracking which objects have already been copied, to avoid getting caught in coping a recursive object. However it doesn’t say what to put in the dictionary. Do I put objects in, or object IDs? How do you use it? I can’t find any site that explains it, except this book that says that it need not be used, except to pass it to other invocations of __deepcopy__.
Thanks
To be consistent with the built-in
copy.deepcopybehavior, you should use theidof the object as a key.More Details:
While you can often get away with using a different key scheme (such as the object itself, if it’s hashable), as long as you’re consistent, you can still run into trouble. Frequently
__deepcopy__is implemented by callingcopy.deepcopyon some contained attributes. If you add items directly tomemo, you have to be certain the keys won’t collide with items added bycopy.deepcopy, which adds keys generated byid, which are integers.So if you use a different key scheme, such as using objects directly as keys, you can’t ever add any integer objects.
Bottom Line:
It’s much easier to just use
idand not have to worry about the exceptions above.