deepcopy and file object attributes
Dan Perl
dperl at rogers.com
Tue Sep 14 15:47:08 EDT 2004
Here is some code to illustrate a problem that I have:
import copy
class myc:
def __init__(self):
self.myf=file('bar.txt',"w")
def foo(self):
self.myf.write('hello world!') # it's going to fail for
d.foo( )
c = myc()
d = copy.deepcopy(c) # d.myf is created as closed
del c
d.foo() # ValueError: I/O operation on closed file
I figured out with a debugger that d.myf gets created as a file object that
is closed from the get-go. Is this the expected behavior? If so, is the
behavior due to the file object (its own __deepcopy__ method) or is the
behavior due to the deepcopy (it doesn't know how to get the file object
open)?
I already have a way to get around the problem, by overriding the
__deepcopy__ method. Any other suggestions?
I have seen many parallels being drawn between copy/deepcopy and pickle.
Are they sharing implementations? I can definitely see a problem with
pickle-ing an open file object, but I would normally expect a copy( ) to
also copy the state of the file object. Am I wrong about that?
Dan
More information about the Python-list
mailing list