Bug in __del__ function
dmq at gain.com
Thu Jun 24 04:49:21 CEST 2004
On 23 Jun 2004 21:22:59 -0400, Heather Coppersmith <me at privacy.net>
>On Wed, 23 Jun 2004 18:07:50 -0700,
>David MacQuigg <dmq at gain.com> wrote:
>> The example below is a repeatable test case. It might be possible to
>> simplify this further, but at this point, I haven't a clue as to why
>> it works with some sequences of commands, but not others.
>> I'm also not able to repeat the problem by putting the commands in the
>> file, and just running the file. Adding the necessary 'print'
>> keywords makes the problem go away. This could be just a problem in
>> IDLE, but unless I'm sure of that, I don't want to be using __del__ in
>> my programs.
>> Is this a bug, or have I misunderstood the use of __del__?
>[ code / interaction mostly snipped ]
>>>>> del cat1
>> <__main__.Cat object at 0x00A11F70>
>> sys.getrefcount(obj): 5 ### Should be one less.
>I'm not sure about that. The interactive prompt keeps a reference to
>the last thing it printed, which in this case was cat2. Perhaps IDLE
>has similar behavior? That would also explain why adding extra print
>statements and/or running from a file makes the problem go away.
Wow. This explains everything. The erratic behavior is all dependent
on what the interpreter sees as the current _ (underscore) reference.
Simply printing a value changes that reference and frees the deleted
>>> del cat2 ### nothing happens, because _ still references the object.
<__main__.Cat object at 0x00A11F70>
>>> 2 ### changes _ and immediately frees the object.
Deleting instance: <__main__.Cat object at 0x00A11F70>
Cat:0 Mammal:0 Animal:0
2 ### The deletion apparently occurs before the command finishes.
This will make a good example for the "Gotcha" section in my OOP
chapter. Thanks for your help.
More information about the Python-list