Suppose I have some function, f
:
def f (a=None): print a
Now, if I have a dictionary such as dct = {"a":"Foo"}
, I may call f(**dct)
and get the result Foo
printed.
However, suppose I have a dictionary dct2 = {"a":"Foo", "b":"Bar"}
. If I call f(**dct2)
I get a
TypeError: f() got an unexpected keyword argument 'b'
Fair enough. However, is there anyway to, in the definition of f
or in the calling of it, tell Python to just ignore any keys that are not parameter names? Preferable a method that allows defaults to be specified.
Yes, Python enforces an order on arguments: all non-keyword arguments must go first, followed by any keyword arguments.
You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function.
Unexpected keyword argument %r in %s call. Description: Used when a function call passes a keyword argument that doesn't correspond to one of the function's parameter names.
There are two advantages - one, using the function is easier since we do not need to worry about the order of the arguments. Two, we can give values to only those parameters which we want, provided that the other parameters have default argument values.
As an extension to the answer posted by @Bas, I would suggest to add the kwargs arguments (variable length keyword arguments) as the second parameter to the function
>>> def f (a=None, **kwargs): print a >>> dct2 = {"a":"Foo", "b":"Bar"} >>> f(**dct2) Foo
This would necessarily suffice the case of
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With