【问题标题】:Type Hints Don't Evaluate In Decorators类型提示不在装饰器中评估
【发布时间】:2019-05-19 05:15:15
【问题描述】:

给定

class A:
    pass

class B:
    pass

如果我定义一个新的ACallback 类型,它采用A 的实例

from typing import Callable

ACallback = Callable[[A], None]

并定义一个接受B实例的函数

def b_callback(b: B):
    pass

如果我尝试在预期使用ACallback 的地方使用b_callback,我会收到类型提示警告 - 正如预期的那样。

def test(callback: ACallback):
    pass


test(the_callback)  # <-- "Expected type '(A) -> None', got '(b: B) -> None` instead

但是,如果我创建一个带有 ACallback 的装饰器

def test2(callback: ACallback):
    def decorate(f):
        def new_f(*args, **kwargs):
            return f(*args, **kwargs)
        return new_f
    return decorate

并传递一个不匹配的函数

@test2(the_callback)  # <-- No type hint errors
def decorator_test():
    pass

我没有看到任何类型提示警告。

问题:缺少类型提示警告是因为...

  • 类型提示错误?
  • Python 类型提示限制?
  • PyCharm 类型提示限制?
  • 还有别的吗?

【问题讨论】:

  • 你用什么做类型分析? PyCharm 内置处理?到目前为止,mypy 在我的测试中似乎可以很好地处理装饰器。
  • 这是一个已知的issue

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


【解决方案1】:

这似乎是 PyCharm 中的一个错误(或“缺少功能”)。我试过这个程序:

import typing

ACallback = typing.Callable[[int], None]

def test2(callback: ACallback):
    def decorate(f):
        def new_f(*args, **kwargs):
            return f(*args, **kwargs)
        return new_f
    return decorate


def foo(s: str):
    pass


test2(foo)


@test2(foo)
def bar():
    pass

用最新版本的mypy,结果是

decorated.py:17: error: Argument 1 to "test2" has incompatible type "Callable[[str], Any]"; expected "Callable[[int], None]"
decorated.py:20: error: Argument 1 to "test2" has incompatible type "Callable[[str], Any]"; expected "Callable[[int], None]"

即两种使用都导致了错误。


如果你想将它与 PyCharm 一起使用,至少有 2 个用于 PyCharm 集成的不同插件;一个名为mypy,另一个名为Dropbox,即not available via JetBrains repository

我认为 DropBox 是“mypy 官方认可的插件”之一,因为 all the key mypy/Python type hinting people are employed by Dropbox...

【讨论】:

  • 感谢您的回答。只是为未来的读者评论插件:mypy 插件在最新的 PyCharm 版本 (183.4) 中被破坏了 Dropbox 插件实际上并没有增强视觉内置类型提示,只是提供了一种更轻松地运行 mypy 的方式跨度>
猜你喜欢
  • 2018-04-14
  • 2021-11-27
  • 2010-12-15
  • 1970-01-01
  • 2022-10-07
  • 1970-01-01
  • 1970-01-01
  • 2015-10-23
相关资源
最近更新 更多