Back to series
· 7 min read

Python Positional and Keyword Arguments


I. What Are Positional and Keyword Arguments?

When calling a Python function, the actual arguments must be mapped to the formal parameters in the function definition. Depending on how the arguments convey information, there are two basic forms:

  • Positional Arguments: matched according to the parameter's position in the function definition.
  • Keyword Arguments: explicitly specify the corresponding formal parameter by parameter name.

1. Positional Arguments

Positional arguments are matched to the function's formal parameters based on the order in which they are passed.

def introduce(name, age, city):
    print(f"姓名:{name}")
    print(f"年龄:{age}")
    print(f"城市:{city}")


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

Output:

Name: Alice
Age: 25
City: Tokyo

Parameter binding:

Formal Parameter Actual Argument Matching Method
name "Alice" First position
age 25 Second position
city "Tokyo" Third position

Characteristics of positional arguments:

  1. The argument order must correspond to the order of the formal parameters in the function definition.
  2. Parameter names do not need to be written explicitly.
  3. Calls are concise and suitable when the parameter meanings are clear and the number of parameters is small.
  4. If the argument order is wrong, it may cause semantic errors or even runtime exceptions.

For example:

def calculate(a, b):
    return a - b


print(calculate(10, 3))  # 7
print(calculate(3, 10))  # -7

Both calls are valid, but the results differ because the order of the positional arguments has changed.

2. Keyword Arguments

Keyword arguments specify actual arguments by formal parameter name and do not depend on the order in which the arguments are arranged.

def introduce(name, age, city):
    print(f"姓名:{name}")
    print(f"年龄:{age}")
    print(f"城市:{city}")


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

You can also change the order of the keyword arguments:

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

The output is the same.

Characteristics of keyword arguments:

  1. Binding is established through parameter names.
  2. Arguments do not have to be passed in the order in the function definition.
  3. Readability is stronger, making them suitable for functions with many parameters or unclear parameter meanings.
  4. They can reduce misuse caused by incorrect argument order.

3. Comparison of the Two Approaches

Aspect of Comparison Positional Arguments Keyword Arguments
Basis for Matching Argument position Argument name
Order Requirement Must correspond to formal parameter order No fixed order required
Readability Depends on parameter meanings Usually clearer
Call Form func(10, 20) func(a=10, b=20)
Common Scenarios Simple, clear parameters Many parameters, configuration-style calls

II. Mixing Positional and Keyword Arguments

Python allows positional and keyword arguments to be mixed in the same function call, but specific rules must be followed.

1. Positional Arguments Must Come Before Keyword Arguments

Correct example:

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


create_user("Alice", age=25, city="Tokyo")

Here:

  • "Alice" matches name by position.
  • age=25 matches age by name.
  • city="Tokyo" matches city by name.

Incorrect example:

create_user(name="Alice", 25, city="Tokyo")

This raises a SyntaxError, because positional arguments cannot follow keyword arguments.

2. Positional and Keyword Arguments Cannot Assign the Same Parameter Repeatedly

The same formal parameter cannot be assigned both positionally and by keyword at the same time.

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


introduce("Alice", name="Bob", age=25)

When run, it raises a TypeError:

TypeError: introduce() got multiple values for argument 'name'

The reason is:

  • "Alice" has already been bound to name as the first positional argument.
  • name="Bob" then attempts to assign a value to name again.
  • The same parameter is bound more than once.

3. Binding Process for Mixed Calls

For example:

def order(product, quantity, price):
    print(product, quantity, price)


order("Laptop", price=5999, quantity=2)

Parameter binding relationships:

Passed argument Bound parameter
"Laptop" product
price=5999 price
quantity=2 quantity

In mixed calls, Python matches arguments by position and by name separately.

flowchart TD
    A["Start function call"] --> B["Receive arguments"]
    B --> C["Process positional arguments"]
    C --> D["Bind parameters in order"]
    D --> E["Process keyword arguments"]
    E --> F["Bind parameters by name"]
    F --> G{"Is there duplicate binding?"}
    G -->|Yes| H["Raise TypeError"]
    G -->|No| I{"Is any required parameter unassigned?"}
    I -->|Yes| J["Raise TypeError"]
    I -->|No| K["Complete parameter binding"]
    K --> L["Execute function body"]

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

Note: The above is a simplified flow for ease of understanding. Actual calls also involve rules such as restrictions on argument kinds, handling default values, and collecting variable arguments.

III. Ordering Rules for Positional and Keyword Arguments

To understand function call rules, the key is to distinguish the order in which arguments are passed from the order in which parameters are defined.

1. Positional Arguments Are Bound in Definition Order

def register(username, email, age):
    print(username, email, age)


register("Tom", "tom@example.com", 20)

The correspondence is:

First positional argument → username
Second positional argument → email
Third positional argument → age

If the positional order changes, Python will not automatically determine the meaning of the parameters based on the data itself.

2. Keyword Arguments Can Be Reordered

def register(username, email, age):
    print(username, email, age)


register(
    age=20,
    username="Tom",
    email="tom@example.com"
)

Keyword arguments are matched by name, so they can be reordered freely.

3. Positional Constraints in Mixed Use

def connect(host, port, timeout):
    print(host, port, timeout)


# Correct
connect("localhost", 8080, timeout=30)

# Correct
connect("localhost", port=8080, timeout=30)

# Correct
connect(host="localhost", port=8080, timeout=30)

The following form is invalid:

connect(host="localhost", 8080, timeout=30)

Because positional arguments cannot appear after keyword arguments.

IV. Default Parameters, Positional Parameters, and Keyword Parameters

Default parameters allow you to specify default values for parameters when defining a function. When calling the function, you can omit that parameter or pass it explicitly.

1. Basic Usage of Default Parameters

def greet(name, message="Hello"):
    print(f"{message}, {name}!")


greet("Alice")
greet("Alice", "Welcome")
greet("Alice", message="Good morning")

Output:

Hello, Alice!
Welcome, Alice!
Good morning, Alice!

Here:

  • name is a required parameter.
  • message is a parameter with a default value.
  • When message is omitted, the default value is used.
  • When message is passed explicitly, the value provided by the caller is used.

2. Default Parameters Must Follow the Definition Order

Among ordinary parameters, a parameter with a default value cannot appear before a parameter without a default value.

Incorrect example:

def create_user(name="Alice", age):
    pass

This raises a SyntaxError.

Correct way to write it:

def create_user(name, age=18):
    print(name, age)

3. Default Parameters Can Be Overridden by Keyword

def connect(host, port=8080, timeout=10):
    print(host, port, timeout)


connect("localhost")
connect("localhost", 9000)
connect("localhost", timeout=30)
connect("localhost", port=9000, timeout=30)

Output:

localhost 8080 10
localhost 9000 10
localhost 8080 30
localhost 9000 30

When there are many parameters, using keyword arguments to override default values is usually clearer than relying on position.

V. Positional-Only Parameters and Keyword-Only Parameters

Python not only supports positional and keyword arguments, but also allows the function definer to restrict how parameters are passed.

Python 3.8 introduced two important parameter separators:

  • /: indicates that the parameters before it can only be passed positionally.
  • *: indicates that the ordinary parameters after it can only be passed by keyword.

1. Positional-Only Parameters

Using / restricts certain parameters so that they can only be passed positionally.

def calculate(a, b, /):
    return a + b


print(calculate(10, 20))

The following call is not allowed:

calculate(a=10, b=20)

Because a and b are located before /, they can only be passed as positional arguments.

Complete definition example:

def calculate(a, b, /, c):
    return a + b + c


calculate(10, 20, 30)
calculate(10, 20, c=30)

Parameter classification:

Parameter Parameter Type Call Method
a Positional-only parameter calculate(10, 20, 30)
b Positional-only parameter calculate(10, 20, 30)
c Ordinary parameter Either positional or keyword

2. Keyword-Only Parameters

Using * restricts the ordinary parameters after it so that they can only be passed by keyword.

def create_user(name, *, age, city):
    print(name, age, city)


create_user("Alice", age=25, city="Tokyo")

The following call is not allowed:

create_user("Alice", 25, "Tokyo")

Because age and city come after *, they must be passed by keyword.

3. Using / and * together

The two separators can be combined to form a clearer parameter interface.

def configure(host, port, /, timeout, *, debug, retry):
    print(host, port, timeout, debug, retry)


configure(
    "localhost",
    8080,
    30,
    debug=True,
    retry=3
)

Parameter categories:

Parameter Type Passing method
host positional-only parameter can only be passed by position
port positional-only parameter can only be passed by position
timeout regular parameter position or keyword
debug keyword-only parameter can only be passed by name
retry keyword-only parameter can only be passed by name

4. Complete structure of parameter kinds

Python function parameters can be organized in the following order:

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

Meaning of each part:

Parameter part Type Description
a, b positional-only parameters must be passed by position
c regular parameter passed by position or keyword
d regular parameter with a default value can be omitted
args variadic positional parameter collects extra positional arguments
e keyword-only parameter must be passed by name
f keyword-only parameter with a default value can be omitted
kwargs variadic keyword parameter collects extra keyword arguments

Example call:

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


example(
    1, 2, 3, 4, 5, 6,
    e=7,
    f=8,
    debug=True,
    mode="fast"
)

Output:

1 2 3 4
(5, 6)
7 8
{'debug': True, 'mode': 'fast'}

Note the following:

  • *args collects extra positional arguments not received by other parameters.
  • **kwargs collects extra keyword arguments not received by other parameters.
  • Regular parameters after *args can only be passed by keyword.
  • **kwargs must appear at the end of the parameter definition.

VI. Argument Unpacking, Positional Arguments, and Keyword Arguments

Python supports using * and ** to unpack iterables and mapping objects and pass their data to functions.

1. Using * to unpack positional arguments

When the elements in a list or tuple need to be passed as separate positional arguments, you can use *.

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


numbers = [10, 20, 30]

print(add(*numbers))

Equivalent to:

add(10, 20, 30)

*numbers expands the elements in the iterable one by one into positional arguments.

2. Using ** to unpack keyword arguments

When the keys in a dictionary correspond to function parameter names, you can use **.

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


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

introduce(**user)

Is equivalent to:

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

Note:

  • After **, you need to supply a mapping object, usually a dictionary.
  • The keys of the dictionary must be strings and must satisfy the requirements for keyword names.
  • If the unpacked result binds the same parameter again alongside another argument, a TypeError will be raised.

3. Using * and ** 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)

Is equivalent to:

create_order(
    "Laptop",
    2,
    price=5999,
    currency="CNY"
)