user-supplied locals dict for function execution?

bruno at modulix onurb at xiludom.gro
Mon Mar 20 18:59:32 CET 2006


Lonnie Princehouse wrote:
> Can anyone think of a way to substitute a user-supplied dictionary as
> the local dict for a function call?
> 
> e.g.
> 
> def f():
>    x = 5
> 
> d = {}
> 
> exec_function_in_dictionary( f, d )  # ???
> 
> print d["x"]      #  5
> 

def f(**kw):
  kw['x'] = 5

d = {}
f(**d)
print d['x']

... But I suppose this is not what you're looking for !-)

> #--------------
> 
> Right now, the way I'm doing this is to parse the function body out of
> its source code and call exec on the body.  This has problems ---
> notably that it only works on functions for which source code can be
> found, also that the parsing is tricky (but I can fix that).


What's your use case exactly ?

Well, I suppose you could either go for bytecode hacks on the function's
code object or have a look at the new AST module, but that's actually
way too black magic for me...


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list