**kwargs
Gordon McMillan
gmcm at hypernet.com
Wed Jan 19 00:00:32 EST 2000
sp00fD writes:
> In article <1263886656-955174 at hypernet.com>,
> gmcm at hypernet.com wrote:
> > sp00fD writes:
> >
> > > my.foo(foo="something", bar="something else", this_dict)
> >
> > Not quite. To call foo with the named args wrapped up as a
> > dictionary, you need to use apply:
> > apply(foo, ("something", "something else"), this_dict)
>
> Using the above apply(), how does foo know that foo(should have named
> that something else) == "something" and bar == "something else", they
> appear to be passed as normal args.
Because they're named in the parameter list, they always
appear as locals (so "foo" and "bar" are always bound to
something). The Python function-calling machinery takes care
of it for you. You have to pull stuff out of this_dict.
The fully general (pass me anything) declaration would be
def foo(*args, **kwargs)
So when I'm trying a new callback with <name a GUI>, the
first shot will be
def callback(*args, **kwargs):
print "callback(%s, %s)" % (repr(args), repr(kwargs))
Beyond that, the **kwargs stuff is of limited use. You might
look at how Pmw uses it in the __init__ methods of compound
(Tk based) widgets. But for most cases, it's more work to
suck stuff out of kwargs than it is to provide named
parameters.
> Also, how is this dictionary represented after the foo method receives
> it? ie. this_dict["wow"] = 1
> apply(foo, (....), this_dict)
>
> foo then sees kwargs["wow"] == 1?
>
> > or
> > this_dict['foo'] = "something"
> > this_dict['bar'] = "something else"
> > apply(foo, (), this_dict)
> >
>>> def foo(arg1=None, **kwargs):
... print 'arg1=%s, kwargs=%s' % (`arg1`, `kwargs`)
...
>>> foo(1)
arg1=1, kwargs={}
>>> apply(foo, (1,))
arg1=1, kwargs={}
>>> apply(foo, (1,), {'a':2})
arg1=1, kwargs={'a': 2}
>>> apply(foo, (), {'arg1':3,'a':2})
arg1=3, kwargs={'a': 2}
>>>
- Gordon
More information about the Python-list
mailing list