Back to series
· 6 min read

Python *args and **kwargs


I. Why Are args and *kwargs Needed?

Regular functions usually need to define the number of parameters in advance.

def add(a, b):
    return a + b


print(add(10, 20))

If a function needs to accept three, four, or even more parameters, its definition must be modified repeatedly.

def add(a, b, c):
    return a + b + c

When the number of parameters cannot be determined in advance, fixed parameters are not flexible enough.

Python provides two mechanisms for variable arguments:

  • *args: Accepts any number of positional arguments.
  • **kwargs: Accepts any number of keyword arguments.

They allow a function to receive and process data passed by the caller without predetermining the number of parameters.

II. What Is *args?

*args is used to receive extra positional arguments when a function is called and collect them into a tuple.

1. Basic Syntax

def function(*args):
    print(args)
    print(type(args))


function(10, 20, 30)

Output:

(10, 20, 30)
<class 'tuple'>

Where:

  • * indicates collecting extra positional arguments.
  • args is the variable name and can be customized.
  • The collected result is always a tuple.

Note that args is not a Python keyword but a customary naming convention.

The following form is also valid:

def function(*values):
    print(values)


function(1, 2, 3)

In actual development, args is usually used because it is more general and readable.

2. Receiving Different Numbers of Positional Arguments

def calculate_sum(*args):
    total = 0

    for number in args:
        total += number

    return total


print(calculate_sum())
print(calculate_sum(10))
print(calculate_sum(10, 20))
print(calculate_sum(10, 20, 30, 40))

Output:

0
10
30
100

The function can receive zero, one, or more positional arguments.

When no extra positional arguments are passed, args is an empty tuple:

def show(*args):
    print(args)


show()

Output:

()

3. The Nature of *args

*args does not pass all arguments as a single whole; instead, it collects multiple positional arguments.

For example:

def show(*args):
    print(args)


show("Python", 18, True)

Argument collection relationship:

Argument Passed at Call Time Content in args
"Python" First element
18 Second element
True Third element

Finally:

args = ("Python", 18, True)

From a data structure perspective, args is a tuple, so operations supported by tuples can be used.

def show(*args):
    print("参数数量:", len(args))
    print("第一个参数:", args[0])
    print("所有参数:", args)


show("Python", "Java", "Go")

Output:

Argument count: 3
First argument: Python
All arguments: ('Python', 'Java', 'Go')

Note: If no arguments are passed, directly accessing args[0] will raise an IndexError.

4. Combining *args with Regular Parameters

*args can be used together with regular parameters.

def introduce(name, *args):
    print("姓名:", name)
    print("其他信息:", args)


introduce("Alice", 25, "Tokyo", "Python")

Output:

姓名: Alice
其他信息: (25, 'Tokyo', 'Python')

Here:

  • name receives the first positional argument.
  • args collects the remaining positional arguments.

Therefore, regular positional arguments are bound first in the order they are defined, and only the remaining positional arguments are collected by args.

3. What is **kwargs?

**kwargs is used to receive extra keyword arguments when a function is called and collect them into a dictionary.

1. Basic syntax

def function(**kwargs):
    print(kwargs)
    print(type(kwargs))


function(name="Alice", age=25, city="Tokyo")

Output:

{'name': 'Alice', 'age': 25, 'city': 'Tokyo'}
<class 'dict'>

Where:

  • ** indicates collecting extra keyword arguments.
  • kwargs is the variable name and can be customized.
  • The collected result is a dictionary.

Like args, kwargs is not a Python keyword, but a naming convention widely used by the community.

2. Accepting a varying number of keyword arguments

def create_user(**kwargs):
    print(kwargs)


create_user()
create_user(name="Alice")
create_user(name="Bob", age=25)
create_user(name="Charlie", age=30, city="Tokyo")

Output:

{}
{'name': 'Alice'}
{'name': 'Bob', 'age': 25}
{'name': 'Charlie', 'age': 30, 'city': 'Tokyo'}

When no extra keyword arguments are passed, kwargs is an empty dictionary.

3. Iterating over **kwargs

Since kwargs is a dictionary, you can use dictionary iteration methods.

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")


