deepcopy and file object attributes

D

Dan Perl

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top