简体   繁体   中英

Why running exec inside function fail in python3?

Results running the code for python3:

------- input option 1 - exec code is executed --------
0 - for running inside function, 1 - for running in main programa: 1
option = 1
10

------- input option 0 - exec code not executed inside function ----
0 - for running inside function, 1 - for running in main programa: 0
option = 0
code inside execfunction => A = 10
Traceback (most recent call last):
  File "myexec.py", line 19, in <module>
    print(A)    
NameError: name 'A' is not defined
---------------------Code --------------------------

myexec.py

def execfunction(icode):
    print('code inside execfunction => %s' %(icode))
    exec(icode)

option = int(input("0 - for running inside function, 1 - for running in main programa: "))

print('option = %d' %(option))

code = 'A = 10'

if (option == 1):
    exec(code)
else:
    execfunction(code)  

print(A) 

Is it because exec is a function in python 3 but a statement in python 2? Have a look at this discussion

Python compiler will LOAD GLOBAL on encountering the print statement, where it fails as undefined variable 'A'. If you try to disassemble your code [import dis], you will get to see the execution of the backend process call.

A nice and well defined explanation is given in this Creating dynamically named variables in a function in python 3 / Understanding exec / eval / locals in python 3

If you really want execfunction to execute the function in the global scope, you can do

def execfunction(code):
    exec(code, globals())

Then, this will make the calls to execfunction execute in the global scope, instead of only in the local scope of the function.

For reference: https://docs.python.org/3/library/functions.html#exec

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM