You should not be accessing __dict__
directly at all.
Use a __getattr__
method to proxy calls to the underlying self._file
object instead:
class File(object):
def __init__(self, *args):
self._file = open(*args)
def __getattr__(self, name):
return getattr(self._file, name)
I've also switched the code to best-practices; using self
instead of this
and using open()
instead of file()
.
For new-style objects (inheriting from object
), use setattr()
to set arbitrary attributes. There is no need to use a call forwarder wrapper, however. You could have taken the bound methods of self._file
and set those directly on self
too:
class File(object):
def __init__(self, *args):
self._file = open(*args)
for name in dir(self._file):
setattr(self, name, getattr(self._file, name))
If all you wanted was a file object that auto-closes on garbage collection, then you went through a lot of trouble for nothing. Python file objects already have a __del__
handler that does exactly that. It is just not exposed as an explicit __del__
function, instead the C implementation uses a deallocation function that calls close_the_file(f)
when deallocated.
Best practice, however, is to use file objects as context manager, using the with
statement:
with open(somefilename) as fileobj:
# do all sorts with fileobj
# here, fileobj will have been closed automatically.
Quoting from the file.close()
documentation:
As of Python 2.5, you can avoid having to call this method explicitly if you use the with statement. For example, the following code will automatically close f when the with
block is exited:
from __future__ import with_statement # This isn't required in Python 2.6
with open("hello.txt") as f:
for line in f:
print line,