如何为类型定义Python协议,即:
Callablewith返回指定类型值的任何类型的的关键字参数数。
这是我的尝试:
from typing import Any, Protocol, TypeVar
T = TypeVar("T", covariant=True)
class Operation(Protocol[T]):
def __call__(self, **kwargs: Any) -> T:
pass
# some example functions that should be a structural sub-type
我的代码如下所示,它运行良好的BDW,没有任何错误。
from typing import Literal
def verify(word: str) -> Literal['Hello XY']:
a = 'Hello ' + word
return a
a = verify('XY')
虽然,当我试图使用mypy进行类型检查时,它会抛出一个错误error: Incompatible return value type (got "str", expected "Literal['Hel
我在Python /Rest- 3.8+环境中工作,在新代码中强制使用类型,但是构建在大量非类型化的遗留代码和数据之上。我们广泛使用TypedDicts,以确保我们生成的数据能够以正确的数据类型传递到TypeScript前端。 MyPy/PyCharm/等在检查我们的新代码是否输出符合的数据方面做得很好,但我们想要测试许多RestSerializer/ModelSerializers的输出是否符合TypeDict。如果我有一个序列化程序和类型的dict,比如: class PersonSerializer(ModelSerializer):
class Meta:
m
我有一个如下所示的类: from typing import Optional
import numpy as np
class TestClass():
def __init__(self, a: Optional[float] = None):
self.a = np.radians(a) 这将返回错误Argument 1 to "__call__" of "ufunc" has incompatible type "Optional[float]"; expected "Union[Union[int,
你能发现下面代码中的错误吗?梅蒂不能。
from typing import Dict, Any
def add_items(d: Dict[str, Any]) -> None:
d['foo'] = 5
d: Dict[str, str] = {}
add_items(d)
for key, value in d.items():
print(f"{repr(key)}: {repr(value.lower())}")
当然,Python发现了错误,这对通知我们'int' object has no attribu
我在Python中有以下的理解:
from typing import cast
# everything is fine
print([value for value in [1, 2, 3, 4]])
# on the first "value": Expression type contains "Any" (has type "List[Any]")
print("{}".format([value for value in [1, 2, 3, 4]]))
# on the "cast": Expre