copyreg — Registering pickle support functions

Python Methods and Functions

copyreg.constructor (object)
This function is used to declare an object as a valid constructor. An object is not considered a valid constructor if it is not called. This function raises a TypeError if the object cannot be called.

copyreg.pickle (type, function, constructor = none)
This is used to declare a function as a function " abbreviations "for objects of type type. The function must return either a string or a tuple containing two or three elements. 
The constructor parameter is optional. It is a callable object that can be used to restore an object when called with a set of arguments returned by the function during fetch. A TypeError is thrown if the object is a class or the constructor cannot be called.


# Python 3 program for illustration
use of copyreg module

import copyreg, copy, pickle

class C ( object ):

def __ init __ ( self , a):

self . a = a


def pickle_c (c):

print ( "pickling a C instance ..." )

  return C , (ca,)

copyreg.pickle (C, pickle_c)

c = C ( 1 )

d = copy.copy (c)

print (d)


p = pickle.dumps (c)

print (p)


 pickling a C instance ... pickling a C instance ... b'x80x03c__main__ C qx00Kx01x85qx01Rqx02.' 

This article courtesy of Aditi Gupta . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting the article [email protected] ... See my article appearing on the Python.Engineering homepage and help other geeks.

Please write in comments if you find anything wrong or if you'd like to share more information on the topic discussed above.