【发布时间】:2021-01-12 18:09:09
【问题描述】:
对于以下文件:
from abc import ABC, abstractmethod
from typing import Any, Awaitable, Callable, TypeVar, cast
T = TypeVar('T')
def dec(args: Any) -> Callable[..., Awaitable[T]]:
def dec2(f: Callable[..., Awaitable[T]]) -> Awaitable[T]:
async def wrapper(*args:Any, **kwargs:Any) -> T:
print(args)
return cast(T, await f(*args, **kwargs))
return cast(Awaitable[T], wrapper)
return dec2
class A(ABC):
@abstractmethod
async def fn(self) -> 'bool':
pass
class B(A):
@dec('hi')
async def fn(self) -> 'bool':
return True
class C(A):
@dec('hi')
async def fn(self) -> 'bool':
return False
我收到以下 mypy 错误:
$ mypy typetest.py
typetest.py:24: error: Signature of "fn" incompatible with supertype "A"
typetest.py:30: error: Signature of "fn" incompatible with supertype "A"
Found 2 errors in 1 file (checked 1 source file)
键入需要如何工作才能保留类签名并且不会收到 mypy 错误。
这是在 python3.7 上,mypy 0.790
【问题讨论】:
-
尝试使用
-> bool而不是-> 'bool'。返回类型不应需要引号,这可能会干扰签名。 -
报价有效。唯一的区别是在运行时不会进行名称查找。使用
from __future__ import annotations会导致 all 注释被隐式视为字符串文字(我相信这将是 Python 3.10 中的默认设置)。
标签: python python-3.x mypy