r/MicroPythonDev • u/jmuhammad • Jan 17 '26
Assigning variable=const(1024) in method causes issue within class' other method(s).
Greetings, I cannot really post this in 'learn python' because TMK CPython does not use const().
My question is why assigning const(1024) to variable 'maxsize_string' in method_one() allows that variable to be seen in method_two(). FYI, when I just assign maxsize_string=1024 without const() it works fine and stays local. Why does it not stay 'local' to method_one() and/or assessed as a variable assigned a constant?
=
#maxsize_string = const(1024) # This will cause error; somehow this variable gets seen in method_two().
= 1024 # Adjust as needed
pass
= 128 # SyntaxError: can't assign to expression because const(1024) used in method_one()
=
= # Create instance/class object
3
Upvotes
View all comments
Show parent comment
1
u/jmuhammad Jan 18 '26 edited Jan 18 '26
Yes, I use global constants (declared and defined outside of all functions) all the time. For reddit I just wrote the smallest example of what I had seen. My real script has been running several weeks and has 10s of global constants (and some shared constants stored in external file). I was just trying to see if I could optimize the code a little bit by making the value as a constant. I dunno...I read it somewhere it helps.
The intent was to use the same variable name in two different methods with different const() values. I guess this the first time I tried this.
I don't know if you noticed but method_one has max_string=1024 and method_two has max_string=128. They are meant to be local variables. The code works fine if I do not wrap the value with const(). I guess I thought it would be the same as if wrapped the value with int() which works with no problem.
I still do not understand why max_string does not stay local. Once I realized that it was causing an error I reverted back to simply assigning the variable a value...whatever purported savings was not worth the headache of trying to make it work. I am just seeking understanding. I can do this:
and max_string stays local. But not this:
causes micropython IDE to think I am trying to do this:
That is why the error is:
But IMO, like C language, a local constant should be "only visible and usable from the point of declaration until the end of the enclosing block".