Micropython conditional compilation

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
hlovatt
Posts: 68
Joined: Thu Aug 15, 2019 3:52 am
Location: Sydney

Micropython conditional compilation

Post by hlovatt » Mon Nov 25, 2019 10:34 pm

Hi,

I want to share a file between Micropython and Python but for the MicroPython version I want to annotate with viper. The Micropython version outline is:

Code: Select all

import micropython

class Message:
    @micropython.viper
    def transaction_id(...):
        ...
I know I can add a pre-processor to do this; but was thinking it would be great if there was a purely pythonic way, something like an `if` statement round the import and viper annotations? But, how do you know that the compiler is MicroPython, not CPython etc.?

Help much appreciated,

-- Howard.

PS Edit after original post. What I am currently doing is using a dummy `micropython.py` file for CPython, it works quite well but was wondering if there is a better approach.

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Micropython conditional compilation

Post by jimmo » Tue Nov 26, 2019 2:41 am

You can certainly put an if around the import. But I think the solution you've come up with (providing a micropython.py with a no-op version of the const function and viper/native/etc decorators for CPython) is the intended way of solving this.

You might be able to do something like have main.py edit sys.path only when running on CPython to include the path to micropython.py to a directory that's excluded for your micropython deploy process.

hlovatt
Posts: 68
Joined: Thu Aug 15, 2019 3:52 am
Location: Sydney

Re: Micropython conditional compilation

Post by hlovatt » Tue Nov 26, 2019 3:16 am

@jimmo Thanks for advice. There are some tricky situations though, e.g. in:

Code: Select all

    @micropython.viper
    def validity_of_previous_request(self) -> uint
how do I define `uint` in my module `micropython`?

I currently do:

Code: Select all

import sys
if sys.implementation.name != 'micropython':
    uint = int
    __all__ += 'uint'
But I have to put this into each file that imports micropython!

Post Reply