Method returning new instance of class?

"Martin v. Löwis" martin at
Tue Sep 7 22:29:15 CEST 2004

Arthur wrote:
> """The copy module does not use the copy_reg registration module.""" 
> This is actually pretty esoteric stuff for someone who has not delved
> into these mysteries before, so I am a bit lost.

It appears that this documentation is incorrect. Just look at the
source of and see for yourself:

from copy_reg import dispatch_table

def copy(x):
     reductor = dispatch_table.get(cls)

> Is it that copy_reg comes into play in defining a custom method for
> copying, that is called as a regular method, and not via the copy
> module?

It is a customization of the copy module.

> Does anyone have a reference for copy_reg used in the specific context
> of copying, rather than pickling?

Sure: Assume you want to copy file objects, and that this should create
a file object for the same file name and mode, but starting from the
beginning. You do

def copy_file(f):
   return file, (, f.mode)
copy_reg.pickle(file, copy_file, file)

Then you can do

 >>> f=open("/etc/passwd","r")
 >>> f
<open file '/etc/passwd', mode 'r' at 0x401f7760>
 >>> f.readline()
 >>> g=copy.copy(f)
 >>> g
<open file '/etc/passwd', mode 'r' at 0x401f7060>
 >>> g.readline()


More information about the Python-list mailing list