Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one ignore unexpected keyword arguments passed to a function?

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.

like image 208
rspencer Avatar asked Oct 22 '14 19:10

rspencer


People also ask

Can non keyword arguments be passed after keyword arguments?

Yes, Python enforces an order on arguments: all non-keyword arguments must go first, followed by any keyword arguments.

How do you make an argument optional in Python?

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.

What is unexpected keyword argument Python?

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.

What is keyword arguments in functions What are the benefits of using it?

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.


1 Answers

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

  1. to just ignore any keys that are not parameter names
  2. However, it lacks the default values of parameters, which is a nice feature that it would be nice to keep
like image 102
Abhijit Avatar answered Sep 23 '22 18:09

Abhijit