简体   繁体   中英

What is the " / " in the built-in list function descriptions

At the end of the built-in list function descriptions is "/". What is it?

>>> l=[]
>>> help(l.insert)
Help on built-in function insert:

insert(index, object, /) method of builtins.list instance
    Insert object before index.

>>> help(l.index)
Help on built-in function index:

index(value, start=0, stop=9223372036854775807, /) method of builtins.list instance
    Return first index of value.

From Python documentation about help() :

Note that if a slash(/) appears in the parameter list of a function, when invoking help(), it means that the parameters prior to the slash are positional-only.

and from the FAQ entry on positional-only parameters :

What does the slash(/) in the parameter list of a function mean?

A slash in the argument list of a function denotes that the parameters prior to it are positional-only. Positional-only parameters are the ones without an externally-usable name. Upon calling a function that accepts positional-only parameters, arguments are mapped to parameters based solely on their position. For example, divmod() is a function that accepts positional-only parameters. Its documentation looks like this:

>>> help(divmod)
Help on built-in function divmod in module builtins:
>
> divmod(x, y, /)
>    Return the tuple (x//y, x%y).  Invariant: div*y + mod == x.

The slash at the end of the parameter list means that both parameters are positional-only. Thus, calling divmod() with keyword arguments would lead to an error:

>>> divmod(x=3, y=4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: divmod() takes no keyword arguments

There are three kinds of parameters in Python:

  1. Positional-only, which can only be set by positional arguments
  2. "Regular", which can be set either by positional arguments or keyword arguments
  3. Keyword-only, which can only be set by keyword arguments.

When defining a function, a / is used to separate positional-only parameters (at least one) on the left and the rest on the right. If there is no / in the parameter list, there are no positional-only parameters.

The syntax originated in the argument clinic, which is used to define functions for the CPython implementation. Its use appeared in help for such functions before it was added to the syntax of Python itself in PEP-570.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM