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') ...
To get the value associated with a specific key that does not exist in the Python dictionary, use the **kwargs get() method. self.
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.
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.
Introduction to the Python **kwargs parametersWhen a function has the **kwargs parameter, it can accept a variable number of keyword arguments as a dictionary.
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
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