execfile question [+Q: why doesn't del dict imply dict.clear() ??]

Bengt Richter bokr at oz.net
Tue Feb 19 22:20:45 EST 2002


On Tue, 19 Feb 2002 12:51:10 GMT, Mark Barclay <markabarclay at attbi.com> wrote:
>Kerim Borchaev wrote:
>
>> Can someone explain why while running this script I don't see C.__del__
>> eventually called?
>>
>> For me the output of it's execution is:
>>
>> >main.py
>> it's me
>> init
>> executed
>> >
>>
>> ##main.py######################
>> execfile('executable.py', {})
>> print 'executed'
>> ########################
>>
>> ##executable.py######################
>> print "it's me"
>> class C:
>>     def __init__(self):
>>         print 'init'
>>     def __del__(self):
>>         print 'deleted'
>>
>> c = C()
>> ########################
>>
>> Thanks in advance.
>
[changing Mark's top-post to bottom]

>"del c" will cause your __del__() to be called.
>So will any other action that causes your instance to be garbage-collected.
>
[...example snipped...]

I think he's asking why finishing execfile is not one of those
'other actions'.

I think the contents of the anonymous dictionary he passed are not
automatically deleted (why not?) when it goes away, so a reference
in it is keeping the c instance from being collected.

Try not passing a dictionary, or pass one with a name and empty it
explicitly when you get control back. E.g.,
 >> ##main.py######################
    d={}
 >> execfile('executable.py', d)
    d.clear()
 >> print 'executed'
 >> ########################


BTW, Just deleting the dictionary (say del d) does not seem
to imply d.clear(), and hence just del d won't trigger the c destructor.

Is that correct python behavior??

Regards,
Bengt Richter




More information about the Python-list mailing list