Mypy 在这一行出错:
response = {'available_fields': []}
error: Need type annotation for 'response'
Run Code Online (Sandbox Code Playgroud)
当我添加响应是字典的愚蠢注释时,错误消失了:
response: typing.Dict = {'available_fields': []}
Run Code Online (Sandbox Code Playgroud)
所以,我对此有一些疑问。为什么愚蠢的注释会处理错误?如何调整 mypy(配置、选项等)而不担心没有注释的这一行?
我在 Python 中有一个辅助方法,它返回方法列表以及每个方法的带注释的数据。所以它是一个列表字典。带注释的数据由类来表示Attribute。
定义如下:
# A filter predicate can be either an attribute object or a tuple/list of attribute objects.
AttributeFilter = Union['Attribute', Iterable['Attribute'], None]
# A class offering a helper method
class Mixin:
def GetMethods(self, filter: AttributeFilter=Attribute) -> Dict[Callable, List[Attribute]]:
pass
Run Code Online (Sandbox Code Playgroud)
此语法和相应的类型检查工作正常。
因为我想改进它。
用户通常从类派生用户定义的属性Attribute。我想表达的是,如果用户传递像UserAttributeto 这样的派生类GetMethods,那就返回 s 列表的字典UserAttribute。
# Some user-defined attribute and some public data in it
class UserAttribute(Attribute):
someData: str
# Create a big class
class Big(mixin):
# …Run Code Online (Sandbox Code Playgroud) 我一直在阅读有关typing.Sequence和 的内容typing.MutableSequence。两者都没有大量的“轻松阅读”,一切都直接进入细节。
序列是列表的只读版本
MutableSequence所以这让我想知道,和 只是普通之间有什么区别List?
更多细节
我能找到的最好的来源是Python 数据模型的标准类型层次结构部分。
从阅读该部分来看Mutable sequences,似乎可能MutableSequence是 ? 的“父母” List?
换句话说,可以互换使用它们,只是MutableSequence限制少一点?
假设我有一个 python 函数def func_AB(param1: str)。param1只能采用值A或B。如果它采用任何其他字符串值,则会出现错误。
发生这种情况时是否可以使用 python 类型检查来给出错误?目前,我用来assert检查是否param1包含有效的字符串值。
我正在使用 python 3.8.5
Is there I way that I can annotate a function to ensure that an object being passed into the function has a certain method or attribute, but where I don't care about its actual type?
Pycharm internally uses a syntax that looks like {b} to indicate what methods/attributes it's inferred are required for the object, but that doesn't appear to be valid Python syntax:
def func(a: {b}): # Error
a.b = 1
Run Code Online (Sandbox Code Playgroud)
Is there a way to get the type …
假设我必须上课。
class A:
@staticmethod
def foo():
pass
class B(A):
pass
Run Code Online (Sandbox Code Playgroud)
我有某种函数可以根据对象的类型构造对象并调用函数。
def create(cls: Type[A]) -> A:
cls.foo()
return cls()
Run Code Online (Sandbox Code Playgroud)
现在我可以对该函数进行以下调用。因为B继承了A一切都很好。
instance_a: A = create(A)
instance_b: B = create(B)
Run Code Online (Sandbox Code Playgroud)
除了后者之外,类型检查将开始抱怨,因为create根据注释返回 的实例A。
TypeVar这可以通过如下方式解决。
from typing import Type, TypeVar
T = TypeVar('T')
def create(cls: Type[T]) -> T:
cls.foo()
return cls()
Run Code Online (Sandbox Code Playgroud)
但现在类型检查并没有完成它最初的工作,即保证cls有一个名为 的方法foo。有没有办法指定泛型为某种类型?
我想使用多个通用协议并确保它们兼容:
from typing import TypeVar, Protocol, Generic
from dataclasses import dataclass
# checking fails as below and with contravariant=True or covariant=True:
A = TypeVar("A")
class C(Protocol[A]):
def f(self, a: A) -> None: pass
class D(Protocol[A]):
def g(self) -> A: pass
# Just demonstrates my use case; doesn't have errors:
@dataclass
class CompatibleThings(Generic[A]):
c: C[A]
d: D[A]
Run Code Online (Sandbox Code Playgroud)
Mypy 出现以下错误:
Invariant type variable 'A' used in protocol where contravariant one is expected
Invariant type variable 'A' used in protocol where covariant one …Run Code Online (Sandbox Code Playgroud) 我有这样的东西(非常简单):
# mymodule.py
from typing import TypedDict, cast
D=TypedDict('D', {'x':int, 'y':int})
d = {}
d['x']=1
d['y']=2
d = cast(D, d)
Run Code Online (Sandbox Code Playgroud)
但 mypy 抱怨道:
mymodule.py:9: error: Incompatible types in assignment (expression has type "D", variable has type "Dict[str, int]") Found 1 error in 1 file (checked 1 source file)
将普通字典转换为子类型不应该是有效的吗TypedDict?如果不是,“构建”字典然后声明其类型的正确方法是什么?
请注意,这是非常简单的;实际上,字典是根据比上面给出的更复杂的算法构建的。
更新:即使我更改变量名称而不是尝试转换类型,问题似乎仍然存在。
# mymodule.py
from typing import TypedDict, cast
D=TypedDict('D', {'x':int, 'y':int})
d = {}
d['x']=1
d['y']=2
dd: D = d
Run Code Online (Sandbox Code Playgroud)
error: Incompatible types in assignment (expression has type …
这是一个例子:
from typing import TypedDict
class Foo(TypedDict):
a: str
b: int
foo = Foo(a='2', b=4)
for key in foo:
print(foo[key])
Run Code Online (Sandbox Code Playgroud)
我明白了
main.py:10: note: Revealed type is 'Any'
main.py:10: error: TypedDict key must be a string literal; expected one of ('a', 'b')
Found 1 error in 1 file (checked 1 source file)
Run Code Online (Sandbox Code Playgroud)
我觉得这很令人惊讶 - 难道不知道这key是 的键之一foo,因此它foo[key]应该是有效的吗?
游乐场网址:https://mypy-play.net/? mypy=latest&python=3.9&gist=8972284897f25314f9c790eab4cb8548
是否可以创建一个类似的类
from typing import Union, Literal
class Foo:
bar: Union[str, int]
qux: Literal["str", "int"]
Run Code Online (Sandbox Code Playgroud)
这样,如果qux是Literal["str"],则bar属于类型str,如果qux是Literal["int"],则bar属于类型int?可以注释一下吗?
我知道typing.overload,但我认为这与此示例无关
python ×10
python-typing ×10
type-hinting ×7
mypy ×4
python-3.x ×2
annotations ×1
duck-typing ×1
generics ×1
inheritance ×1
list ×1
sequence ×1
subclass ×1
typeddict ×1