print_info(
    name="Alice",
    age=25,
    city="Tokyo"
)

Output:

name: Alice
age: 25
city: Tokyo

4. Flexible configuration with **kwargs

def connect(**config):
    host = config.get("host", "localhost")
    port = config.get("port", 8080)
    timeout = config.get("timeout", 10)

    print("主机:", host)
    print("端口:", port)
    print("超时:", timeout)


connect(
    host="192.168.1.100",
    port=9000,
    timeout=30
)

Output:

主机:192.168.1.100
端口:9000
超时:30

This approach is suitable for functions that have many configuration items and need different parameters in different call scenarios.

4. The difference between args and *kwargs

Both can receive a variable number of arguments, but their collection methods and data structures are different.

Comparison *args **kwargs
Parameter type Extra positional arguments Extra keyword arguments
Collected as tuple dict
Call form func(10, 20) func(a=10, b=20)
Access Indexing, iteration Keys, iteration
Typical use An unpredictable number of positional arguments An unpredictable number of configuration arguments

1. Using Both at the Same Time

def show(*args, **kwargs):
    print("位置参数:", args)
    print("关键字参数:", kwargs)


show(10, 20, name="Alice", age=25)

Output:

位置参数: (10, 20)
关键字参数: {'name': 'Alice', 'age': 25}

As you can see:

  • 10 and 20 are collected into args.
  • name and age are collected into kwargs.

2. How Arguments Are Collected in Each Case

flowchart TD
    A["Call the function"] --> B["Receive arguments"]
    B --> C{"How arguments are passed"}
    C -->|Positional arguments| D["Handed to args for collection"]
    C -->|Keyword arguments| E["Handed to kwargs for collection"]
    D --> F["Create a tuple"]
    E --> G["Create a dict"]
    F --> H["Execute the function body"]
    G --> H

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#E8EDF2,stroke:#B8C3CE,color:#334155
    style C fill:#FFF5DE,stroke:#E8D29A,color:#334155
    style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style E fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
    style G fill:#F3EDFC,stroke:#C4B2E3,color:#334155
    style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    linkStyle default stroke:#A3B8AC,stroke-width:1.5px

V. The Complete Ordering Rules for Function Parameters

A Python function can use regular parameters, default parameters, positional-only parameters, keyword-only parameters, and variadic parameters all at once.

Understanding the parameter ordering rules is the key to using *args and **kwargs correctly.

1. The Complete Parameter Structure

def example(
    a, b, /,
    c, d=10,
    *args,
    e, f=20,
    **kwargs
):
    pass

The meaning of each part:

Parameter Type Description
a, b Positional-only parameters Can only be passed by position
c Regular parameter Can be passed by position or by keyword
d Default parameter Can be omitted
args Variadic positional parameter Collects extra positional arguments
e Keyword-only parameter Must be passed by keyword
f Default keyword parameter Can be omitted
kwargs Variadic keyword parameter Collects extra keyword arguments

Here, / and the standalone * are parameter-kind separators:

  • Parameters to the left of / can only be passed by position.
  • *args collects extra positional arguments.
  • Regular parameters after *args can only be passed by keyword.
  • **kwargs collects any remaining unmatched keyword arguments.

2. Order of Parameter Definitions

Python function parameters follow this ordering structure:

def function(
    positional_only,
    /,
    positional_or_keyword,
    *args,
    keyword_only,
    **kwargs
):
    pass

Note that ordinary parameters and default parameters can be combined according to the rules, and *args and **kwargs can also be omitted separately.

3. Complete Example

def create_user(
    name,
    age=18,
    *hobbies,
    city,
    **extra
):
    print("姓名:", name)
    print("年龄:", age)
    print("爱好:", hobbies)
    print("城市:", city)
    print("其他信息:", extra)


create_user(
    "Alice",
    25,
    "reading",
    "coding",
    city="Tokyo",
    job="Engineer",
    active=True
)

Output:

姓名: Alice
年龄: 25
爱好: ('reading', 'coding')
城市: Tokyo
其他信息: {'job': 'Engineer', 'active': True}

