exec on micropython does not recognize local variable

General discussions and questions abound development of code with MicroPython that is not hardware specific.
Target audience: MicroPython Users.
Post Reply
puppet13th
Posts: 9
Joined: Tue May 03, 2022 9:56 am

exec on micropython does not recognize local variable

Post by puppet13th » Mon Jun 06, 2022 2:08 pm

example code:

Code: Select all

a = 1
b = 2
c = 3

def plus_one(number):
    code = 'print(a,b,c,number)'
    exec(code)

plus_one(4)
on micropython:

Code: Select all

MicroPython v1.18 on 2022-01-17; ESP32 module with ESP32
Type "help()" for more information.
>>> %Run -c $EDITOR_CONTENT
Traceback (most recent call last):
  File "<stdin>", line 9, in <module>
  File "<stdin>", line 7, in plus_one
  File "<string>", line 1, in <module>
NameError: name 'number' isn't defined
on cpython:

Code: Select all

Python 3.7.9 (bundled)
>>> %Run test_exec.py
1 2 3 4
it is a bug or exec on micropython works differently from cpython?

User avatar
mattyt
Posts: 410
Joined: Mon Jan 23, 2017 6:39 am

Re: exec on micropython does not recognize local variable

Post by mattyt » Tue Jun 07, 2022 2:12 pm

In this case, it is different to CPython (to reduce memory use).

See this documented difference: Code running in eval() function doesn’t have access to local variables

puppet13th
Posts: 9
Joined: Tue May 03, 2022 9:56 am

Re: exec on micropython does not recognize local variable

Post by puppet13th » Wed Jun 08, 2022 3:55 am

mattyt wrote:
Tue Jun 07, 2022 2:12 pm
In this case, it is different to CPython (to reduce memory use).

See this documented difference: Code running in eval() function doesn’t have access to local variables
Thank you very much,you point me to the right direction. :D

i was able to make it works using these code example:

Code: Select all

a = 1
b = 2
c = 3

def plus_one(number):
    global num
    num = number
    code = 'print(a,b,c,num)'
    exec(code)

plus_one(4)
code output:

Code: Select all

MicroPython v1.18 on 2022-01-17; ESP32 module with ESP32
Type "help()" for more information.
>>> %Run -c $EDITOR_CONTENT
1 2 3 4

Post Reply