In Python, the * (double star/asterisk) and (star/asterisk) notation in function definitions and calls play crucial roles in handling variable arguments.
The syntax
def foo(x, y, **kwargs): pass
indicates that the function foo can accept an arbitrary number of keyword arguments. These keyword arguments are gathered into a dictionary named kwargs. For example:
def bar(**kwargs): for a in kwargs: print(a, kwargs[a]) # Call the function bar(name='one', age=27) # Output: # name one # age 27
Similarly, the syntax
def foo(x, y, *args): pass
allows the function foo to accept an arbitrary number of positional arguments. These arguments are collected into a tuple named args.
def foo(*args): for a in args: print(a) # Call the function foo(1) # Output: 1 foo(1, 2, 3) # Output: 1 # Output: 2 # Output: 3
Both *kwargs and args can be used together to allow both fixed and variable arguments. For instance:
def foo(kind, *args, bar=None, **kwargs): print(kind, args, bar, kwargs) # Call the function foo(123, 'a', 'b', apple='red') # Output: 123 ('a', 'b') None {'apple': 'red'}
The * notation can also be used to unpack argument lists when calling functions. For example:
def foo(bar, lee): print(bar, lee) # Create a list baz = [1, 2] # Call the function using unpacking foo(*baz) # Output: 1 2
In Python 3.8 and later, it is possible to specify positional-only parameters in a function definition by using the * notation before the regular parameters:
def func(arg1, arg2, arg3, *, kwarg1, kwarg2): pass
This function can only accept three positional arguments, and any additional arguments must be passed as keyword arguments.
In Python 3.6 and later, the order of keyword arguments is preserved in the kwargs dictionary. This can be useful in certain scenarios, such as when you need to maintain the order of arguments passed to the function.
The above is the detailed content of How do *args and kwargs Work in Python Function Definitions and Calls?. For more information, please follow other related articles on the PHP Chinese website!