Search code examples
pythonpython-3.xexeceval

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()")

Solution

  • 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())