How to use the exec statement

Alex Martelli aleax at aleax.it
Sun Oct 6 16:28:23 EDT 2002


JB wrote:

> Alex Martelli wrote:
> 
> Thx.
> There is one thing I do nt understand, though. (It is late
> and I am tried. I may understand it tomorrow.)
> 
> In thet new namespace there will be a function f. The user
> must be able to call f via exec.

OK:

def f():
    global resulter
    resulter = 23

namespace = {'f': f}

> But f needs a global variable, otherwise it cannot
> communicate with the rest of my program. If the user can

f's global variables are those of the module that defines f.
They don't change when you set a reference to f in some
dict, as above.

> access this variable and overwrites it...
> How to solve this?

The user doesn't see 'resulter' as a global variable (it's not
a global in the namespace called 'namespace' but in f's
global-namespace, i.e., the dict of the module that defines
f).  The user might import that module and tamper with its
global -- if you use module r_exec you make that quite a
bit more difficult (perhaps not QUITE impossible) to pull off.


Alex




More information about the Python-list mailing list