Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Difference between kwargs.pop() and kwargs.get()

I have seen both ways but I do not understand what the difference is and what I should use as "best practice":

def custom_function(**kwargs):     foo = kwargs.pop('foo')     bar = kwargs.pop('bar')     ...  def custom_function2(**kwargs):     foo = kwargs.get('foo')     bar = kwargs.get('bar')     ... 
like image 915
Aliquis Avatar asked Mar 11 '18 08:03

Aliquis


People also ask

What is Kwargs get in Python?

To get the value associated with a specific key that does not exist in the Python dictionary, use the **kwargs get() method. self.

What is the correct way to use the Kwargs statement?

The double asterisk form of **kwargs is used to pass a keyworded, variable-length argument dictionary to a function. Again, the two asterisks ( ** ) are the important element here, as the word kwargs is conventionally used, though not enforced by the language.

What is the point of Kwargs?

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.

Can you pass Kwargs as a dictionary?

Introduction to the Python **kwargs parametersWhen a function has the **kwargs parameter, it can accept a variable number of keyword arguments as a dictionary.


Video Answer


1 Answers

get(key[, default]): return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

d = {'a' :1, 'c' :2} print(d.get('b', 0)) # return 0 print(d.get('c', 0)) # return 2 

pop(key[, default]) if key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised.

d = {'a' :1, 'c' :2} print(d.pop('c', 0)) # return 2 print(d) # returns {'a': 1} print(d.get('c', 0)) # return 0 

NB: Regarding best practice question, I would say it depends on your use case but I would go by default for .get unless I have a real need to .pop

like image 70
Dhia Avatar answered Sep 20 '22 15:09

Dhia