Confusion about micropython.const

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
User avatar
Walkline
Posts: 14
Joined: Wed Feb 19, 2020 4:44 pm

Confusion about micropython.const

Post by Walkline » Thu Mar 19, 2020 1:44 pm

Here's the sample code:

Code: Select all

from micropython import const

class a(object):
    test = const(0x1)

class b(object):
    test = 0
And here is the result:

Code: Select all

Traceback (most recent call last):
  File "<stdin>", line 4, in b
SyntaxError: can't assign to expression
According to the documents about micropython.const
Constants declared this way are still accessible as global variables from outside the module they are declared in.
It is a global variable, but it is also a class member constant. Why does it affect member variables of other classes?

fstengel
Posts: 55
Joined: Tue Apr 17, 2018 4:37 pm

Re: Confusion about micropython.const

Post by fstengel » Thu Mar 19, 2020 4:26 pm

Look there: http://docs.micropython.org/en/latest/r ... eclaration

As far as I can tell, when you write foo=const(42) then foo is not a variable but behaves as if, as compile time, it is replaced by 42. So your code would be seen as:

Code: Select all

from micropython import const

class a(object):
    test = const(0x1) # from now on test is a shortcut for 0x1

class b(object):
    0x1 = 0 # and here it fails: test has been replaced by its "value"

User avatar
Walkline
Posts: 14
Joined: Wed Feb 19, 2020 4:44 pm

Re: Confusion about micropython.const

Post by Walkline » Thu Mar 19, 2020 6:25 pm

fstengel wrote:
Thu Mar 19, 2020 4:26 pm
test = const(0x1) # from now on test is a shortcut for 0x1
Thanks fstengel, that's uh.....amazing

And then I have second question

Code: Select all

from micropython import const

ONE = 1
TWO = 2

COMPILED = const(ONE | TWO)
In this way, it's still got exception, according to you link
The argument to const() may be anything which, at compile time, evaluates to an integer e.g. 0x100 or 1 << 8.
Is "anything" excluded variables?

User avatar
Roberthh
Posts: 3667
Joined: Sat May 09, 2015 4:13 pm
Location: Rhineland, Europe

Re: Confusion about micropython.const

Post by Roberthh » Thu Mar 19, 2020 7:26 pm

The reason: variable assignment does not happen at compile time. It happens when the code is executed.
In comparison, the following works:

Code: Select all

ONE = const(1)
TWO = const(2)

COMPILED = const(ONE | TWO)
Note: You do not have to import const.

User avatar
Walkline
Posts: 14
Joined: Wed Feb 19, 2020 4:44 pm

Re: Confusion about micropython.const

Post by Walkline » Fri Mar 20, 2020 3:52 am

Roberthh wrote:
Thu Mar 19, 2020 7:26 pm
The reason: variable assignment does not happen at compile time. It happens when the code is executed.

Note: You do not have to import const.
Thanks Robert, this is helpful for me, thanks again :D

Post Reply