Page 1 of 1

Micropython Classes in separate Files

Posted: Thu Mar 24, 2022 8:00 pm
by John.lucas
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

Re: Micropython Classes in separate Files

Posted: Fri Mar 25, 2022 9:43 am
by pythoncoder
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.

Re: Micropython Classes in separate Files

Posted: Sat Mar 26, 2022 6:30 pm
by John.lucas
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!

Re: Micropython Classes in separate Files

Posted: Sun Mar 27, 2022 10:24 am
by pythoncoder
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...