Object destruction delayed on interactive prompt
python at mrabarnett.plus.com
Sun Jan 25 20:13:23 CET 2015
On 2015-01-25 18:23, Mario Figueiredo wrote:
> Consider the following class:
> class A:
> def __init__(self, value):
> self.value = value
> def __del__(self):
> print("'A' instance being collected...")
> def __repr__(self):
> return str(self.value)
> If ran as a script, the destructor behavior works as expected:
> if __name__ == '__main__':
> x1 = A(12)
> print(x1) # __repr__()
> x1 = 2 # __del__()
> But if I run it interactively, a weird behavior comes up:
> >>> x1 = A(12)
> >>> x1 = 'string'
> A instance being collected... # __del__() as expected
> >>> x1 = A(12) # Recreate x1
> >>> x1 # __repr__()
> >>> x1 = 'string' # __del__() isn't executed!
> >>> x1 # it is delayed until here
> A instance being collected...
> This is reproducible in IDLE and at the system command prompt. Is this a
> REPL specific behavior?
In the REPL, the result of an expression is bound to '_':
>>> x1 = A(12)
>>> x1 # _ will be bound to the result.
>>> x1 = 'string'
>>> # At this point, _ is still bound to the object.
>>> 0 # This will bind _ to another object, so the previous object can
'A' instance being collected...
More information about the Python-list