斜杠在help()输出中意味着什么?

问题:斜杠在help()输出中意味着什么?

在闭括号前/,Python 3.4的help输出是什么意思range

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return a virtual sequence of numbers from start to stop by step.
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.

                                        ...

What does the / mean in Python 3.4’s help output for range before the closing parenthesis?

>>> help(range)
Help on class range in module builtins:

class range(object)
 |  range(stop) -> range object
 |  range(start, stop[, step]) -> range object
 |  
 |  Return a virtual sequence of numbers from start to stop by step.
 |  
 |  Methods defined here:
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.

                                        ...

回答 0

它象征着结束位置唯一参数,参数,你不能作为关键字参数使用。在Python 3.8之前,只能在C API中指定此类参数。

这意味着keyto 的参数__contains__只能通过position(range(5).__contains__(3))传递,而不能作为关键字参数(range(5).__contains__(key=3))传递,这可以通过pure-python函数中的position参数完成。

另请参阅Argument Clinic文档:

要将所有参数标记为Argument Clinic中的“仅位置”,请/在最后一个参数之后单独添加一行,并使其与参数行缩进。

和(最近添加的)Python FAQ

函数的参数列表中的斜杠表示该函数之前的参数仅是位置参数。仅位置参数是没有外部可用名称的参数。调用仅接受位置参数的函数后,参数将仅基于其位置映射到参数。

3.8版开始,该语法现已成为Python语言规范的一部分,请参阅PEP 570 – 仅Python位置参数。在PEP 570之前,已经保留了该语法以供将来将来包含在Python中,请参阅PEP 457- 仅位置参数的语法

仅位置参数可以导致更清晰的API,使原本仅C语言的模块的纯Python实现更加一致且易于维护,并且由于仅位置参数需要很少的处理,因此它们可导致更快的Python代码。

It signifies the end of the positional only parameters, parameters you cannot use as keyword parameters. Before Python 3.8, such parameters could only be specified in the C API.

It means the key argument to __contains__ can only be passed in by position (range(5).__contains__(3)), not as a keyword argument (range(5).__contains__(key=3)), something you can do with positional arguments in pure-python functions.

Also see the Argument Clinic documentation:

To mark all parameters as positional-only in Argument Clinic, add a / on a line by itself after the last parameter, indented the same as the parameter lines.

and the (very recent addition to) the Python FAQ:

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.

The syntax is now part of the Python language specification, as of version 3.8, see PEP 570 – Python Positional-Only Parameters. Before PEP 570, the syntax was already reserved for possible future inclusion in Python, see PEP 457 – Syntax For Positional-Only Parameters.

Positional-only parameters can lead to cleaner and clearer APIs, make pure-Python implementations of otherwise C-only modules more consistent and easier to maintain, and because positional-only parameters require very little processing, they lead to faster Python code.


回答 1

我自己问了这个问题。:)发现这/是Guido最初在这里提出的。

替代方案:使用’/’怎么样?它与“ *”相反,后者表示“关键字参数”,而“ /”不是新字符。

然后他的提议获胜

嘿。如果是这样,我的“ /”建议将获胜:

 def foo(pos_only, /, pos_or_kw, *, kw_only): ...

我认为涉及此的非常相关的文件是PEP 570。回顾部分看起来不错。

回顾

用例将确定在函数定义中使用哪些参数:

 def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):

作为指导:

仅在名称无关紧要或名称没有含义且仅会以相同顺序传递少数参数的情况下,才使用仅位置。当名称具有含义且通过使用名称明确表示功能定义时,请仅使用关键字。


如果函数以 /

def foo(p1, p2, /)

这意味着所有功能参数都是位置性的。

I asked this question myself. :) Found out that / was originally proposed by Guido in here.

Alternative proposal: how about using ‘/’ ? It’s kind of the opposite of ‘*’ which means “keyword argument”, and ‘/’ is not a new character.

Then his proposal won.

Heh. If that’s true, my ‘/’ proposal wins:

 def foo(pos_only, /, pos_or_kw, *, kw_only): ...

I think the very relevant document covering this is PEP 570. Where recap section looks nice.

Recap

The use case will determine which parameters to use in the function definition:

 def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):

As guidance:

