繁体   English   中英

在 Python 中用作返回类型时,Ellipses 是什么意思,为什么要使用它?

[英]What does Ellipses mean when used as the return type in Python, and why use it?

我研究了 Python 的省略号,并且已经在线阅读了许多线程和博客文章,最相关的是这个堆栈溢出线程 还阅读了Ellipses 上的 python 文档

到目前为止,没有任何文章/文档涵盖的是在类型签名中将省略号本身用作返回类型时的含义,例如:

def my_function(a : int) -> ...:
  # code that does stuff

返回 "..." 类型是什么意思,为什么我们更喜欢它而不是typing.Any

对我来说看起来像是一个错字,或者它是演示代码中的一个占位符,他们希望用其他东西填充它,也许没有。

如果我通过mypy --strict运行以下命令:

def foo() -> ...:
    pass

我收到一个错误:

ellip.py:1: error: Unexpected "..."
Found 1 error in 1 file (checked 1 source file)

适当地表明...不是有效的语法 - 不是预期的类型。 如果你真的想返回一个Ellipsis object 你会想做类似的事情:

from types import EllipsisType

def foo() -> EllipsisType:
    return ...

在 Python 3.10 和 Mypy 0.971 下对我有用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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