Python Copyreg Module
The copyreg module provides support for the pickle module to customize the pickling of objects. It allows you to register functions used to pickle specific types, which is useful for handling objects that are not picklable by default or for customizing the serialization process.
Importing the Module
import copyreg
Registering a Pickle Function
To customize how a type is pickled, you use copyreg.pickle(). It takes the type to be customized and a function that returns a tuple containing the callable to reconstruct the object and the arguments for that callable.
Example
import copyreg
import pickle
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def pickle_point(p):
print("Pickling Point...")
# Return the constructor and arguments to recreate the object
return Point, (p.x, p.y)
# Register the function
copyreg.pickle(Point, pickle_point)
p = Point(10, 20)
dumped = pickle.dumps(p)
loaded = pickle.loads(dumped)
print(loaded) # Output: Point(10, 20)
constructor()
The copyreg.constructor() function declares that a function is a valid constructor. This is not strictly necessary if the function is a class, but can be useful for factory functions to ensure they are safe to use during unpickling.
copyreg.constructor(Point)