What is the purpose and use of **kwargs?

前端 未结 13 2217
伪装坚强ぢ
伪装坚强ぢ 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: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).

提交回复
热议问题