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.

1 comment:

  1. Thanks for sharing those useful basic programming information, it helps me a lot to explore my knowledge in programming...if you want to switch your career in developing area you should know the basic of programmings for that you have to learn python, it was the first programming language.
    Python Training in Chennai|Python Training