← index #3592Issue #3205
Off-topic · high · value 0.338
QUERY · ISSUE

Assigning to __class__ fails without error

openby nickovsopened 2018-02-02updated 2021-05-11
py-core

In the standard Python implementation it is possible to assign to the __class__ attribute of an object. This means that the following code works:

class A:
    def __init__(self, x):
        self.x = x

class B(A):
    @property
    def y(self):
        return self.x*2

a = A(10)
a.__class__ = B
print(a.y)   # Prints 20

One can debate the desirability of this sort of code but it can be quite useful for cases such as unpacking structured data where part of the structure contains type information and you'd like to have different accessor methods for the fields depending on the type tag.

Anyway, whether you like this style or not, in MicroPython assigning to __class__ silently fails. While I'd personally prefer it to succeed at the very least if it's going to fail it should fail with a AttributeError saying that the attribute can't be set.

CANDIDATE · ISSUE

In case of multiple inheritance, super() might not find some parent methods

closedby dvrhaxopened 2017-07-09updated 2017-08-23

Discovered this issue while porting over PyMySQL to micropython both super() calling methods shown produce the same results

class a():
    def doSomething(self):
        print('Something done.')

class aMixin():
    def doSomething(self):
        #super(aMixin, self).doSomething()
        super().doSomething()
        print('Something Else.')

class b(aMixin, a):
    """Super Test Case"""

print('Class a:')
aa = a()
aa.doSomething()

print('Class b:')
bb = b()
bb.doSomething()

CPython prints:

Class a:
Something done.
Class b:
Something done.
Something Else.

However MicroPython produces the following error:

Class a:
Something done.
Class b:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "superTest.py", line 19, in <module>
File "superTest.py", line 7, in doSomething
AttributeError: 'super' object has no attribute 'doSomething'

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied