Sorry but the situation a bit complicated that I can't describe it clearly in the title.
So this is the script to be imported later in exec:
# script_to_be_imported.py
def f():
print("Hello World!")
And this is my main script:
# main.py
script = """
import script_to_be_imported
def function_to_use_the_imported_script():
script_to_be_imported.f()
function_to_use_the_imported_script()
"""
def function_invokes_exec():
exec(script)
function_invokes_exec()
I am using Python 3.11.4 (tags/v3.11.4:d2340ef, Jun 7 2023, 05:45:37) [MSC v.1934 64 bit (AMD64)] on win32, and it tells me that:
Traceback (most recent call last):
File "C:\Users\yueyinqiu\Documents\MyTemporaryFiles\stackoverflow\importInExec\main.py", line 16, in <module>
function_invokes_exec()
File "C:\Users\yueyinqiu\Documents\MyTemporaryFiles\stackoverflow\importInExec\main.py", line 13, in function_invokes_exec
exec(script)
File "<string>", line 6, in <module>
File "<string>", line 4, in function_to_use_the_imported_script
NameError: name 'script_to_be_imported' is not defined
But when I make some small changes which I think they are unrelated, it could work correctly.
For example, it works when exec is invoked outside the function:
# main.py
script = """
import script_to_be_imported
def function_to_use_the_imported_script():
script_to_be_imported.f()
function_to_use_the_imported_script()
"""
exec(script)
and also works when:
# main.py
script = """
import script_to_be_imported
script_to_be_imported.f()
"""
def function_invokes_exec():
exec(script)
function_invokes_exec()
It even works when a value is passed to global although it's just an empty dictionary:
# main.py
script = """
import script_to_be_imported
def function_to_use_the_imported_script():
script_to_be_imported.f()
function_to_use_the_imported_script()
"""
def function_invokes_exec():
exec(script, {})
function_invokes_exec()
So have I misunderstood something? Or it is a bug of python?
exec(...)let you specify the local and global namespaces to.be used, separately, as dicts. (This is reldvant for Python 3.)