No-brainer? Dictionary keys to variable name?

Mark McEahern marklists at mceahern.com
Fri Aug 2 15:39:29 CEST 2002


[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."

Cheers,

// mark

-





More information about the Python-list mailing list