Skip to content

Commit 791b65f

Browse files
committed
py/modmicropython: Add micropython.const, alias for identity function.
Having a micropython.const identity function, and writing "from micropython import const" at the start of scripts that use the const feature, allows to write scripts which are compatible with CPython, and with uPy builds that don't include const optimisation. This patch adds such a function and updates the tests to do the import.
1 parent f65e4f0 commit 791b65f

4 files changed

Lines changed: 7 additions & 0 deletions

File tree

py/modmicropython.c

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_alloc_emergency_exception_buf_obj, mp_alloc_
120120

121121
STATIC const mp_rom_map_elem_t mp_module_micropython_globals_table[] = {
122122
{ MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_micropython) },
123+
{ MP_ROM_QSTR(MP_QSTR_const), MP_ROM_PTR(&mp_identity_obj) },
123124
#if MICROPY_PY_MICROPYTHON_MEM_INFO
124125
#if MICROPY_MEM_STATS
125126
{ MP_ROM_QSTR(MP_QSTR_mem_total), MP_ROM_PTR(&mp_micropython_mem_total_obj) },

tests/micropython/const.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# test constant optimisation
22

3+
from micropython import const
4+
35
X = const(123)
46
Y = const(X + 456)
57

tests/micropython/const2.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# check that consts are not replaced in anything except standalone identifiers
22

3+
from micropython import const
4+
35
X = const(1)
46
Y = const(2)
57
Z = const(3)

tests/micropython/const_error.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
# make sure syntax error works correctly for bad const definition
22

3+
from micropython import const
4+
35
def test_syntax(code):
46
try:
57
exec(code)

0 commit comments

Comments
 (0)