What is the purpose and use of **kwargs?

前端 未结 13 2222
伪装坚强ぢ
伪装坚强ぢ 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:57

    Here's a simple function that serves to explain the usage:

    def print_wrap(arg1, *args, **kwargs):
        print(arg1)
        print(args)
        print(kwargs)
        print(arg1, *args, **kwargs)
    

    Any arguments that are not specified in the function definition will be put in the args list, or the kwargs list, depending on whether they are keyword arguments or not:

    >>> print_wrap('one', 'two', 'three', end='blah', sep='--')
    one
    ('two', 'three')
    {'end': 'blah', 'sep': '--'}
    one--two--threeblah
    

    If you add a keyword argument that never gets passed to a function, an error will be raised:

    >>> print_wrap('blah', dead_arg='anything')
    TypeError: 'dead_arg' is an invalid keyword argument for this function
    

提交回复
热议问题