Java final vs Py __del__

Gerhard Häring gh at ghaering.de
Thu Nov 27 07:19:31 EST 2003


Krisztian,

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 
be done.

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):
>           self.__filename=filename
>           self.__data=[]
>           self.__file=None
>       def open(self):
>           self.__file=open(self.__filename,"w")
>       def write(self,data):
>           self.__data.append(data)
>       def close(self):
>           self.__file.writelines(self.__data)
>           self.__file.close()
>           self.__file=None
>       def __del__(self):
>           if self.__file<>None:
>              self.close()
>           # like destructor: we do the things are forgotten by
>           programmer

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 
expressions. [1]

HTH,

-- Gerhard

[1] custom classes can implement the __nonzero__ special method to 
return their value in a boolean context.






More information about the Python-list mailing list