Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for a python function to ignore unused kwargs [duplicate]

If I have a simple function:

def add(a, b, c):
    return a + b + c

Is it possible for me to make it so that if I supply an unused kwarg, it is simply ignored?

kwargs = dict(a=1, b=2, c=3, d=4)
print add(**kwargs) #prints 6
like image 792
Lucretiel Avatar asked Mar 19 '13 21:03

Lucretiel


People also ask

Can Kwargs be empty?

**kwargs allow a function to take any number of keyword arguments. By default, **kwargs is an empty dictionary. Each undefined keyword argument is stored as a key-value pair in the **kwargs dictionary.

What does *_ mean in Python?

*_ means multiple placeholders,just like you write def my_callbacK_handler(a, b, _,_,_....,_): and will create a variable named _ which is a list of the extra arguments. It has two advantage: It can handle the case where there is no extra argument.

Can you have multiple Kwargs in Python?

Python 3.5+ allows passing multiple sets of keyword arguments ("kwargs") to a function within a single call, using the `"**"` syntax.

How do you beat Kwargs argument?

Kwargs allow you to pass keyword arguments to a function. They are used when you are not sure of the number of keyword arguments that will be passed in the function. Kwargs can be used for unpacking dictionary key, value pairs. This is done using the double asterisk notation ( ** ).


1 Answers

Sure. Just add **kwargs to the function signature:

def add(a, b, c, **kwargs):
    return a + b + c

kwargs = dict(a=1, b=2, c=3, d=4)
print add(**kwargs) 
#prints 6
like image 155
unutbu Avatar answered Sep 29 '22 11:09

unutbu