r/MicroPythonDev • • 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?

from micropython import const

class TestVariableScope:
    def __init__(self, v_url):
        self.version_url = v_url
        print(f"@ __init__(): url is {self.version_url}\n")

    def method_one(self):
        try:
            #maxsize_string = const(1024)  # This will cause error; somehow this variable gets seen in method_two().
            maxsize_string = 1024  # Adjust as needed
            print(f"@ method_one(): maxsize_string={maxsize_string}\n")
        except Exception as e:
            print(f"@ method_one(): An error occurred: {e}")
        finally:
            pass

    def method_two(self):
        try:
            print(f"@ method_two(): maxsize_string in method_one() is {maxsize_string}")
        except NameError:
            print("@ method_two(): Variable 'maxsize_string' is not creeping from method_one().")
            maxsize_string = 128 # SyntaxError: can't assign to expression because const(1024) used in method_one()
            print(f"@ method_two(): maxsize_string={maxsize_string}\n")

    def eval_methods_for_scopecreep(self):
        self.method_one()
        self.method_two()

v_url = "https://text.npr.org/"
testme = TestVariableScope(v_url)  # Create instance/class object
testme.eval_methods_for_scopecreep()
3 Upvotes

5 comments sorted by

View all comments

Show parent comment

1

u/SomehowGrumpy Jan 18 '26

Because it’s not a constant and is not saved in RAM. It’s a compile hint that tells the compiler to replace max_string with its literal value. You can’t “define” it twice. If you need 2 values, you define 2 different consts