Subclassing native classes

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
agonnen
Posts: 27
Joined: Sat Oct 13, 2018 7:52 pm

Subclassing native classes

Post by agonnen » Fri Jan 04, 2019 8:58 pm

I would like to know what is the status of Subclassing native classes in Micropython.
Specifically, I have a C library which I expose in Micropython, and would like to subclass its objects in Micropython.
The official docs only mention that "Subclassing native classes is not fully supported in MicroPython" (https://micropython.org/resources/docs/ ... types.html).

Does anyone know what is actually supported and what is not when subclassing a native type or classes from a user added module?

Maksym Galemin
Posts: 11
Joined: Mon May 28, 2018 11:48 pm

Re: Subclassing native classes

Post by Maksym Galemin » Mon Jan 14, 2019 11:21 am

As per the Exception.__init__ method does not exist. item I think the limitation is that you should use super().__init__() instead of BaseNativeClass.__init__() in constructors of your subclasses derived from native classes. And I guess you should check native_base_init_wrapper() function from py/objtype.c for details (or just search for "native_base" in this file and check the code). But I might be wrong... :)

In any case it would be better if you could include an example of your subclasses derived from native uPy classes as it's much easier to deal with some specific cases rather than describing all possible scenarios.

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

Re: Subclassing native classes

Post by pfalcon » Mon Jan 14, 2019 8:01 pm

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/

paulwings
Posts: 1
Joined: Tue Apr 05, 2022 7:13 am

Re: Subclassing native classes

Post by paulwings » Tue Apr 05, 2022 7:14 am

The reason to use super is so that child classes that may be using cooperative multiple inheritance will call the correct next parent class function in the Method Resolution Order (MRO).

In Python 3, we can call it like this:

Code: Select all

class ChildB(Base):
    def __init__(self):
        super().__init__()
In Python 2, you were required to call super like this with the defining class's name and self, but you'll avoid this from now on because it's redundant, slower (due to the name lookups), and more verbose (so update your Python if you haven't already!):

Code: Select all

        super(ChildB, self).__init__()
Without super, you are limited in your ability to use multiple inheritance because you hard-wire the next parent's call:

Code: Select all

        Base.__init__(self) # Avoid this.

Post Reply