The parameter binding process here:

  1. "Alice" is bound to name.
  2. 25 is bound to age.
  3. "reading" and "coding" are collected into hobbies.
  4. city="Tokyo" is bound to the keyword-only parameter city.
  5. job and active are collected into extra.

VI. args and *kwargs unpacking

What was introduced earlier is parameter collection: the function collects multiple arguments into a tuple or dictionary.

In contrast, argument unpacking expands a tuple, list, or dictionary and then passes it to the function.

Although both use * and **, they occur at different stages.

1. Using * to Unpack Positional Arguments

def add(a, b, c):
    return a + b + c


numbers = [10, 20, 30]

print(add(*numbers))

Output:

60

Here *numbers expands the elements in the list into separate positional arguments.

Equivalent to:

add(10, 20, 30)

A tuple can also be used:

numbers = (10, 20, 30)

print(add(*numbers))

2. Using ** to Unpack Keyword Arguments

def introduce(name, age, city):
    print(name, age, city)


user = {
    "name": "Alice",
    "age": 25,
    "city": "Tokyo"
}

introduce(**user)

Output:

Alice 25 Tokyo

Here **user expands the key-value pairs in the dictionary into keyword arguments.

Equivalent to:

introduce(
    name="Alice",
    age=25,
    city="Tokyo"
)

3. Unpacking Positional and Keyword Arguments Together

def create_order(product, quantity, price, currency="CNY"):
    print(product, quantity, price, currency)


args = ("Laptop", 2)

kwargs = {
    "price": 5999,
    "currency": "CNY"
}

create_order(*args, **kwargs)

Output:

Laptop 2 5999 CNY

4. Notes on Unpacking

First, the unpacked arguments must match the function signature.

def add(a, b):
    return a + b


numbers = [10, 20, 30]

add(*numbers)

This will raise a TypeError because the function accepts only two positional arguments.

Second, the same parameter cannot be bound more than once.

def show(name, age):
    print(name, age)


data = {
    "name": "Bob",
    "age": 25
}

show("Alice", **data)

This will raise a TypeError because name is assigned through both a positional argument and a keyword argument at the same time.

Third, the keys in dictionary unpacking must be valid keyword names.

def show(name):
    print(name)


data = {
    "name": "Alice"
}

show(**data)

Normally, the keys in dictionary unpacking must be strings and must either match function parameter names or be accepted by **kwargs.

7. Typical Use Cases for args and *kwargs

1. Implement a Generic Sum Function

def calculate_sum(*numbers):
    return sum(numbers)


print(calculate_sum(1, 2, 3))
print(calculate_sum(10, 20, 30, 40))

sum() can directly process the collected tuple, so there is no need to iterate over it manually.

2. Implement a Flexible Logging Function

def log(level, *messages, **context):
    message = " ".join(str(item) for item in messages)

    print(f"[{level}] {message}")

    if context:
        print("上下文:", context)


log(
    "INFO",
    "用户登录成功",
    "操作完成",
    user_id=1001,
    ip="127.0.0.1"
)

Output:

[INFO] User login successful Operation completed
Context: {'user_id': 1001, 'ip': '127.0.0.1'}

Here:

  • level is a fixed parameter.
  • messages collects multiple log messages.
  • context collects additional contextual information.

3. Function Wrapping and Argument Forwarding

In practical development, you often need to define a function that executes additional logic before or after calling another function.

def target(name, age):
    print(f"{name},{age}岁")


def wrapper(*args, **kwargs):
    print("开始执行")
    target(*args, **kwargs)
    print("执行结束")


wrapper("Alice", 25)

Output:

Execution started
Alice, 25 years old
Execution finished

wrapper can receive and forward call arguments without needing to know the specific parameter structure of the target function in advance.

This is an important foundation for decorators and generic function wrappers.

4. Implement a Function Decorator

from functools import wraps


def log_call(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        print("调用函数:", func.__name__)

        result = func(*args, **kwargs)

        print("函数执行完成")

        return result

    return wrapper


@log_call
def add(a, b):
    return a + b


print(add(10, 20))

Output:

Calling function: add
Function execution completed
30

Here: