Page 1 of 1
Overriding special methods
Posted: Fri Jan 27, 2017 11:40 am
by AaronKelly
Hello all,
I was wondering if anyone has had any luck implementing the special method __pow__? I tried searching for others implementation and tried adding c extension code for the objxxx.c files but when trying to override the object in the class initiator I get the following:
Code: Select all
> import CustomList
> a = CustomList(1,2,3)
> a**2
>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported types for <listcomp>: 'CustomList', 'int'
Re: Overriding special methods
Posted: Fri Jan 27, 2017 5:42 pm
by pythoncoder
It looks as if the special method hasn't been implemented. This works, returning 8:
Code: Select all
class Foo():
def __init__(self, v):
self.v = v
def __mul__(self, val):
return self.v * val
f = Foo(4)
f * 2
but this doesn't:
Code: Select all
class Bar():
def __init__(self, v):
self.v = v
def __pow__(self, val):
return self.v ** val
f = Bar(4)
f ** 2
throwing
Code: Select all
Traceback (most recent call last):
File "<stdin>", line 8, in <module>
TypeError: unsupported types for : 'Bar', 'int'
>>>
You might want to raise it on GitHub.
Re: Overriding special methods
Posted: Fri Jan 27, 2017 8:39 pm
by AaronKelly
Thanks for the feedback @pythoncoder
I found the piece of code that allows for power overloading in objtype.c and replacing
Code: Select all
[MP_BINARY_OP_POWER]
[MP_BINARY_OP_INPLACE_POWER]
for
Code: Select all
[MP_BINARY_OP_POWER] = MP_QSTR___pow__,
[MP_BINARY_OP_INPLACE_POWER] = MP_QSTR___iadd__,
however the only issue now is that when I try with objects that shouldn't have a power I get
Code: Select all
TypeError: unsupported types for __pow__: 'tuple', 'int'
Instead of say
Code: Select all
TypeError: unsupported types for **: 'tuple', 'int'
Re: Overriding special methods
Posted: Sat Jan 28, 2017 6:08 am
by pythoncoder
I see you've raised this on GitHub so doubtless the maintainers will comment.
In your original post you refer to a CustomList class. I don't know if you're subclassing a list here, but if so be aware that MicroPython support for subclassing built-in types is limited.
https://github.com/micropython/micropyt ... ifferences Obviously it's irrelevant to the ** problem but I thought it worth a mention.
Re: Overriding special methods
Posted: Sat Jan 28, 2017 9:22 am
by AaronKelly
The overloading of builtin types was just an example to show the error in the error message as it refers to the binary operation as __pow__ instead of **.