thegrandchavez
thegrandchavez

Reputation: 1765

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?

Upvotes: 23

Views: 23252

Answers (2)

JLT
JLT

Reputation: 760

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, {})

Upvotes: 7

Tadeck
Tadeck

Reputation: 137420

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),

Upvotes: 22

Related Questions