does python have useless destructors?

"Martin v. Löwis" martin at v.loewis.de
Sun Jun 13 14:22:35 EDT 2004


Marcus Alanen wrote:
>> 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? 

Neither, nor. Creation of the variable and assigning to it is an atomic
action for a global variable.

Local variables are created when the function starts.

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

In the example, the chance is very high that the variable does not get
set, i.e. if open() fails with an exception.

It *might* be that the assignment fails because it runs out of memory.

In either case, Python raises an exception, and subsequent statements
are not executed.

Regards,
Martin




More information about the Python-list mailing list