**kwds behavior?

Hans Nowak hans at zephyrfalcon.org
Tue Sep 2 13:10:41 EDT 2003


Paradox wrote:
> Why does the following attempts to pass in keywords arguments not
> work. It would be alot cooler if there was a way to not have to have
> the function defined with the variable name. It really seems to me
> that the 3rd function should work. Does anyone know how to accomplish
> something like this.

"this" apparently means, that you want to create local variables (within in the 
function) with the same names as the keyword arguments.

> def testKeywords1 (**kwds):
> 	print x
> 	
> def testKeywords2 (**kwds):
> 	locals().update(kwds)
> 	print x
> 		
> def testKeywords3 (**kwds):
> 	locals().update(kwds)
> 	def testNested():
> 		print x
> 	testNested()

As people already pointed out, modifying locals() like this doesn't work. 
There is a solution, but before using it you should stop and ask yourself why 
you want this.  Is there a reason why leaving the values in the dict isn't 
sufficient?  (Or putting them in a special class, like one poster suggested.) 
Creating variables on-the-fly is usually a bad idea.

Now, on to the yucky solution:

 >>> def g(**kwargs):
         for key, value in kwargs.items():
             exec "%s = %s" % (key, repr(value))
         # test test...
	print x
	
 >>> d = {}
 >>> d['x'] = 5
 >>> g(**d)
5

HTH,

-- 
Hans (hans at zephyrfalcon.org)
http://zephyrfalcon.org/







More information about the Python-list mailing list