gpt4 book ai didi

python-3.x - python 3 : Ellipsis in function parameters?

转载 作者:行者123 更新时间:2023-12-04 14:22:18 25 4
gpt4 key购买 nike

我最近遇到了 aiohttp code 中函数参数中使用的省略号 ( ... )然后在该函数的主体中:

def make_mocked_request(method, path, headers=None, *,
match_info=sentinel,
version=HttpVersion(1, 1), closing=False,
app=None,
writer=sentinel,
protocol=sentinel,
transport=sentinel,
payload=sentinel,
sslcontext=None,
client_max_size=1024**2,
loop=...):
"""Creates mocked web.Request testing purposes.

Useful in unit tests, when spinning full web server is overkill or
specific conditions and errors are hard to trigger.

"""

task = mock.Mock()
if loop is ...:
loop = mock.Mock()
loop.create_future.return_value = ()


你能解释一下这个新的 python 3 功能吗?

最佳答案

Ellipsis是 Python 中的内置常量。在 Python 3 中,它具有文字语法 ...所以它可以像任何其他文字一样使用。这被 Guido 接受对于 Python 3,因为 some folks thought it would be cute .

您找到的代码(默认用作函数参数)显然是一种“可爱”的用法。稍后在该代码中,您将看到:

if loop is ...:
loop = mock.Mock()
loop.create_future.return_value = ()

它只是被用作哨兵,在这里,也可能是 object()或其他任何东西 - Ellipsis 没有任何特定内容.也许是通常的哨兵, None , 在这种情况下还有其他特定含义,尽管我在 the commit 中看不到任何证据。 (似乎 None 也可以正常工作)。

有时在野外看到的省略号文字的另一个用例是尚未编写的代码的占位符,类似于 pass 语句:
class Todo:
...

对于涉及扩展切片语法的更典型用例,请参阅 What does the Python Ellipsis object do?

关于python-3.x - python 3 : Ellipsis in function parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54405918/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com