【问题标题】:Confused about type hints in Python3对 Python3 中的类型提示感到困惑
【发布时间】:2017-08-01 06:14:29
【问题描述】:

昨天我从 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 问题还是我做错了什么?

【问题讨论】:

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


    【解决方案1】:

    这看起来像是 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 似乎将其转换为 Anys,这是错误的,并导致 tetra=("a","b","c","d") 等情况被接受为有效。

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

    【讨论】:

    • 这看起来很有希望,但我认为情况并非如此。即使我将 np.ndarray 更改为 int 我也得到了 Any's
    • @Eduardo 我真的不知道 PyCharm 的类型检查器是如何工作的。 mypy,另一个类型检查器,检查它正确,所以我只能推断 PyCharm 出了点问题。
    猜你喜欢
    • 2019-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多