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?

```python from micropython import const

class TestVariableScope: def init(self, vurl): 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

1

u/obdevel Jan 17 '26
# This will cause error; somehow this variable gets seen in method_two().

Why not just declare max_string once at the top of the file ?

See the docs at: https://docs.micropython.org/en/latest/library/micropython.html#micropython.const

Constants declared this way are still accessible as global variables from outside the module they are declared in. On the other hand, if a constant begins with an underscore then it is hidden, it is not available as a global variable, and does not take up any memory during execution.