Home >Backend Development >Python Tutorial >How do *args and kwargs Work in Python Function Definitions and Calls?

How do *args and kwargs Work in Python Function Definitions and Calls?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 05:17:12866browse

How do *args and kwargs Work in Python Function Definitions and Calls?

* and Parameters in Python Functions

In Python, the * (double star/asterisk) and (star/asterisk) notation in function definitions and calls play crucial roles in handling variable arguments.

**kwargs

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

*args

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

and * Combinination

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'}

Extended Iterable Unpacking

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

Note: Positional-only Parameters (Python 3.8 )

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.

Insertion Order for kwargs

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn