Have you really mastered Python’s seven parameters?

I don’t know why people on the Internet always say that there are 4 or 5 parameter types in Python, but they don’t know that there are actually 7 types. Python's seven parameters are  default parameters , positional parameters , keyword parameters , variable-length positional parameters , variable-length keyword parameters , positional-only parameters  and  keyword-only parameters . Newbies may have never seen "variable length parameters", but most people may have never seen "parameters only". "Parameters only" are generally only used when developing modules, so why do I know? Guess... let me tell you in detail.

Let’s look at a piece of code first. Most people can’t understand it:

def function(a, /, b, c=1, *, d=2, **e) -> None: ...

The above code can run normally. It reflects almost all parameter types, almost, but not completely. Because there are several parameter types that cannot coexist with each other.

1. Default Parameter

The default parameter is simple and literal. When you don't give it a value, it will have a default value. Because sometimes it is default if you don't pass a specific value, so it is also called a default parameter.

def function(default_parameter: int = 1) -> int:
    return default_parameter

The above function, if you do not pass a value to it, it will return 1 by default. If a value is passed, it will return the value you passed in. Is not it simple? If you think so, you are totally wrong . What do you think the output of the following code is?

def function(default_parameter=[1]) -> None:
    print(default_parameter)
    default_parameter.append(default_parameter[-1] + 1)

function()
function()
function()

Here is the output:

[1]
[1, 2]
[1, 2, 3]

For a detailed explanation, see (seventh point in the linked article): A large collection of Python error-prone points

This is the most common pitfall in default parameters. Most people will jump into it. A company once made this fatal mistake in its business code, which directly caused the server to crash because the list became abnormally large...

2. Positional Parameter

Positional parameters are what we use every day. We love hearing about them, and they are the ones everyone uses.

def function(a: int, b: float, c: str) -> None:
    print(a + b, c)

The so-called "position" means that parameters are passed by position. The position of positional parameters is not strictly required. You can pass parameters like keyword parameters. For example:

def function(a: int, b: int) -> None:
    print(a, b)

function(1, 2)
function(b=2, a=1)

 The output results of the above two calling methods are the same, both 1 and 2. In fact, the essence of positional parameters is to use tuples to pass parameters, which will be explained in detail later.

3. Keyword Parameter

Keyword parameters can also be understood literally. It is "key" and its name must be specified to pass parameters. It is as simple as that.

When talking about positional parameters above, we also talked about keyword parameters. Keyword parameters do not care about the position of the parameter, as long as the parameter name is specified. Keyword parameters are similar to positional parameters. In fact, a dictionary is used to pass parameters. The key of the dictionary is the parameter name in string form, and the value is the value of the corresponding parameter.

4. Variable-length Positional Parameter

 Variable-length positional parameters, also called variable-length positional parameters or variable-length positional parameters, are generally written as *args. args is the abbreviation of the plural form of the English word argument. "Variable length" means that the number of parameters is uncertain. That is, it has no limit on the number of parameters.

def function(*args: int) -> tuple[int]:
    for arg in args:
        print(arg)
    return args

function(1)
function(1, 2)
function(1, 2, 3)

The above function returns a tuple, that is to say, args is actually a tuple, which is related to the fact that positional parameters are passed in tuples...

In fact, the above code can also be written like this:

def function(*args: int) -> tuple[int]:
    print(*args)
    return args

Someone is wondering, what does *args mean? This involves the knowledge of Python's sequence unpacking (have you never heard of this again?) For details, see: The wonderful use of Python asterisks - Flexible sequence unpacking

The print function is the most typical function in Python that uses variable-length parameters. Its function prototype is as follows (two overloads):

def print(
    *values: object,
    sep: str | None = " ",
    end: str | None = "\n",
    file: SupportsWrite[str] | None = None,
    flush: Literal[False] = False,
) -> None: ...

def print(
    *values: object,
    sep: str | None = " ",
    end: str | None = "\n",
    file: _SupportsWriteAndFlush[str] | None = None,
    flush: bool
) -> None: ...

 That *values ​​is the variable length parameter. In fact, positional parameters are passed after the variable-length positional parameter sequence is unpacked, while variable-length positional parameters are passed directly through the entire tuple.

So let’s expand a bit. Have you always seen on the Internet that Python functions can have multiple return values? is this real? This is a wrong perception! In fact, Python's function still only returns one value. When writing multiple values, Python will automatically turn them into tuples for you. The following code can be verified:

def function():
    a = 1
    b = 2
    return a, b

c = 1, 2

print(type(c))
print(type(function()))

The output results are all tuples. 

5. Variable-length Keyword Parameter

