passing a custom locals to a function

Kuzminski, Stefan R SKuzminski at fairisaac.com
Thu May 22 16:31:02 EDT 2003


Hi,

 

I'm trying to allow for variables in a dictionary to be manipulated
directly ( without specifying the dictionary ) by putting the values in
the local namespace. The end result for the users of the tool I'm
creating is that they can fill in the body of the 'work' function below
with more natural syntax ( var1 + var2 rather than dict['var1'] +
dict['var2]  )

 

# pseudo code 

# dict before

dict = { 'var_a' : 1, 'var_b' : 2 }

 

def work( )

    # setup locals ( would like to hide this )            

    for key in dict:

        exec( "%s=%s" % ( key, dict[key] )

 

    # do the work ( this is entered by users of the tool, perhaps by
defining a function, may vary )

    var_c = var_a + var_b

 

    # get the locals back into dict ( not shown )      

    ...

 

work()

 

# dict after

dict = { 'var_a' : 1, 'var_b' :2, 'var_c' : 3 }

 

 

This works but is too slow ( and is a bit of a kludge getting the locals
back into the dict because of extra things that might be in locals I
don't want in the dict such as self ).  I tried to eval and exec passing
locals explicitly, but if I point exec to a function, the locals don't
seem to show up inside the function..

 

def foo():

   print locals()

 

exec( foo.co_func, globals{}, {'var_a" : 1 }

 

this does not result in the locals inside the foo function being what I
passed into exec.  Any thoughts on this would be appreciated, perhaps I
am approaching it incorrectly, the main thing is that my users need to
write formulas using values I have in a dictionary and they shouldn't
need to know about the dictionary..

 

thanks,

Stefan Kuzminski

 

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20030522/5743aba3/attachment.html>


More information about the Python-list mailing list