Forwarding keyword arguments from one function to another
Albert Hopkins
marduk at letterboxes.org
Sun Feb 22 15:32:23 EST 2009
On Sun, 2009-02-22 at 12:09 -0800, Ravi wrote:
> I am sorry about the typo mistake, well the code snippets are as:
>
> # Non Working:
>
> class X(object):
> def f(self, **kwds):
> print kwds
> try:
> print kwds['i'] * 2
> except KeyError:
> print "unknown keyword argument"
> self.g("string", kwds)
>
> def g(self, s, **kwds):
> print s
> print kwds
>
> if __name__ == "__main__":
> x = X()
> x.f(k = 2, j = 10)
>
>
> # Working One
>
> class X(object):
> def f(self, **kwds):
> print kwds
> try:
> print kwds['i'] * 2
> except KeyError:
> print "unknown keyword argument"
> self.g("string", **kwds)
>
> def g(self, s, **kwds):
> print s
> print kwds
>
> if __name__ == "__main__":
> x = X()
> x.f(k = 2, j = 10)
Same reasoning, though admittedly the error text is misleading.
This example can be simplified as:
def foo(x, **kwargs):
pass
>>> foo(1, {'boys': 5, 'girls': 10})
==> TypeError: foo() takes exactly 1 argument (2 given)
Again misleading, but the argument is the same (no pun intended).
However the following would have worked:
>>> foo(1, **{'boys': 5, 'girls': 10})
or
>>> foo(1, boys=5, girls=10)
More information about the Python-list
mailing list