No-brainer? Dictionary keys to variable name?

Steve Holden sholden at holdenweb.com
Fri Aug 2 11:58:53 EDT 2002


"Mark McEahern" <marklists at mceahern.com> wrote in message
news:mailman.1028295605.19630.python-list at python.org...
> [Christopher Myers]
> > >    blarg.runSearchTest(**dictOfArgs)
> > >
> >
> > Excellent.  I knew it was probably a no-brainer.  I had seen this
> > before, but I was having a senior moment (at 33!).
> >
> > One question though:  It looks like in order to have the necessary
> > variables initialized properly, I actually HAVE TO keep my method
> > definition as is, just in case the dict I pass doesn't contain all the
> > necessary keys, is that right?
>
> You want:
>
> 1.  To call the function without specifying the individual arguments.
> 2.  To define the function without specifying the individual arguments.
> 3.  To have all necessary local variables holding the individual arguments
> in the function initialized properly.
>
> The only thing I wonder is how you expect Python to figure out what the
> necessary variables are?  If you reference something that wasn't
specified,
> it should just initialize it to None?
>
>   def foo(**kwargs):
>     print "%s is a necessary local variable." % bar
>
>   theDict = {}
>
>   foo(theDict)
>
> You want something like that to work?  It's probably possible, but at this
> point I'm not sure what problem you're trying to solve that requires this
> kind of implicit approach.
>
> It seems like what's missing from the above is this:
>
>   def foo(**kwargs):
>     if 'bar' not in kwargs:
>       bar = None
>     print "%s is a necessary local variable." % bar
>
>   theDict = {}
>
>   foo(theDict)
>
> Of course, you may say, "But I don't want to have to initialize bar to
> None."
>
Perhaps I'm missing something, but with keyword arguments providing default
values, doesn't this get everything the OP wanted?

>>> def f(arg1, arg2="Arg2", arg3="Arg3"):
...     print "1:", arg1, "2:", arg2, "3:", arg3
...
>>> f("Hello!")
1: Hello! 2: Arg2 3: Arg3
>>> f("With arg2", **{"arg2": "Arg2 was provided"})
1: With arg2 2: Arg2 was provided 3: Arg3

regards
-----------------------------------------------------------------------
Steve Holden                                 http://www.holdenweb.com/
Python Web Programming                http://pydish.holdenweb.com/pwp/
-----------------------------------------------------------------------








More information about the Python-list mailing list