【问题标题】:Typing problems in PyCharmPyCharm 中的打字问题
【发布时间】:2017-04-29 20:54:06
【问题描述】:

我有以下功能:

def clock(dimS: Tuple[int] =(0)) -> Generator[Tuple[int], None, None]:
    """ Produce coordinates """
    itr = 0
    dim = len(dimS)
    maxItr = np.prod(dimS)

    if (dim < 1):
        raise ValueError(
            'function clock expected positive number of dimensions, received: 0'
        )

    while itr < maxItr:
        c = []
        ind = itr

        # build coordinate
        for i in range(dim):
            s = dimS[dim - i - 1]
            g = ind % s
            ind //= s       # update
            c.append(g)

        itr += 1
        yield tuple(reversed(c))

我正在使用 PyCharm 来编辑我的代码(喜欢它)。它告诉我类型 Generator[Tuple[int], None, None] 是预期的,而是 got no return ?当我将其更改为Generator[Tuple[int], None, bool] 并添加一行return True 时,如the documentation 示例中,IDE 突出显示True 并告诉我Expected Generator[Tuple[int], None, bool], got bool。我该如何解决这个问题?


这是一个做同样事情的更简单的例子:

from typing import Generator

def foo(i: int =0) -> Generator[int, None, None]:
    while True:
        i += 1
        yield i

它突出显示Generator[int, None, None] 并告诉我got no return

【问题讨论】:

  • @AndrewLi 我不关注...
  • @AndrewLi Ahh 是的,但是这个函数与文档中的第二个示例有何不同? return 也没有任何价值,至少没有那个关键字;他们只在注释中将Generator 中的YieldType 指定为int。他们明确谈论使用 Generator 注释生成器的返回类型注释。
  • PyCharm 可能无法正确处理生成器类型 - 您是否查看过是否存在未解决的问题?尝试了一个更简单的示例来确保处理正确?
  • @jonrsharpe 我添加了一个更简单的例子,它做同样的事情(编辑:我犯了一个简单的错误,但它仍然做同样的事情)。

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


【解决方案1】:

mypy 毫无问题地接受您的示例输入。从表面上看,这是 PyCharm 的一个问题。

扫描 JetBrains 的错误跟踪器,我发现了一个与您遇到的问题有关的问题,请参阅 Return type hint messes up with 'Generator' type

【讨论】:

  • 问题指出它已修复 @bjd2385 不知道 PyCharm 开发进展如何,但我猜如果您获得最新版本,您将获得预期结果。
  • 我从他们的网站下载并安装了它,所以我不知道我的版本怎么会过时。
  • @bjd2385 据我所知,修复是最近才执行的,很可能包含修复的构建尚未发布。等到下一个版本发布,如果 仍然 没有按预期执行,您应该在他们的错误跟踪器中提出适当的问题。
  • 昨晚 PyCharm 提示我获取更新(右下角的弹出窗口),它解决了这个问题。感谢您的所有帮助;看来我只比修复提前了一天。
  • 另外,我在参加 PyCon 后检查了 Mypy,它真的很有用!
猜你喜欢
  • 2022-12-29
  • 1970-01-01
  • 2020-06-09
  • 2019-12-05
  • 1970-01-01
  • 2019-02-12
  • 1970-01-01
  • 1970-01-01
  • 2019-02-01
相关资源
最近更新 更多