beginner's refcount questions

Fredrik Lundh fredrik at
Mon Oct 30 08:07:27 CET 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()

except IOError:
print "done!"



> 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?


More information about the Python-list mailing list