Type emulation issues with new style classes

Rainer Deyke rainerd at eldwood.com
Sat Feb 28 19:37:06 EST 2004


Chris wrote:
> I'm looking for a way to do this without explicity definining every
> emulation method, i.e. (__str__, __lt__, __le__, __eq__, __ne__,
> __gt__, __ge__, __len__, __getitem__, __add__, __sub__, __mul__,
> __floordiv__, __mod__, __divmod__, __pow__, __lshift__, ... ad
> nausuem).

You can get away with mentioning all of those names only once in your code.

class IndirectionMixins(object):
  pass

def add_indirection_method(name):
  def f(self, *args, **kwargs):
    return self.__getattr__(name)(*args, **kwargs)
  setattr(IndirectionMixins, name, f)

for name in ['__str__', '__lt__', ...]:
  add_indirection_method(name)

class Y(IndirectionMixins):
  ...

>  Plus, there's a few this isn't going to work for several
> of the the arithmetic operators, such as when I want to have __add__
> undefined so Python will attpemt __radd__.

That's harder.  It might be possible with metaclasses.


-- 
Rainer Deyke - rainerd at eldwood.com - http://eldwood.com





More information about the Python-list mailing list