**kwds behavior?

Bengt Richter bokr at oz.net
Wed Sep 3 05:56:50 CEST 2003


On 2 Sep 2003 07:52:22 -0700, JoeyTaj at netzero.com (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.
>def testKeywords1 (**kwds):
>	print x
>	
>def testKeywords2 (**kwds):
>	locals().update(kwds)
>	print x
>		
>def testKeywords3 (**kwds):
>	locals().update(kwds)
>	def testNested():
>		print x
>	testNested()
>	
>dict = {}
>dict['x'] = 5
># doesn't work
>testKeywords1(**dict)
># doesn't work
>testKeywords2(**dict)
># doesn't work
>testKeywords3(**dict)

A couple of other things that might relate to what you want:

 >>> def testkw(**kw):
 ...     exec 'print x' in kw
 ...
 >>> testkw(x='did it work?')
 did it work?

Guess so, but
 >>> testkw(y='did it work?')
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 2, in testkw
   File "<string>", line 1, in ?
 NameError: name 'x' is not defined

Note that that's a NameError, not a KeyError, as in:
 >>> def testkw1(**kw):
 ...     print '%(x)s' % kw
 ...
 >>> testkw1(x='did it work?')
 did it work?

Ok, but
 >>> testkw1(y='did it work?')
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 2, in testkw1
 KeyError: 'x'

Yet another way ...

 >>> def testkw2(**kw):
 ...     ns = type('',(),kw)()
 ...     print ns.x
 ...
 >>> testkw2(x='did it work?')
 did it work?

 >>> testkw2(y='did it work?')
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 3, in testkw2
 AttributeError: '' object has no attribute 'x'

Or silliness,

 >>> def testkw3(**kw):
 ...     exec """
 ... def foo():
 ...     print x
 ... """ in kw
 ...     kw['foo']()
 ...
 >>> testkw3(x='did it work?')
 did it work?

 >>> testkw3(y='did it work?')
 Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 6, in testkw3
   File "<string>", line 3, in foo
 NameError: global name 'x' is not defined

So what are you actually trying to do?

Regards,
Bengt Richter




More information about the Python-list mailing list