executing a function with feeding its global variables

Jean-Daniel jeandaniel.browne at gmail.com
Sat Feb 12 18:22:18 CET 2011


I am writing a small framework where the user which writes a function
can expect some global variable to be set in the function namespace.

The user has to write a function like this:
# function.py
from framework import, command, run

def myfunc():
    print HOST

if __name__=="__main__":

command() registers the function, and run() evaluates or execute the
function within an environment or a namespace where HOST has been
automagically set.

Question: how can write run in a way that when using run() in a
script, the decorated function will be run with the special names made

Here is the code for this, which does not work as intended because the
'HOST' can not be found when evaluating the decorated function

# framework.py
HOST = ''
PORT = 12345

commands = []

def command(f):
    return f

def run():
    for f in commands:
        assert globals()['HOST']
        exec 'f()' in globals(),locals()

if __name__=='__main__':

    def info():
        print HOST,PORT


Note that the assert makes sure the HOST variable is indeed present in
the globals when running the function. When running function.py, I get
an NameError exception. When I put the func function in the framework
module and execute framework.py as a script, this works fine, the
global HOST is available in the func namespace which gets printed. I
tried many combinations of eval() or exec as well as many combinations
for the globals() and locals() mapping fed to eval/exec without

Thank you for your help

More information about the Python-list mailing list