Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between **kwargs and dict in Python 3.2?

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?

like image 939
thegrandchavez Avatar asked May 08 '12 00:05

thegrandchavez


People also ask

Is Kwargs as dict Python?

“ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.

Why would you sometimes want to use keyword arguments in a class constructor?

Why use keyword arguments? When calling functions in Python, you'll often have to choose between using keyword arguments or positional arguments. Keyword arguments can often be used to make function calls more explicit.

What does Kwargs get do?

kwargs get returns the value of the dictionary ket. The key returns the default value if it is not in the dictionary. kwargs pop removes and returns the value of the dictionary key. The key returns the default value if it is not in the dictionary.


2 Answers

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),
like image 100
Tadeck Avatar answered Sep 28 '22 06:09

Tadeck


It is right that in most cases you can just interchange dicts and **kwargs.

For example:

my_dict = {'a': 5, 'b': 6}
def printer1(adict):
    return adict
def printer2(**kwargs):
    return kwargs

#evaluate:
>>> printer1(my_dict)
{'a': 5, 'b': 6}
>>> printer2(**my_dict)
{'a': 5, 'b': 6}

However with kwargs you have more flexibility if you combine it with other arguments:

def printer3(a, b=0, **kwargs):
    return a,b,kwargs

#evaluate
>>> printer3(**my_dict)
(5, 6, {})
like image 40
JLT Avatar answered Sep 28 '22 07:09

JLT