Overriding copy.deepcopy() for builtin type in Python 3

138 Views Asked by At

I want a deep copy of a large data structure, but I want to handle objects of type bytes in a different way. Basically, if it can be decoded as UTF-8, I want to copy it as a string, otherwise I want to calculate a hash and copy that instead of the real value. Seems like it ought to be easy enough to implement.

If bytes were a class I had control over, I could rewrite its __deepcopy__ function, but I don't. I also don't have the ability to make these objects a different class instead of bytes without a significant amount of effort, which I'm trying to avoid. Getting deepcopy to work in a different way seemed like a reasonable choice.

I tried to make a new class inheriting from copy, assuming deepcopy fell back on copy once it found a leaf node, but it's not implemented as a class. (I don't think my assumption was correct either.) I can't just implement a new function and fall back on deepcopy if the argument isn't a bytes object, because it'll never come back out to use my logic once it goes in.

Any ideas how I can solve this problem in a reasonably easy way?

0

There are 0 best solutions below