Use positional-only if names do not matter or have no meaning, and there are only a few arguments which will always be passed in the same order. Use keyword-only when names have meaning and the function definition is more understandable by being explicit with names.


If the function ends with /

def foo(p1, p2, /)

This means all functional arguments are positional.


回答 2

正斜杠(/)表示之前的所有参数都是位置唯一的参数。在接受PEP 570之后,在python 3.8中添加了仅位置参数功能。最初,此表示法是在PEP 457-仅位置参数表示法中定义的

在函数定义中,Foraward斜杠(/)之前的参数仅是位置参数,后跟斜杠(/)的参数根据语法可以是任何种类。仅在调用函数时根据参数的位置将参数映射到仅位置参数。通过关键字(名称)传递仅位置参数无效。

让我们来看下面的例子

def foo(a, b, / , x, y):
   print("positional ", a, b)
   print("positional or keyword", x, y)

在上面的函数定义中,参数a和b仅是位置信息,而x或y可以是位置信息或关键字。

以下函数调用有效

foo(40, 20, 99, 39)
foo(40, 3.14, "hello", y="world")
foo(1.45, 3.14, x="hello", y="world")

但是,以下函数调用无效,从而引发TypeError异常,因为a,b没有作为位置参数传递,而是作为关键字传递

foo(a=1.45, b=3.14, x=1, y=4)

TypeError:foo()获得了一些仅位置参数作为关键字参数传递:’a,b’

python中的许多内置函数仅接受位置参数,而按关键字传递参数没有意义。例如,内置函数len仅接受一个positional(only)参数,如果将len调用为len(obj =“ hello world”)会损害可读性,则检查help(len)。

>>> help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

仅位置参数使基础c /库函数易于维护。它允许将来仅更改位置参数的参数名称,而不会破坏使用API​​的客户端代码的风险

最后但并非最不重要的一点是,仅位置参数允许我们使用其名称在可变长度关键字参数中使用。检查以下示例

>>> def f(a, b, /, **kwargs):
...     print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}

仅位置参数比较好此处在python中的函数参数类型中进行了解释:仅位置参数

仅位置参数语法已正式添加到python3.8中。签出python3.8的新功能-仅位置参数

与PEP相关:PEP 570-Python仅位置参数

Forward Slash (/) indicates all arguments prior to it are positional only argument. Positional only arguments feature was added in python 3.8 after PEP 570 was accepted. Initially this notation was defined in PEP 457 – Notation for Notation For Positional-Only Parameters

Parameters in function definition prior Foraward slash (/) are positional only and parameters followed by slash(/) can be of any kind as per syntax. Where arguments are mapped to positional only parameters solely based on their position upon calling a function. Passing positional-only parameters by keywords(name) is invalid.

Let’s take following example

def foo(a, b, / , x, y):
   print("positional ", a, b)
   print("positional or keyword", x, y)

Here in the above function definition parameters a and b are positional-only, while x or y can be either positional or keyword.

Following function calls are valid

foo(40, 20, 99, 39)
foo(40, 3.14, "hello", y="world")
foo(1.45, 3.14, x="hello", y="world")

But, following function call is not valid which raises an exception TypeError since a, b are not passed as positional arguments instead passed as keyword

foo(a=1.45, b=3.14, x=1, y=4)

TypeError: foo() got some positional-only arguments passed as keyword arguments: ‘a, b’

Many built in function in python accept positional only arguments where passing arguments by keyword doesn’t make sense. For example built-in function len accepts only one positional(only) argument, Where calling len as len(obj=”hello world”) impairs readability, check help(len).

>>> help(len)
Help on built-in function len in module builtins:

len(obj, /)
    Return the number of items in a container.

Positional only parameters make underlying c/library functions easy to maintain. It allows parameters names of positional only parameters to be changes in future without risk of breaking client code that uses API

Last but not least, positional only parameters allow us to use their names to be used in variable length keyword arguments. Check following example

>>> def f(a, b, /, **kwargs):
...     print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}

Positional only parameters is better Explained here at Types of function arguments in python: Positional Only Parameters

Positional-only parameters syntax was officially added to python3.8. Checkout what’s new python3.8 – positional only arguments

PEP Related: PEP 570 — Python Positional-Only Parameters