SoFunction
Updated on 2025-03-04

Detailed explanation of Python prohibiting position parameter transfer function

Python prohibits position-transferring function

This method of defining functions uses the keyword-only arguments in Python, and uses it in the parameter list.*Symbols serve as delimiters to explicitly indicate that the parameters after the function must be passed using keywords (i.e. parameter names) and cannot be passed through position (i.e. in order).

In the function definition:

def init(
    *,
    args: List[str] | None = None,
    context: Context = None,
    domain_id: int | None = None,
    signal_handler_options: SignalHandlerOptions | None = None
) -> None

All parameters (args, context, domain_id, signal_handler_options) are all keyword arguments, which means that when calling this function, you must explicitly use the parameter name to specify the value of each argument, and you cannot pass them by just the position.

For example:

# The correct way to callinit(args=["some", "args"], context=some_context, domain_id=123, signal_handler_options=options)

# Incorrect call method (Can raise TypeError)init(["some", "args"], some_context, 123, options)

In the second way of calling, because the parameter name is not used, the Python interpreter cannot correctly map the provided value to the function's parameters, so it throws aTypeError

This design is especially useful when a function requires a lot of parameters, or the order of parameters may be confusing the caller.

It increases the readability and robustness of the code, because the caller must clearly indicate the value of each parameter.

Avoid parameter changes when passing parameters in python

import os
import collections
import math
import sys

# We know that when using python, when passing parameters, unlike C++, the parameter passing is a value passing, and the actual value of the parameter is not changed; the parameter will only be changed when passing references.# However, in Python, the passing of parameters is divided into mutable types and immutable types. For example, list is mutable types and tuple is immutable types. Here are two methods to avoid parameter changes.# The first one is to use the following v[:] to operate on the list"""
def main(v, cnt):
    if cnt == 5:
        (cnt)
        print(v)
        return
    (cnt)
    main(v[:], cnt+1)
    print(v)
    return
"""

"""
v = [1, 2, 3]
main(v[:], 4)
"""

# The second type is to use tuple when passing parameters. In the function, turn tuple into list and modify it."""def main(v, cnt):
    if cnt == 5:
        tmp = list(v)
        (cnt)
        print(tmp)
        return
    tmp=list(v)
    (cnt)
    main(tuple(tmp), cnt+1)
    print(tmp)
    return

v=[1,2,3]
main(tuple(v),4)"""


Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.