micropython

Protected const() class variable


Why do protected class variables assigned to MicroPython const() are missing from list of class members? The MicroPython docs indicate that "if a constant begins with an underscore then it is hidden" - does it mean it's dropped completely from the program?

Following code:

from micropython import const

class Device:
    class_variable_1 = const(1)
    _class_variable_2 = const(2)

print(dir(Device))

Results in missing class_variable_2:

['__class__', '__module__', '__name__', '__qualname__', '__bases__', '__dict__', 'class_variable_1']

Solution

  • Yes. The complete statement you quoted is

    if a constant begins with an underscore then it is hidden, it is not available as a global variable, and does not take up any memory during execution.

    To avoid taking up memory, it has to be left out of the class dictionary.

    Constants are recognized by the MicroPython parser and replaced with their values at compile time, they're not looked up by name at runtime. The names for non-hidden constants are just there for introspection.