← index #11929PR #8548
Related · high · value 0.237
QUERY · ISSUE

Don't allow `micropython.const`

openby jimmoopened 2023-07-04updated 2023-07-04
enhancement

This came up in https://github.com/micropython/micropython-lib/pull/693

It does seem reasonable to expect that A = micropython.const(1) should do the right thing, but it only works if you write A = const(1). I would argue that the former should raise an error or otherwise indicate that it's not doing anything useful.

We need to support from micropython import const because this facilitates:

  1. Running MicroPython code on CPython (where you have a micropython.py that provides a dummy const function).
  2. On builds with MICROPY_COMP_CONST disabled (e.g. when settrace is enabled) there will be no "magic" const, so it needs to be imported.

I think 791b65f4b261a23e427664f0b86ce32b60e33cb5 confirms the above.

Some ideas:

  1. We could change parse.c to turn const(...) into a no-op, rather than not handling it at all when MICROPY_COMP_CONST is disabled. (I never realised until today that we had this implicit requirement to use from micropython import const to be able to use const() in all builds, I have written a lot of .py files that don't do this!). Then micropython.const should no longer be the identity function (it should raise an error).

or

  1. Only if MICROPY_COMP_CONST is enabled, then micropython.const should no longer be the identity function (it should raise an error to indicate incorrect usage).

or

  1. Make the parser also handle micropython.const.

My preference would be #1. Instead of making micropython.const raise an error, it could also just be None (enough to make the import work), but then it might be a bit confusing to figure out why it's failing.

CANDIDATE · PULL REQUEST

py/parse: Allow all constant objects to be used in "X = const(o)".

mergedby dpgeorgeopened 2022-04-14updated 2022-11-22
py-core

Now that constant tuples are supported in the parser (eg (1, True, "str")), it's a small step to allow anything that is a constant to be used with the pattern:

from micropython import const

X = const(obj)

This PR makes the required changes to allow the following types of constants:

from micropython import const

_INT = const(123)
_FLOAT = const(1.2)
_COMPLEX = const(3.4j)
_STR = const("str")
_BYTES = const(b"bytes")
_TUPLE = const((_INT, _STR, _BYTES))
_TUPLE2 = const((None, False, True, ..., (), _TUPLE))

Prior to this, only integers could be used in const(...).

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied