Page 1 of 1
Confusion about micropython.const
Posted: Thu Mar 19, 2020 1:44 pm
by Walkline
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?
Re: Confusion about micropython.const
Posted: Thu Mar 19, 2020 4:26 pm
by fstengel
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"
Re: Confusion about micropython.const
Posted: Thu Mar 19, 2020 6:25 pm
by Walkline
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?
Re: Confusion about micropython.const
Posted: Thu Mar 19, 2020 7:26 pm
by Roberthh
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.
Re: Confusion about micropython.const
Posted: Fri Mar 20, 2020 3:52 am
by Walkline
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