Inherit Pin class not working

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Inherit Pin class not working

Post by kevinkk525 » Tue May 01, 2018 9:07 pm

I tried to inherit the Pin class to include a dictionary from nodemcu pin names to pin id but I got the following problems:

Code: Select all

>>> class PinNew(machine.Pin):
...     def __init__(self, *args,**kwargs):
...         args=list(args)
...         if type(args[0])==str:
...             args[0]=pins[args[0]]
...         print(args,kwargs)
...         super().__init__(*args,**kwargs)
...
...
...
>>> PinNew(0)
(0,) {}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
TypeError: function takes 1 positional arguments but 2 were given
>>> PinNew("D0")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert str to int
I have no idea about the first error and the 2nd is even more weird as the code does not convert the str pin to int anywhere and it says that it does it in line 1.

Wrapping around the Pin class works fine on the other hand:

Code: Select all

def Pin(*args,**kwargs):
...     args=list(args)
...     if type(args[0])==str:
...         args[0]=pins[args[0]]
...     return machine.Pin(*args,**kwargs)
...
...
>>> Pin(0)
Pin(0)
>>> Pin("D0")
Pin(16)
>>> Pin("D0",mode=machine.Pin.OUT)
Pin(16)
What am I doing wrong?
Or is it just the Pin class that is a bit weird?

I don't have the problem on the loboris fork of esp32.
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Inherit Pin class not working

Post by pythoncoder » Thu May 03, 2018 4:23 am

In general subclassing built-in types (i.e. types implemented in C) is not supported. See implementation differences.
Peter Hinch
Index to my micropython libraries.

kevinkk525
Posts: 969
Joined: Sat Feb 03, 2018 7:02 pm

Re: Inherit Pin class not working

Post by kevinkk525 » Thu May 03, 2018 7:15 am

Oh.. did not read that. Thanks.
Interesting that it works on the loboris fork on esp32 though.
Kevin Köck
Micropython Smarthome Firmware (with Home-Assistant integration): https://github.com/kevinkk525/pysmartnode

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Inherit Pin class not working

Post by pythoncoder » Thu May 03, 2018 7:43 am

Subclassing built-ins can sometimes work - but it's best avoided as behaviour is not guaranteed. The one exception I'm aware of is the framebuf class which was explicitly coded to support subclassing.
Peter Hinch
Index to my micropython libraries.

Post Reply