Method returning new instance of class?

"Martin v. Löwis" martin at v.loewis.de
Tue Sep 7 16:29:15 EDT 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 copy.py 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.name, 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()
'root:x:0:0:root:/root:/bin/bash\n'
 >>> g=copy.copy(f)
 >>> g
<open file '/etc/passwd', mode 'r' at 0x401f7060>
 >>> g.readline()
'root:x:0:0:root:/root:/bin/bash\n'

Regards,
Martin




More information about the Python-list mailing list