changing local dictionnary for functions

Jeremy Hylton jeremy at alum.mit.edu
Tue Apr 9 12:19:52 EDT 2002


Boris Boutillier <boris at cantal.lip6.fr> wrote in message news:<pan.2002.04.08.18.45.23.620630.19669 at cantal.lip6.fr>...
> To be more precise, I'm looking for this kind of function :
> execfunction(func,*args,globals,locals)
> 
> func is a function
> *args : is a list of arguments to pass to the function
> globals is a dictionnary (or subclass of it) being used as global dict
> locals is a dictionnary (or subclass of it) being used as local dict
> 
> I think this kind of function can be written by playing with the
> func.func_code bytecode, but before trying to do it this way I'd like to
> be sure there is no simple way to do it.

I think the table in the docs is mistaken.  I can't think of any way
to call a function and cause it to use a different namespace for its
locals.  The implementation of local namespaces is fairly fundamental;
the namespace isn't even implemented as a dictionary.

You can exec the bytecode of the func (func.func_code) using a custom
locals dictionary, but there are two significant limitations:  The
function can't take any arguments and its return value is swallowed by
the exec statement.

Also, be careful if you pass a subclass of dict to exec.  The
interpreter uses the PyDict API which operates on the concrete
representation of the dict rather than the abstract API.  For example,
if your subclass overrides __getitem__() or __setitem__(), those
methods won't be called.

I'm having trouble imagining what you are really trying to do, so I
can't be more helpful.  In general, when I do very dynamic things with
namespaces, I use classes and instances because the language provides
more user control over attribute lookup than name lookup.

Jeremy



More information about the Python-list mailing list