【问题标题】:Decorated function return type remains original when called directly装饰函数返回类型在直接调用时保持原始
【发布时间】:2022-01-24 10:46:45
【问题描述】:

定义一个接受Callable[..., int]并返回Callable[..., str]的装饰器似乎无法被mypy理解

def decorator(wrapped: Callable[..., int]) -> Callable[..., str]:
    def wrapper() -> str:
        return str(wrapped())

    return wrapper


@decorator
def foo() -> int:
    return 0


def bar():
    x = foo()  # mypy sees x as int even though the decorator(foo)() returns str

有什么办法可以让foo()的返回类型不是它原来的返回类型,而是装饰器指定的返回类型?

编辑:简化示例

【问题讨论】:

  • 您使用哪个版本的 mypy? mypy 0.790 显示没有问题
  • 我正在使用mypy 0.910

标签: python decorator mypy python-typing


【解决方案1】:

这是我在最新版本的 mypy (0.930) 中看到的:str not int

def decorator(wrapped: Callable[..., int]) -> Callable[..., str]:

    def wrapper() -> str:
        return str(wrapped())

    return wrapper


@decorator
def foo() -> int:
    return 0


def bar() -> None:
    x = foo()
    reveal_type(x)  # Mypy: Revealed type is "builtins.str"

【讨论】:

  • 也一样。您如何检查您的 mypy 是否将其视为 int?
  • 我在 PyCharm 中使用了一个 mypy 插件,到目前为止,我认为它会显示类型不匹配,就像运行 mypy 会抛出它们一样。在我的情况下,即使在文件上运行 mypy 成功,IDE 也会抱怨。如果我更改类型以使 IDE 满意,那么 mypy 会抱怨,这似乎是插件或我的本地设置的问题
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 2015-08-31
  • 2016-10-20
  • 1970-01-01
相关资源
最近更新 更多