beginner's refcount questions

Fredrik Lundh fredrik at pythonware.com
Mon Oct 30 02:07:27 EST 2006


Jens Theisen wrote:

> Thus, the following code
> 
> class Foo:
>     def __del__(self):
>         print "deled!"
> 
> def foo():
>     f = Foo()
> 
> foo()
> print "done!"
> 
> prints
> 
> deled!
> done!
> 
> and not the other way round.

the behaviour you see in this simple program is not guaranteed by the 
language specification, and even trivial modifications to your program 
may cause trouble even under a reference-counting implementation of 
Python.  for example,

class Foo:
     def __del__(self):
         print "deled!"

def foo():
     f = Foo()
     i = open("file.txt")
     return i.readline()

try:
     foo()
except IOError:
     pass
print "done!"

prints

done!
deled!

> In c++, this is a central technique used for all sorts of tasks,
> whereas in garbage collected languages it's usually not available.

Python is not C++.  if you want to do controlled resource management, 
you need to use "try/finally" or "with".

> Is there a reason not to rely on this in Python? For example, are
> there alternative Python implementations that behave differently?  Or
> some other subtle problems?

http://www.effbot.org/pyfaq/how-does-python-manage-memory.htm
http://www.effbot.org/pyfaq/my-class-defines-del-but-it-is-not-called-when-i-delete-the-object.htm

</F>




More information about the Python-list mailing list