Sunday, May 31, 2015

necromancy, lesson one

There is a dark, mysterious, and dangerous power of Necromancy in the Python language; used only at great peril: the __del__ method.  Consider this class:

>>> class Living(object):
...    def __del__(self):
...       undead_hoard.append(self)
...
>>> undead_hoard = []

Let's use it.

>>> a = Living()
>>> undead_hoard
[]

So far so good.  What happens if we delete one?

>>> del a
>>> undead_hoard
[<__main__.Living object at 0x020C01D0>]

The object got resurrected by __del__.  No problem, it can be removed from the list:

>>> del undead_hoard[0]
>>> undead_hoard
[<__main__.Living object at 0x020C01D0>]

Hmm, maybe reset the list?

>>> undead_hoard = []
>>> undead_hoard
[<__main__.Living object at 0x020C01D0>]

Lesson one of Python Necromancy: __del__ may be called many times on the same object; a safe __del__ must be re-entrant.  In this case, the resurrection was the fault of the __del__ method itself, but that is not always the case.