What is the difference between **kwargs and dict in Python 3.2?
arguments, dictionary, python, syntax
Solution
There is a difference in argument unpacking (where many people use `kwargs`) and passing `dict` as one of the arguments:
Using argument unpacking:
# Prepare function
def test(**kwargs):
return kwargs
# Invoke function
>>> test(a=10, b=20)
{'a':10,'b':20}
Passing a dict as an argument:
# Prepare function
def test(my_dict):
return my_dict
# Invoke function
>>> test(dict(a=10, b=20))
{'a':10,'b':20}
The differences are mostly:
- readability (you can simply pass keyword arguments even if they weren't explicitly defined),
- flexibility (you can support some keyword arguments explicitly and the rest using `**kwargs`),
- argument unpacking helps you avoid unexpected changes to the object "containing" the arguments (which is less important, as Python in general assumes developers know what they are doing, which is a different topic),
Problem
It seems that many aspects of python are just duplicates of functionality. Is there some difference beyond the redundancy I am seeing in kwargs and dict within Python?