我有一个装饰器,它接受一个函数并返回具有一些附加属性的相同函数:
import functools
from typing import *
def decorator(func: Callable) -> Callable:
func.attr1 = "spam"
func.attr2 = "eggs"
return func
Run Code Online (Sandbox Code Playgroud)
如何键入提示的返回值decorator?我希望类型提示传达两条信息:
Callableattr1和attr2如果我写一个协议,
class CallableWithAttrs(Protocol):
attr1: str
attr2: str
Run Code Online (Sandbox Code Playgroud)
那我输了Callable。显然我不能让协议继承自Callable;
class CallableWithAttrs(Callable, Protocol):
attr1: str
attr2: str
Run Code Online (Sandbox Code Playgroud)
mypy 说:
error: Invalid base class "Callable"
Run Code Online (Sandbox Code Playgroud)
另一方面,如果我只使用Callable,我会丢失有关添加属性的信息。
这在引入类型变量时可能更加复杂,即当装饰器必须返回与给定函数相同类型的可调用对象时func,正如 MisterMiyagi 在评论中指出的那样。
import functools
from typing import *
C = TypeVar('C', bound=Callable)
def decorator(func: C) -> C:
func.attr1 = …Run Code Online (Sandbox Code Playgroud) 我希望 mypy 验证变量是否是某个基类的子类,并且它还具有特定的 mixin。Union 仅验证该值属于一种类型或另一种类型。我需要检查该值是否是两种类型。
在示例中,我编写了一个关键字“All”来演示我正在寻找的行为:
from typing import All
class Base ( object ):
pass
class Mixin ( object ):
pass
def assert_all ( x ):
# type: ( All[Base,Mixin] ) -> None
assert isinstance ( x, Base ) and isinstance ( x, Mixin )
class Child ( Mixin, Base ):
pass
assert_all ( Child() )
try:
assert_all ( Base() ) # !!! mypy should complain here
except AssertionError:
pass
else:
raise AssertionError ( 'assert inside of …Run Code Online (Sandbox Code Playgroud)