对Python3中的类型提示感到困惑

时间:2017-03-10 19:22:47

标签: python python-3.x types pycharm type-hinting

昨天我从2.7升级到3.6。我也开始使用类型提示。这里 是我的代码片段:

import numpy as np
from typing import Union, Tuple, Sequence, Any

Vector = Union[np.ndarray, Tuple[float, float, float]]
Matrix = np.ndarray
Tetra = Tuple[Vector, Vector, Vector, Vector]
...
def transform_ref2tetra(tetra: Tetra) -> Matrix:
    """ Return the matrix M that transforms the points of the reference tetra
    R=[[1,0,0],[0,1,0],[0,0,1],[0,0,0]] to tetra, i.e., M.R=tetra.
    """
    ...

在PyCharm2016.3.2中,我要求获得快速文档:

def transform_ref2tetra(tetra: Tetra)
Inferred type: (tetra: Tuple[Any, Any, Any, Any]) -> ndarray

Return the matrix M that transforms the points of the reference tetra
R=[[1,0,0],[0,1,0],[0,0,1],[0,0,0]] to tetra, i.e., M.R=tetra.

这不仅仅是一个文档问题;如果我打电话:

transform_ref2tetra(tetra=("a","b","c","d"))

我没有得到警告(当然,我在运行时遇到错误)。

知道发生了什么事吗?这是PyCharm问题还是我做错了什么?

1 个答案:

答案 0 :(得分:0)

这看起来像PyCharms'型检查工具; Tetra作为一种类型,由Python正确定义:

>>> Tetra
typing.Tuple[typing.Union[numpy.ndarray, typing.Tuple[float, float, float]], typing.Union[numpy.ndarray, typing.Tuple[float, float, float]], typing.Union[numpy.ndarray, typing.Tuple[float, float, float]], typing.Union[numpy.ndarray, typing.Tuple[float, float, float]]]

由于某种原因,PyCharm似乎将此转换为Any s,这是错误的,并导致tetra=("a","b","c","d")被接受为有效的情况。

您应该将此提交给PyCharms问题跟踪器,但我最好的猜测是Any被使用,因为找不到numpy的任何存根文件。