Is __mul__ sufficient for operator '*'?

Muhammad Alkarouri malkarouri at
Tue Oct 20 02:31:44 CEST 2009

Hi everyone,

I was having a go at a simple implementation of Maybe in Python when I
stumbled on a case where x.__mul__(y) is defined while x*y is not.

The class defining x is:

class Maybe(object):
    def __init__(self, obj):
        self.o = obj
    def __repr__(self):
        return 'Maybe(%s)' % object.__getattribute__(self, "o")
    def __getattribute__(self, name):
            o = object.__getattribute__(self, "o")
            r = getattr(o,name)
            if callable(r):
                f = lambda *x:Maybe(r(*x))
                return f
                return Maybe(r)
            return Maybe(None)

The code exercising this class is:

>>> x=Maybe(9)
>>> x.__mul__(7)
>>> x*7

Traceback (most recent call last):
  File "<pyshell#83>", line 1, in <module>
TypeError: unsupported operand type(s) for *: 'Maybe' and 'int'

The farthest I can go in this is that I presume that __mul__ (as
called by operator *) is supposed to be a bound method while I am
returning a lambda function. Is this correct? And How can I make the
implementation support such operators?


Muhammad Alkarouri

More information about the Python-list mailing list