What is the purpose and use of **kwargs?

前端 未结 13 2179
伪装坚强ぢ
伪装坚强ぢ 2020-11-21 04:59

What are the uses for **kwargs in Python?

I know you can do an objects.filter on a table and pass in a **kwargs argument. &nbs

相关标签:
13条回答
  • 2020-11-21 05:33

    This is the simple example to understand about python unpacking,

    >>> def f(*args, **kwargs):
    ...    print 'args', args, 'kwargs', kwargs
    

    eg1:

    >>>f(1, 2)
    >>> args (1,2) kwargs {} #args return parameter without reference as a tuple
    >>>f(a = 1, b = 2)
    >>> args () kwargs {'a': 1, 'b': 2} #args is empty tuple and kwargs return parameter with reference as a dictionary
    
    0 讨论(0)
  • 2020-11-21 05:37

    kwargs are a syntactic sugar to pass name arguments as dictionaries(for func), or dictionaries as named arguments(to func)

    0 讨论(0)
  • 2020-11-21 05:39

    On the basis that a good sample is sometimes better than a long discourse I will write two functions using all python variable argument passing facilities (both positional and named arguments). You should easily be able to see what it does by yourself:

    def f(a = 0, *args, **kwargs):
        print("Received by f(a, *args, **kwargs)")
        print("=> f(a=%s, args=%s, kwargs=%s" % (a, args, kwargs))
        print("Calling g(10, 11, 12, *args, d = 13, e = 14, **kwargs)")
        g(10, 11, 12, *args, d = 13, e = 14, **kwargs)
    
    def g(f, g = 0, *args, **kwargs):
        print("Received by g(f, g = 0, *args, **kwargs)")
        print("=> g(f=%s, g=%s, args=%s, kwargs=%s)" % (f, g, args, kwargs))
    
    print("Calling f(1, 2, 3, 4, b = 5, c = 6)")
    f(1, 2, 3, 4, b = 5, c = 6)
    

    And here is the output:

    Calling f(1, 2, 3, 4, b = 5, c = 6)
    Received by f(a, *args, **kwargs) 
    => f(a=1, args=(2, 3, 4), kwargs={'c': 6, 'b': 5}
    Calling g(10, 11, 12, *args, d = 13, e = 14, **kwargs)
    Received by g(f, g = 0, *args, **kwargs)
    => g(f=10, g=11, args=(12, 2, 3, 4), kwargs={'c': 6, 'b': 5, 'e': 14, 'd': 13})
    
    0 讨论(0)
  • 2020-11-21 05:42

    As an addition, you can also mix different ways of usage when calling kwargs functions:

    def test(**kwargs):
        print kwargs['a']
        print kwargs['b']
        print kwargs['c']
    
    
    args = { 'b': 2, 'c': 3}
    
    test( a=1, **args )
    

    gives this output:

    1
    2
    3
    

    Note that **kwargs has to be the last argument

    0 讨论(0)
  • 2020-11-21 05:43

    kwargs is just a dictionary that is added to the parameters.

    A dictionary can contain key, value pairs. And that are the kwargs. Ok, this is how.

    The what for is not so simple.

    For example (very hypothetical) you have an interface that just calls other routines to do the job:

    def myDo(what, where, why):
       if what == 'swim':
          doSwim(where, why)
       elif what == 'walk':
          doWalk(where, why)
       ...
    

    Now you get a new method "drive":

    elif what == 'drive':
       doDrive(where, why, vehicle)
    

    But wait a minute, there is a new parameter "vehicle" -- you did not know it before. Now you must add it to the signature of the myDo-function.

    Here you can throw kwargs into play -- you just add kwargs to the signature:

    def myDo(what, where, why, **kwargs):
       if what == 'drive':
          doDrive(where, why, **kwargs)
       elif what == 'swim':
          doSwim(where, why, **kwargs)
    

    This way you don't need to change the signature of your interface function every time some of your called routines might change.

    This is just one nice example you could find kwargs helpful.

    0 讨论(0)
  • 2020-11-21 05:46

    Keyword Arguments are often shortened to kwargs in Python. In computer programming,

    keyword arguments refer to a computer language's support for function calls that clearly state the name of each parameter within the function call.

    The usage of the two asterisk before the parameter name, **kwargs, is when one doesn't know how many keyword arguments will be passed into the function. When that's the case, it's called Arbitrary / Wildcard Keyword Arguments.

    One example of this is Django's receiver functions.

    def my_callback(sender, **kwargs):
        print("Request finished!")
    

    Notice that the function takes a sender argument, along with wildcard keyword arguments (**kwargs); all signal handlers must take these arguments. All signals send keyword arguments, and may change those keyword arguments at any time. In the case of request_finished, it’s documented as sending no arguments, which means we might be tempted to write our signal handling as my_callback(sender).

    This would be wrong – in fact, Django will throw an error if you do so. That’s because at any point arguments could get added to the signal and your receiver must be able to handle those new arguments.

    Note that it doesn't have to be called kwargs, but it needs to have ** (the name kwargs is a convention).

    0 讨论(0)
提交回复
热议问题