pythonian 23
pythonian 23

Reputation: 395

Access things outside of module with eval and exec

If I import a module that uses exec or eval, is it possible to give it access to the main program?

myExec.py

def myExec(code):
    exec(code)

main.py

import myExec
def test():
    print("ok")
myExec.myExec("test()")

Upvotes: 1

Views: 195

Answers (1)

Scrapper142
Scrapper142

Reputation: 586

Yes!

exec has a few optional parameters, globals and locals. These basically tell it what global and local variables its allowed to use, in the form of a dictionary. Calling globals() or locals() functions returns the dictionary with all the global and local variables where you are calling from, so you can use:

myExec.py:

def myExec(code, globals_=None, locals_=None):  # the trailing underscore is so that there are no name conflicts
    exec(code, globals_, locals_)

main.py:

import myExec
def test():
    print("ok")
myExec.myExec("test()", globals())

Upvotes: 1

Related Questions