Search code examples
pythonpickle

Is Python's copyreg supposed to be used in regular Python code?


Python's copyreg documentation looks like it's just a way to customize the pickling of specific classes defined in Python.

However, a comment in its source code says that "This is only useful to add pickle support for extension types defined in C, not for instances of user-defined classes."

Is that really true? If so, it is odd that it's not mentioned in the actual documentation page.

If it is true, can it actually be used for customizing the pickling of user-defined Python classes?


Solution

  • The comment in the source code was added with this commit back in 2000. Interestingly if you notice the filename it is copy_reg.py not copyreg.py.

    copy_reg.py is the python 2 version and it has been been renamed to copyreg in python 3. Python 2 version of copy_reg does not support classes which is documented here.

    copy_reg.pickle(type, function[, constructor])

    Declares that function should be used as a “reduction” function for objects of type type; type must not be a “classic” class object. (Classic classes are handled differently;

    So I assume that the comment was intended for python 2 but was forgotten to be removed in python3. I think it's a good idea to create PR to remove this comment from the code.