Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 8013

MicroPython • Re: Variable Scope problem (again)

$
0
0
:oops: just a RTFM problem !
I would also have classed 'eval' evaluating the global variables instead of the local variables of the same name as a bug.

Code:

A = 1B = 2def Test(A, B, fn):  print("A =", A)  print("B =", B)  print(A, "+", B, "=", A + B)  print(fn, "=", eval(fn))Test(A=3, B=4, fn="A + B")
It doesn't do that with desktop Python 3.11.2 -

Code:

pi@Pi4B:/tmp $ python e.pyA = 3B = 43 + 4 = 7A + B = 7<-- As expected
But does with MicroPython -

Code:

pi@Pi4B:/tmp $ mpremote run e.pyA = 3B = 43 + 4 = 7A + B = 3<-- Not as expected
That is however described here -

Code running in eval() function doesn’t have access to local variables

Cause: MicroPython doesn’t maintain symbolic local environment, it is optimized to an array of slots. Thus, local variables can’t be accessed by a name. Effectively, eval(expr) in MicroPython is equivalent to eval(expr, globals(), globals()).

Statistics: Posted by hippy — Fri Dec 19, 2025 3:15 pm



Viewing all articles
Browse latest Browse all 8013

Trending Articles