标签: python-typing

为什么当 mypy 需要类型注释时,愚蠢的注释会处理错误?

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 annotations type-hinting mypy python-typing

4
推荐指数
1
解决办法
1万
查看次数

如何编写 typehint / 使用 typevar 作为过滤器方法?

我在 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)

python type-hinting python-typing

4
推荐指数
1
解决办法
3512
查看次数

Python 类型提示:何时使用 MutableSequence 与 List

我一直在阅读有关typing.Sequence和 的内容typing.MutableSequence。两者都没有大量的“轻松阅读”,一切都直接进入细节。

这个答案可以指定Python类型注释中的方差吗?

序列是列表的只读版本

MutableSequence所以这让我想知道,和 只是普通之间有什么区别List


更多细节

我能找到的最好的来源是Python 数据模型的标准类型层次结构部分。

从阅读该部分来看Mutable sequences,似乎可能MutableSequence是 ? 的“父母” List

换句话说,可以互换使用它们,只是MutableSequence限制少一点?

python list sequence type-hinting python-typing

4
推荐指数
1
解决办法
2684
查看次数

使用类型检查来检查字符串是否仅具有某些值

假设我有一个 python 函数def func_AB(param1: str)param1只能采用值AB。如果它采用任何其他字符串值,则会出现错误。

发生这种情况时是否可以使用 python 类型检查来给出错误?目前,我用来assert检查是否param1包含有效的字符串值。

我正在使用 python 3.8.5

python python-3.x python-typing

4
推荐指数
1
解决办法
947
查看次数

如何使用静态检查来确保对象具有特定的方法/属性?

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 …

python duck-typing type-hinting python-3.x python-typing

4
推荐指数
1
解决办法
723
查看次数

在 Python 中使用泛型动态类型化子类

假设我必须上课。

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。有没有办法指定泛型为某种类型?

python generics inheritance subclass python-typing

4
推荐指数
1
解决办法
1371
查看次数

如何在python中使用TypeVar进行多个通用协议的输入和输出?

我想使用多个通用协议并确保它们兼容:

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)

python python-typing

4
推荐指数
1
解决办法
5505
查看次数

将内置字典类型转换为 TypedDict

我有这样的东西(非常简单):

# 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 …

python type-hinting mypy python-typing

4
推荐指数
1
解决办法
4533
查看次数

迭代 TypedDict 的键

这是一个例子:

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

python type-hinting mypy python-typing typeddict

4
推荐指数
1
解决办法
2367
查看次数

字段类型取决于其他字段的类型

是否可以创建一个类似的类

from typing import Union, Literal

class Foo:
    bar: Union[str, int]
    qux: Literal["str", "int"]
Run Code Online (Sandbox Code Playgroud)

这样,如果quxLiteral["str"],则bar属于类型str,如果quxLiteral["int"],则bar属于类型int?可以注释一下吗?

我知道typing.overload,但我认为这与此示例无关

python type-hinting mypy python-typing

4
推荐指数
1
解决办法
550
查看次数