Micropython Classes in separate Files

Discussion about programs, libraries and tools that work with MicroPython. Mostly these are provided by a third party.
Target audience: All users and developers of MicroPython.
Post Reply
John.lucas
Posts: 3
Joined: Tue Mar 22, 2022 7:33 pm

Micropython Classes in separate Files

Post by John.lucas » Thu Mar 24, 2022 8:00 pm

When classes are in separate files there are no errors but the program does nothing. Pycharm recognises the BlinkerClass for code complete. On a Pico if that helps. Thanks

>>>File: main.py

Code: Select all

import blinker

if __name__ == "__main__":
    b = blinker.BlinkerClass()
    b.blink(25)
>>>File: blinker.py

Code: Select all

import time
from machine import Pin

class BlinkerClass:
    @staticmethod
    def blink(pin):
        led = Pin(pin, Pin.OUT)
        while True:
            led.value(1)
            time.sleep(0.5)
            led.value(0)
            time.sleep(2)
Note 1: @staticmethod is needed else an error!!
Note 2: if def blink(pin): is changed to def blink(self, pin): another error

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

Re: Micropython Classes in separate Files

Post by pythoncoder » Fri Mar 25, 2022 9:43 am

Your example works fine here. I think this must be an IDE problem - I use command line tools rshell and mpremote.

A couple of general points. Your main.py would work equally well written

Code: Select all

import blinker
b = blinker.BlinkerClass()
b.blink(25)
I can see no reason why you had to use a static method - perhaps another IDE issue? This also works

Code: Select all

import time
from machine import Pin

class BlinkerClass:
    def blink(self, pin):
        led = Pin(pin, Pin.OUT)
        while True:
            led.value(1)
            time.sleep(0.5)
            led.value(0)
            time.sleep(2)
Call me a command-line dinosaur if you will but I think some IDE's cause more problems than they fix.
Peter Hinch
Index to my micropython libraries.

John.lucas
Posts: 3
Joined: Tue Mar 22, 2022 7:33 pm

Re: Micropython Classes in separate Files

Post by John.lucas » Sat Mar 26, 2022 6:30 pm

Tried micropython and circuitpython with Pycharm, Thonny and VisualStudio code. The only thing that reliably works is CircuitPython with Mu editor. I think its all about the way the .py files are copied to the Pico board and life's too short to do more diagnostics. Mu is pretty basic but it works!

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

Re: Micropython Classes in separate Files

Post by pythoncoder » Sun Mar 27, 2022 10:24 am

The gold standards are mpremote and rshell. If something fails when using those, it's usually the Python code or (rarely) the firmware. I find debugging code quite hard enough without adding an extra layer of uncertainty...
Peter Hinch
Index to my micropython libraries.

Post Reply