mercredi 22 avril 2015

Defining a function with exec from inside a function in global environment

I have a function that, when called, should define another function with use of exec and make this new function available for the main program. The mwe is the following.

Main program:

#!/usr/bin/python
from ext import makeF

makeF()
sayA()

External module:

def makeF():
    script="def sayA():\n\tprint 'Aah'"
    exec(script)
    sayA()
    return

What I want is to be able to call the inner function sayA() from the main program, so in this example the output should be

Aah
Aah

but instead it returns

Aah
Traceback (most recent call last):
  File "mwe.py", line 5, in <module>
    sayA()
NameError: name 'sayA' is not defined

which I kind of expected, so I replace the exec(script) line with exec(script,globals), according to the docs, but instead I get

Traceback (most recent call last):
  File "mwe.py", line 4, in <module>
    makeF()
  File "/home/tomas/tests/ext.py", line 3, in makeF
    exec(script,globals,locals)
TypeError: exec: arg 2 must be a dictionary or None

I have the feeling I'm missing something pretty obvious here but I can't figure out. Any help is appreciated.

Thank you.

Aucun commentaire:

Enregistrer un commentaire