Bug with micropython.const

C programming, build, interpreter/VM.
Target audience: MicroPython Developers.
Post Reply
Polo
Posts: 10
Joined: Tue Oct 02, 2018 1:07 pm

Bug with micropython.const

Post by Polo » Tue Jan 22, 2019 1:11 pm

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.

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Bug with micropython.const

Post by pythoncoder » Tue Jan 22, 2019 4:45 pm

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.
Peter Hinch
Index to my micropython libraries.

Polo
Posts: 10
Joined: Tue Oct 02, 2018 1:07 pm

Re: Bug with micropython.const

Post by Polo » Wed Jan 23, 2019 1:38 pm

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

User avatar
pythoncoder
Posts: 5956
Joined: Fri Jul 18, 2014 8:01 am
Location: UK
Contact:

Re: Bug with micropython.const

Post by pythoncoder » Thu Jan 24, 2019 6:40 pm

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.
Peter Hinch
Index to my micropython libraries.

Polo
Posts: 10
Joined: Tue Oct 02, 2018 1:07 pm

Re: Bug with micropython.const

Post by Polo » Mon Jan 28, 2019 10:39 am

That makes sense. Thank you

Post Reply