reference counting and file objects

"Martin v. Löwis" martin at v.loewis.de
Tue May 24 18:07:56 EDT 2005


Paul Rubin wrote:
>>>lines = file("myfile","r").readlines()
> 
> It's released even if the exception is raised inside readlines?

I think so, but only because readlines is a builtin function.
If it wasn't, there would be a stack frame for readlines, which
would have "self" as a local variable.

As readlines is builtin, it will not make it into the traceback.
So the reference to the file would be only on the evaluation
stack, at first, but that then gets copied into the argument
tuple. The argument tuple, in turn, is released in the process
of unwinding (again, it wouldn't if readlines wasn't builtin).

I might be wrong, but I think the following trace shows that
this is what happens:

>>> class F:
...   def __del__(self):print "released"
...
>>> len(F())
released
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: F instance has no attribute '__len__'

Compare this to a Python function:

>>> def len2(o): raise Exception
...
>>> len2(F())
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 1, in len2
Exception
>>> raise ""
released
Traceback (most recent call last):
  File "<stdin>", line 1, in ?

However, this analysis also shows that it is quite delicate
to rely on this pattern.

Regards,
Martin



More information about the Python-list mailing list