Page 1 of 1

Possible enhancement to const()

Posted: Sat May 21, 2016 4:58 am
by pythoncoder
In device drivers it's common practice to have a substantial number of global constants specifying things like device commands and registers e.g.:

Code: Select all

DATA_REG = const(0x23)
COMMAND_REG = const(0X24)
Each line causes four bytes of RAM to be used, even if the module is implemented as frozen bytecode. This is because the language requires the variables to be available to other modules even if this is not the designer's requirement. Given the use of MicroPython on resource constrained platforms this seems wasteful.

Would it be feasible to enforce module locality on globals having names starting with an underscore and declared as constant? This would turn a Python naming convention into physical reality, but only when using the const() keyword.

Code: Select all

_DATA_REG = const(0x23)
_COMMAND_REG = const(0X24)
This arose from considering a discussion here http://forum.micropython.org/viewtopic. ... nst#p10773

Re: Possible enhancement to const()

Posted: Sat May 21, 2016 6:55 am
by deshipu
Another alternative would be to not make available names that are not listed in "__all__" for the module -- if it's defined, that is.

Re: Possible enhancement to const()

Posted: Sat May 21, 2016 9:59 am
by pythoncoder
Indeed. I have no knowledge of compiler design so I've no idea which would be easier to implement. One arguable advantage to my approach is that, with the change, MicroPython code remains compatible with standard Python by adding

Code: Select all

const = lambda x : x