Java final vs Py __del__
gh at ghaering.de
Thu Nov 27 13:19:31 CET 2003
python-dev is the wrong place for this question, so I'll answer your
question on python-list instead.
Kepes Krisztian wrote:
> Hi !
> I very wonder, when I get exp. in java with GC. [...]
> In the Py the __del__ is same java's final, or it is to be called in
> every way by GC ?
Python's __del__ and Java's finalizers are serving the same purpose and
they're pretty much equivalent.
Java usually has generational garbage collection, with a separate
Garbage Collector thread that collect's garbage whenever it thinks it's
necessary and the CPU resources are available.
Python in its CPython implementation has a predictable garbage
collection, but this is not guaranteed to stay this way.
So Python makes no guarantees about when your objects really get
collected, once their refcount reaches zero (i. e. no more references to
the object). For you as an API designer this means that you best provide
a close/destroy method to make it possible to let the necessary cleanup
Especially if you want to create code that runs on CPython and Jython,
you cannot depend on the current implementation of CPython's
(predictable) garbage collection.
Additionally, you can call the cleanup routine in the __del__, in case
the programmer forgot to call it. Just like you did below:
> I build this method as safe method: if the programmer don't do any
> closing/freeing thing, I do that ?
> simple example:
> class a:
> def __init__(self,filename):
> def open(self):
> def write(self,data):
> def close(self):
> def __del__(self):
> if self.__file<>None:
> # like destructor: we do the things are forgotten by
Two more hints:
I strongly recommend you compare to None using the "is" operator, like
this: "if self.__file is not None". This is idiomatic, safer, and faster
than the <> operator.
You *could* also use "if not self.__file", because if __file is None, it
evaluates to "false" in the context of "if" or "while".
From the standard types, None, 0, 0.0, , "", () all evaluate to
"false", while everything else evaluates to "true" in boolean
 custom classes can implement the __nonzero__ special method to
return their value in a boolean context.
More information about the Python-list