overload operator __rmul__ does not work

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
stmfresser
Posts: 22
Joined: Sat Jun 20, 2015 11:48 am

overload operator __rmul__ does not work

Post by stmfresser » Fri Aug 19, 2016 4:11 pm

i'm trying to test the overload operator __rmul__ on micropython, Unfortunately it does not work on micropython

Code: Select all

class foo:
    def __init__(self, data):
        self.data = data
    def __mul__(self, other):
        if type(other) in (int, float):
            return foo(self.data * other)
        else:
            return foo(self.data * other.data)
    def __rmul__(self, other):
        if type(other) in (int, float):
            return foo(self.data * other)
        else:
            return foo(self.data * other.data)

Code: Select all

if __name__ == '__main__':
    f1 = foo(10)
    f2 = foo(20)
    (f1*f2).data # 200
    (f1*50).data # 500
    (50*f1).data # it does not work on micropython

Code: Select all

>>> (50*f1).data                                                                
Traceback (most recent call last):                                              
  File "<stdin>", line 1, in <module>                                           
TypeError: unsupported types for __mul__: 'int', 'foo' 
I suppose __rmul__ has not implemented in micropython.

Does anyone know, how to solve it.

pfalcon
Posts: 1155
Joined: Fri Feb 28, 2014 2:05 pm

Re: overload operator __rmul__ does not work

Post by pfalcon » Fri Aug 19, 2016 4:25 pm

Sorry, none of the __r*__ methods are supported. MicroPython is intended to be a practical tool for (very) constrained systems, not a way to deal with abstractions-on-abstractions. In your case, an obvious way to resolve is:

Code: Select all

f1 = 10
50 * f1
If you really need to do that on objects, you of course can too:

Code: Select all

f1 = foo(10)
rmul(50, f1)
Awesome MicroPython list
Pycopy - A better MicroPython https://github.com/pfalcon/micropython
MicroPython standard library for all ports and forks - https://github.com/pfalcon/micropython-lib
More up to date docs - http://pycopy.readthedocs.io/

stmfresser
Posts: 22
Joined: Sat Jun 20, 2015 11:48 am

Re: overload operator __rmul__ does not work

Post by stmfresser » Fri Aug 19, 2016 5:01 pm

pfalcon wrote:Sorry, none of the __r*__ methods are supported.
Okay Thanks!

Post Reply