As for variable-length keyword parameters, it can be compared to variable-length positional parameters. Just replace the tuple with a dictionary. Everything else is the same, so I won’t go into details here.

6. Positional-only Parameter

Okay, we finally get to the point. Before looking at the positional parameters, let me introduce you to a brother. It is a slash (/) . It not only means division in Python, but also has a meaning, and it has a special name. It's called Positional-only argument separator . I wonder how many people know this brother?

Just write a slash directly in the parameter list. It forces the preceding parameter to be a positional parameter and cannot be passed using keyword parameters!

It appears in Python’s built-in function isinstance:

def isinstance(
    __obj: object,
    __class_or_tuple: _ClassInfo,
    /  # 这里!这里!这儿出现了仅位置参数分隔符!
) -> bool

Also in int:

class int(
    __x: str | ReadableBuffer | SupportsInt | SupportsIndex | SupportsTrunc = ...,
    /  # 这里!这里!这儿有仅位置参数分隔符!
)

My understanding of this thing is (unofficial understanding). The purpose of this thing is generally to prevent some ordinary people from not understanding the code. Some things are conventional and do not need to be written out deliberately, such as parameter names. After all, you have seen them before. Who writes like this when using int? ? ?

int(__x=1)

The above is wrong code! Although the parameter name is indeed __x, only the positional parameter separator forces it to be a positional parameter, and __x is not allowed to be written out (written out as a keyword parameter)! And writing it out will only be misleading and difficult to read!

7. Keyword-only Parameter

Similarly, before looking at keyword-only parameters, let me introduce you to a brother, which is an asterisk (*) . In Python, it not only means multiplication and sequence unpacking, but also has another meaning. The special name is called Keyword-only argument separator . I wonder how many people know this brother?

Just write an asterisk directly in the parameter list. It forces the parameters behind it to be keyword parameters , and parameters cannot be passed using positional parameters!

My understanding of this (unofficial understanding) is that it is very convenient to modify modules and projects, and has good compatibility with different versions. Unlike positional parameters, once one parameter is missing or added in the middle, all subsequent parameters will be misaligned. leading to unpredictable problems. After this keyword-only parameter separator is written, you can force others to pass it in the form of keyword parameters when using your function to prevent parameter misalignment. This is generally used when there are many parameters. For example, the Python built-in module tkinter has an absurd number of initialization parameters for some control classes:

def __init__(
    self: Canvas,
    master: Misc | None = None,
    cnf: dict[str, Any] | None = {},
    *,  # 这里!这里!这儿有个仅关键字参数分隔符!
    background: str = ...,
    bd: _ScreenUnits = ...,
    bg: str = ...,
    border: _ScreenUnits = ...,
    borderwidth: _ScreenUnits = ...,
    closeenough: float = ...,
    confine: bool = ...,
    cursor: _Cursor = ...,
    height: _ScreenUnits = ...,
    highlightbackground: str = ...,
    highlightcolor: str = ...,
    highlightthickness: _ScreenUnits = ...,
    insertbackground: str = ...,
    insertborderwidth: _ScreenUnits = ...,
    insertofftime: int = ...,
    insertontime: int = ...,
    insertwidth: _ScreenUnits = ...,
    name: str = ...,
    offset: ... = ...,
    relief: _Relief = ...,
    scrollregion: tuple[_ScreenUnits, _ScreenUnits, _ScreenUnits, _ScreenUnits] | tuple[()] = ...,
    selectbackground: str = ...,
    selectborderwidth: _ScreenUnits = ...,
    selectforeground: str = ...,
    state: Literal['normal', 'disabled'] = ...,
    takefocus: _TakeFocusValue = ...,
    width: _ScreenUnits = ...,
    xscrollcommand: _XYScrollCommand = ...,
    xscrollincrement: _ScreenUnits = ...,
    yscrollcommand: _XYScrollCommand = ...,
    yscrollincrement: _ScreenUnits = ...
) -> None

That’s it, now I have a question. After reading this knowledge, if you look back at the code at the beginning, can you tell which parameter types conflict with each other and cannot coexist? Leave your answer in the comment area (I won’t write out the answer [doge]) 


I usually write some module codes myself, so I know these quite well. They are all Python programming tools! It is recommended that everyone also master this knowledge. Although it may not be useful, it is not overwhelming because of the many skills!

Seeing this, I wonder if you have gained some knowledge? If you like it, you might as well  like , collect  and  forward it  ? If you can follow , that would be even better! ! !

This article has been included in a column. The column can be seen at the top of the article. It contains more incredible Python knowledge for you!

Guess you like

Origin blog.csdn.net/weixin_62651706/article/details/132353749