Python Mandatory Keyword Arguments

Mandatory keyword parameters are a new feature introduced in version 3.1. The purpose is to add regular parameters (optional default values) after variable-length positional parameters or keyword parameters. The assignment must be forced to be passed in by keywords.

Mandatory keyword arguments are different from keyword arguments.


1) The following argument list is not allowed in Python 2, but now a is a mandatory keyword argument, assignment to a must force "a=xx"

>>> def foo(*args, a):
... print(args, a)
foo(1,2,3,4): error, a is not assigned
foo(1,2,3,4, a= 5): Correct

>>> def foo(*args, a=5):
... print(args, a)
foo(1,2,3,4): Correct, but a is default 5


2) Introduce *
If a variable-length positional parameter or a keyword parameter is followed by a regular parameter, then the regular parameter must be a mandatory keyword parameter, but how can a regular parameter be followed by a mandatory keyword parameter?
def compare(a, b, *, q1, q2=3):
    ...
The words after "*" are mandatory keyword arguments. In the above example, q1 and q2 are mandatory keyword arguments

>>> def foo(a ,b,c=3): # c is a keyword argument
... print(a,b,c)
foo(1,2,4): returns "1 2 4"

>>> def foo(a,b, *,c=3): # c is a mandatory keyword argument
... print(a,b,c)

foo(1,2,4): error, c is not assigned
foo(1,2,c=4) : true, returns "1 2 4"


In short:
Mandatory keyword argument assignments must be explicitly passed in via keyword.

When the mandatory keyword parameter has no default value, it must be assigned a value when calling, otherwise an error will be reported; when the mandatory keyword parameter has a default value, if it is not explicitly assigned when calling, it will use the default value.


If there is any inappropriateness in the text, please forgive and point out, thank you


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325561858&siteId=291194637