Page 1 of 1

Bug with micropython.const

Posted: Tue Jan 22, 2019 1:11 pm
by Polo
This seems like a bug to me:

Code: Select all

MicroPython v1.9.4-740-gdc23978dd on 2018-12-10; PYBv1.1 with STM32F405RG
Type "help()" for more information.
>>> from micropython import const
>>> a = const(1)
>>> b = const(int(1))
Traceback (most recent call last):
  File "<stdin>", line 1
SyntaxError: constant must be an integer
>>> c = const(a+1)
Traceback (most recent call last):
  File "<stdin>", line 1
SyntaxError: constant must be an integer

const is failing with b and c even though the values are integers.

Re: Bug with micropython.const

Posted: Tue Jan 22, 2019 4:45 pm
by pythoncoder
I'm not sure why b) fails. But c) will fail because the expression put into const() must be capable of evaluation at compile time. Assigning a Python variable fails this test.

Using const() at the REPL is ineffective. It is only meaningful in scripts, where the compiler can save bytecode (and runtime) by assigning its numeric value directly rather than indirectly through a variable.

Re: Bug with micropython.const

Posted: Wed Jan 23, 2019 1:38 pm
by Polo
Oh, I see.
So this is perfectly normal since b is not available at compile time?

Code: Select all

# test.py
from micropython import const
b = const(1)

Code: Select all

# main.py
from micropython import const
from test import b

a = const(1)
c = const(a + 1)  # works
d = const(b + 1)  # SyntaxError: constant must be an integer
I'm still a little confused on the subject of what gets compiled and what gets evaluated in Python

Re: Bug with micropython.const

Posted: Thu Jan 24, 2019 6:40 pm
by pythoncoder
In your example b is a variable exported by module test. The compiler can't possibly know its value because code in test might modify it at runtime. A module can only export variables. The const notion is MicroPython specific: the Python language has no notion of constants. It's a performance optimisation. In essence it accepts expressions containing integer literals or other constants defined in the same module. The expression must return an integer.

Re: Bug with micropython.const

Posted: Mon Jan 28, 2019 10:39 am
by Polo
That makes sense. Thank you