Green threads on pyboard



Some weeks ago i received new fancy device — pyboard. It’s like arduino, but using python instead of wiring. I was little disappointed, because micropython wasn’t have multithreading module.

And i developed microasync — library with green threads for micropython.

Little example, code for toggling leds concurrently:

from microasync.async import loop, coroutine, Delay
import pyb


@coroutine  # decorator for making green thread from function
def toggle_led_on_interval(led, interval):
    while True:
        pyb.LED(led).toggle()
        yield Delay(interval)  # like time.sleep, but non-blocking


toggle_led_on_interval(1, 1)
toggle_led_on_interval(2, 2)
toggle_led_on_interval(3, 1)
toggle_led_on_interval(4, 2)

# start main loop:
loop()

And result:

doto from clojure in python



When i writing code in clojure i can use good macro – doto.

With whom python code like:

window = QMainWindow()
window.setTitle(TITLE)
window.setWindowFlags(Qt.FramelessWindowHint)
window.setAttribute(Qt.WA_TransparentForMouseEvents, True)
window.show()

can be translated in clojure code like:

(doto (QMainWindow.)
      (.setTitle title)
      (.setWindowFlags Qt/FramelessWindowHint)
      (.setAttribute Qt/WA_TransparentForMouseEvents True)
      (.show))

And i wrote hackish class for doing something similar in python.

from functools import partial


class DoTo(object):
    def __init__(self, obj):
        self._obj = obj

    def _do(self, name, *args, **kwargs):
        getattr(self._obj, name)(*args, **kwargs)
        return self

    def __getattr__(self, item):
        return partial(self._do, item)

With method chaining we can emulate behavior of clojure doto:

window = QMainWindow()
DoTo(window)\
    .setTitle(TITLE)\
    .setWindowFlags(Qt.FramelessWindowHint)\
    .setAttribute(Qt.WA_TransparentForMouseEvents, True)\
    .show()