is there anybody using __del__ correctly??

Steven Bethard steven.bethard at gmail.com
Mon Aug 13 12:26:22 EDT 2007


Michele Simionato wrote:
> SPECIALMETHODS = ['__%s__' % name for name in
> '''
> abs add and call concat contains delitem delslice div eq floordiv ge
> getitem
> getslice gt iadd iand iconcat idiv ifloordiv ilshift imod imul index
> inv invert
> ior ipow irepeat irshift isub iter itruediv ixor le len lshift lt mod
> mul ne neg
> not or pos pow repeat repr rshift setitem setslice str sub truediv
> xor
> '''.split()]
> 
> def add_special_method(cls, name):
>     def meth(self, *args):
>         return getattr(self, name)(*args)
>     meth.__name__ = name
>     setattr(cls, name, meth)
> for name in SPECIALMETHODS:
>     add_special_method(Impostor, name)
> 
> In this way the Impostor can emulate even the special methods. Here is
> an example:
> 
>>>> class C(object):
> ...
> pass
> ...
>>>> c=Impostor(C())
>>>> print c
> <__main__.C object at 0x102a390>
> 
> Notice that the impostor is calling the __str__ method of C, so it
> really looks like a C object. Moreover
> 
>>>> c.__class__
> <class '__main__.C'>
> 
> and
> 
>>>> isinstance(c, C)
> True
> 
> so the Impostor is doing a damn pretty good job of imposture for C
> objects. Of course it does what it can, and it cannot impersonate C
> objects completely:
>
>>>> type(c)
> <class '__main__.Impostor'>
> 
> so code using checks like ``type(c) is C`` would break and the
> approach here cannot be considered more than a hack.

That's fun. =)

I don't really think it's too much of a hack either. ``type(c) is C`` is 
expected to fail for proxy classes, which is why everyone keeps getting 
told to use ``isinstance(c, C)`` instead.  In Py3K, when ``isinstance`` 
becomes overloadable, it's going to be even more of a mistake to write 
``type(c) is C``.

That said, I doubt I'd want to slow down all attribute access on my 
class just to do some cleanup, when it's probably better to just tell 
everyone to use a ``with`` block. ;-)

STeVe



More information about the Python-list mailing list