does python have useless destructors?

Marcus Alanen marcus.alanen at abo.fi
Sun Jun 13 09:54:46 EDT 2004



Hannu Kankaanpää wrote:

> It's not that simple when you compare it to C++ RAII idiom,
> and the above code is actually wrong. If open() raises an
> exception, myfile hasn't yet been assigned and myfile.close()
> will raise another, unwanted exception of type "NameError".
> The correct idiom is:
> 
> myfile = file("myfilepath", "w")
> try:
>     myfile.write(reallybigbuffer)
> finally:
>     myfile.close()

Does anybody know when "myfile" is created if it hasn't been introduced 
previously? I.e. is Python guaranteed to create the variable, call the 
function, then assign, or call the function, create variable, then 
assign? In the latter case, we (at least technically) have a very small 
chance that the creation of the variable fails, for some reason or the 
other.

By the way, in one of our projects we obviously use several different 
resources, so I wrote a simple/stupid script that checks for a resource 
acquisition (here "file"), immediately followed by an appropriate "try" 
followed at some point with "finally" and then a corresponding 
destructor call (here "close"). Simple, but finds lot's of errors.

Marcus



More information about the Python-list mailing list