在尝试更新我的代码以符合 PEP-484(我使用的是mypy0.610)时,我遇到了以下报告:
$ mypy mymodule --strict-optional --ignore-missing-imports --disallow-untyped-calls --python-version 3.6
myfile.py:154: error: Signature of "deliver" incompatible with supertype "MyClass"
我的课:
from abc import abstractmethod
from typing import Any
class MyClass(object):
@abstractmethod
def deliver(self, *args: Any, **kwargs: Any) -> bool:
raise NotImplementedError
Run Code Online (Sandbox Code Playgroud)
我的文件.py:
class MyImplementation(MyClass):
[...]
def deliver(self, source_path: str,
dest_branches: list,
commit_msg: str = None,
exclude_files: list = None) -> bool:
[...]
return True
Run Code Online (Sandbox Code Playgroud)
我肯定在这里做错了什么,但我不太明白是什么:)
任何指针将不胜感激。
memo: dict[int, int] = {0: 0, 1: 1} # *our base cases*
Run Code Online (Sandbox Code Playgroud)
返回以下错误:
memo: dict[int, int] = {0: 0, 1: 1} # *our base cases*
Run Code Online (Sandbox Code Playgroud) 当用于os.getenv检索环境变量时,默认行为返回Optional[str]. 这是有问题的,因为使用这些变量的任何下游方法/函数都可能被定义为str显式接受类型。是否有可接受的用法来解决此问题或强制执行str返回类型?
getenv在in typeshed的存根文件定义中,您可以发现它的getenv返回类型可以为Optional[str]或 ,Union[str, T_]具体取决于 kwarg 的使用default。
目前我能看到的四个选项是:
Optional[str]类型作为参数。这感觉不太正确,因为函数/方法的结构可能不符合类型的Optional意义。即该操作没有理由将特定参数设为None。defaultkwarg forgetenv并提供str默认值。这似乎更正确,但要求为每次使用设置一个默认值getenv。我能看到的唯一问题是这样做可能会混淆不同环境中的测试或使用。getenvstr。我真的不喜欢这个,因为它期望环境始终被正确配置,根据我的经验,这不是一个好的假设。下面是一个引发 mypy 错误的示例。
import os
SOME_VAR = os.getenv("SOME_VAR")
def some_func(val: str) -> None:
print(f"Loaded env var: {val}")
some_func(SOME_VAR)
Run Code Online (Sandbox Code Playgroud)
上面引发了 mypy 错误:
错误:“some_func”的参数 1 具有不兼容的类型“Optional[str]”;预期“str”
我有一个通用类Graph[Generic[T], object]。
我的问题是,是否有任何函数返回作为泛型传递给类的类型Graph
>>> g = Graph[int]()
>>> magic_func(g)
<class 'int'>
Run Code Online (Sandbox Code Playgroud) Python 3.9包括PEP 585并弃用了模块中的许多类型,typing转而支持 中的类型collections.abc,现在它们支持__class_getitem__. 例如,就是这种情况Callable。对我来说,似乎typing.Callable和collections.abc.Callable应该总是表现得相似,但事实并非如此。
这个简单的示例会导致错误:
>>> from typing import Optional
>>> from collections.abc import Callable
>>> def foo(arg: Optional[Callable[[int], int]]) -> None:
... pass
...
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "/usr/local/lib/python3.9/typing.py", line 262, in inner
return func(*args, **kwds)
File "/usr/local/lib/python3.9/typing.py", line 339, in __getitem__
return self._getitem(self, parameters)
File "/usr/local/lib/python3.9/typing.py", line 463, in Optional
return Union[arg, type(None)]
File …Run Code Online (Sandbox Code Playgroud) python python-3.x python-collections python-typing python-3.9
由于我在 Python 中经常使用类型提示,因此我遇到了递归函数接受dict,str作为键和int或dict作为值 ( Dict[str, Union[int, Dict[...]]) 的场景。此时的问题是可能的dict-value 也有str作为键和int或dict作为值 ( Dict[str, Union[int, Dict[Dict[str, Union[int, Dict[...]]]])。
但是,我不知道传递的字典有什么深度。是否有可能通过类型提示来可视化这种重复模式?
我有以下功能:
import pandas as pd
def eq(left: pd.Timestamp, right: pd.Timestamp) -> bool:
return left == right
Run Code Online (Sandbox Code Playgroud)
当我通过 Mypy 运行它时,出现以下错误:
错误:从声明为返回“bool”的函数返回任何内容
我相信这是因为 Mypy 不知道pd.Timestamp所以将其视为Any. (使用 Mypyreveal_type函数表明 Mypy 将left和right视为Any。)
处理这个问题以阻止 Mypy 抱怨的正确方法是什么?
考虑以下代码示例
def sum(a: int, b: int):
return a + b
def wrap(*args, **kwargs):
# delegate to sum
return sum(*args, **kwargs)
Run Code Online (Sandbox Code Playgroud)
除了类型提示丢失之外,代码运行良好。*args, **kwargs在 Python 中用来实现委托模式是很常见的。如果有一种方法可以在使用它们时保留类型提示,那就太好了,但我不知道是否可能以及如何实现。
对象 A、B ... 具有属性namespace,并且我有一个函数可以通过一组特定的属性值过滤此类对象的列表namespace:
T = TypeVar('T')
def filter(seq: list[T], namespace_values: set[str]) -> list[T]:
# Returns a smaller list containing only the items from
# `seq` whose `namespace` are in `namespace_values`
...
Run Code Online (Sandbox Code Playgroud)
X这很有效,但它允许传递不具有该属性的类型的对象,namespace而不会出现任何检查错误。
然后我创建了一个协议并更改了函数以便使用该协议:
class Namespaced(Protocol):
namespace: str
def filter(seq: list[Namespaced], namespace_values: set[str]) -> list[Namespaced]:
# Returns a smaller list containing only the items from
# `seq` whose `namespace` are in `namespace_values`
...
Run Code Online (Sandbox Code Playgroud)
现在,如果我传递一个列表X(这就是我想要的),我会收到一个检查错误,但我丢失了泛型:
list_of_a: list[A] = [a1, a2, a3]
output …Run Code Online (Sandbox Code Playgroud) 正如问题所描述的,我想输入提示selfreturn ,例如:
class A:
def foo(self) -> [what goes here?]:
# do something
return self
Run Code Online (Sandbox Code Playgroud)
我已经尝试过的事情:
A(from __future__ import annotations在顶部添加):这意味着该方法返回一个实例化A()对象,但不一定self。Type[A](adding from typing import Type):这意味着该方法返回的是返回一个未实例化的A,它与 相差甚远self。Self(添加from typing_extensions import Self):mypy 给出错误:
Variable "typing_extensions.Self" is not valid as a type [valid-type]mypy(error)可能有帮助的事情foo:将鼠标悬停在没有返回值注释的方法上,VScode提示显示 - Self@A,我不明白,但是,这绝对区分返回另一个实例化类A()和返回self...谢谢
python ×10
python-typing ×10
python-3.x ×4
mypy ×3
generics ×2
type-hinting ×2
protocols ×1
python-3.9 ×1