support icon indicating copy to clipboard operation
support copied to clipboard

[Bug] Micropython variable scoping confusion

Open afarago opened this issue 3 months ago • 6 comments

Describe the bug I am trying to access and even change local variables via the locals() disctionary. Any local variables seem to be missing from this dictionary / except for the module global scope, where globals() seems to be equal to locals().

To reproduce

def function1():
    apple = 1
    print("apple", apple, locals())
    locals()['apple'] = 2
    print("apple", apple, locals())

def function2():
    peach = 2
    print("peach", peach, locals())
    locals()['peach'] = 3
    print("peach", peach, locals())

def function3():
    pear = 3
    print("pear", pear, locals())
    locals()['pear'] = 4
    print("pear", pear, locals())
    function1()
    function2()

varroot1 = 42
print("varroot1", varroot1, locals())
locals()['varroot1'] = 43
print("varroot1", varroot1, locals())
function3()
varroot1 42 {'__name__': '__main__', 'function1': <function>, 'varroot1': 42, 'function3': <function>, 'function2': <function>}
varroot1 43 {'__name__': '__main__', 'function1': <function>, 'varroot1': 43, 'function3': <function>, 'function2': <function>}
pear 3 {'__name__': '__main__', 'function1': <function>, 'varroot1': 43, 'function3': <function>, 'function2': <function>}
pear 3 {'__name__': '__main__', 'function1': <function>, 'varroot1': 43, 'pear': 4, 'function3': <function>, 'function2': <function>}
apple 1 {'__name__': '__main__', 'function1': <function>, 'varroot1': 43, 'pear': 4, 'function3': <function>, 'function2': <function>}
apple 1 {'apple': 2, '__name__': '__main__', 'pear': 4, 'function3': <function>, 'function2': <function>, 'function1': <function>, 'varroot1': 43}
peach 2 {'apple': 2, '__name__': '__main__', 'pear': 4, 'function3': <function>, 'function2': <function>, 'function1': <function>, 'varroot1': 43}
peach 2 {'apple': 2, 'peach': 3, '__name__': '__main__', 'pear': 4, 'function3': <function>, 'function2': <function>, 'function1': <function>, 'varroot1': 43}

Expected behavior Data is set to the new values in the original local scoped variables.

Here only varroot1 variable is changing values.

Screenshots Code snippet is added.

afarago avatar Oct 10 '25 22:10 afarago