Code: Select all
>>> A = const(1)
>>> A
1
>>> _B = const(2)
>>> _B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_B' isn't defined
Code: Select all
>>> A = const(1)
>>> A
1
>>> _B = const(2)
>>> _B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_B' isn't defined
Code: Select all
A = const(1)
_B = const(2)
print(A + _B)
Code: Select all
import foo
print(foo.A) # fine
print(foo._B) # doesn't exist
Code: Select all
import foo
print(foo._private_variable)
Code: Select all
>>> _B="hi"
>>> _B
'hi'
>>> _C=const(3)
>>> _C
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_C' isn't defined
Code: Select all
from micropython import const
_A = const(1)
_B = 2
C = 3
Code: Select all
>>> from foo import *
>>> dir()
['const', '__name__', 'C']
Code: Select all
>>> import foo
>>> foo._A
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '_A'
>>> foo._B
2
>>> foo.C
3
>>>
Code: Select all
>>> _B="hi"
>>> _B
'hi'
>>> _C=const(3)
>>> _C
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_C' isn't defined
This optimisation exists purely to save memory - the const() variables starting with underscores don't even exist, their value just gets substituted at compile time.kevinkk525 wrote: ↑Thu Sep 12, 2019 8:00 amShouldn't the same explanation apply to this too? If _B="hi" works then I would expect it to work with const too.
I didn't realize this was how the REPL worked. For anyone else coming across this later, this example makes it pretty clear:Each statement executed on the REPL kind of like making a file containing that statement and compiling it.
Code: Select all
>>> _B = const(2)
>>> _B
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '_B' isn't defined
>>> _B = const(2); _B
2
The optimisation is important in device drivers where, for readability, you might want a lot of integer symbolic constants. This allows them to be used at zero cost (in RAM and in performance).kevinkk525 wrote: ↑Thu Sep 12, 2019 9:01 amI guess it makes sense although it is confusing in repl to have a different behaviour between const and strings.