Is this possible: scoping question with exec

Brian Kelley bkelley at wi.mit.edu
Fri Aug 24 19:06:39 CEST 2001


I stumbled across a more general if ugly solution, you can replace/add 
to a compiled functions ".func_globals" attribute.

def a(b,c,d):
    print b,c,d
    print e # this is a global

# should fail
#exec "a(1,2,3)" in {"a":a}

# put the namespace into the functions globals
namespace = {'e':'yeah baby!'}
a.func_globals.update(namespace)

exec "a(1,2,3)" in {"a":a}

# remove the namespace from the functions globals
for k,v in namespace.items():
    del a.func_globals[k]

Brian Kelley
Whitehead Institute for Biomedical Research




More information about the Python-list mailing list