【问题标题】:Python 3 type hints in Python 2Python 2 中的 Python 3 类型提示
【发布时间】:2018-11-14 18:15:17
【问题描述】:

我有 python def 定义似乎适用于 python3:

def get_default_device(use_gpu: bool = True) -> cl.Device:

在python2下出现以下语法错误:

Traceback (most recent call last):
  File "map_copy.py", line 9, in <module>
    import utility
  File "/home/root/pyopencla/ch3/utility.py", line 6
    def get_default_device(use_gpu: bool = True) -> cl.Device:
                                  ^
SyntaxError: invalid syntax

如何使类型提示与 python2 兼容?

【问题讨论】:

标签: python python-2.x python-typing


【解决方案1】:

PEP 3107 中为 Python 3.0 引入了函数注释。在 Python 3.5+ 的 PEP 484 中正式将注解用作类型提示。

3.0 之前的任何版本都将完全不支持您用于类型提示的语法。但是,PEP 484 offers a workaround,一些编辑可能会选择兑现。在您的情况下,提示将如下所示:

def get_default_device(use_gpu=True):
    # type: (bool) -> cl.Device
    ...

或更详细地说,

def get_default_device(use_gpu=True  # type: bool
                      ):
    # type: (...) -> cl.Device
    ...

PEP 明确指出,这种形式的类型提示应该适用于任何版本的 Python,如果它完全受支持的话。

【讨论】:

  • PEP484 在这种情况下不是相关来源。类型提示只是函数注释的一种应用,它由PEP3107 为 Python 3.0 引入。
  • @chepner。我已经更新了。虽然我同意注释从 Py 3.0 开始有效,但相关的 PEP 仍然是 484(引用 3107)。
  • 但是为什么他们不只是允许和忽略 py2 中的语法,以便您至少可以使用相同的源代码?
  • @Trass3r。我认为没有from __future__ import ... 选项,因为它会涉及对解释器进行太多更改。
猜你喜欢
  • 2016-05-15
  • 2013-10-12
  • 2018-04-14
  • 2010-11-25
  • 2019-02-08
  • 2020-01-26
  • 2020-10-24
相关资源
最近更新 更多