gpt4 book ai didi

python - 为什么 mypy 提示 Any 作为返回注释,我应该如何注释可以是任何内容的返回值?

转载 作者:行者123 更新时间:2023-11-28 18:09:43 24 4
gpt4 key购买 nike

我有一个本质上是字典包装器的类:

class Wrapper(dict):

...

def __getitem__(self, item: Hashable) -> Any:
return self.wrapped[item]

当使用 mypy 检查注释时,它会在检查此代码时产生 Explicit "Any"is not allowed。我的猜测是,这源于 Any 是所有其他类型的祖先和继承者的概念。我应该如何在允许返回任何内容的地方注释此类函数?

最佳答案

我们需要告诉 mypy self.wrapped 容器的类型与 Wrapper 方法的类型相关,我们可以使用typing.TypeVar instances在我们的案例中用于键和值。

所以我们可以得到类似的东西

from collections import abc
from typing import (Dict,
Iterator,
TypeVar)


class Wrapper(abc.MutableMapping):
KeyType = TypeVar('KeyType')
ValueType = TypeVar('ValueType')

def __init__(self, wrapped: Dict[KeyType, ValueType]) -> None:
self.wrapped = wrapped

def __delitem__(self, key: KeyType) -> None:
del self.wrapped[key]

def __len__(self) -> int:
return len(self.wrapped)

def __iter__(self) -> Iterator[KeyType]:
return iter(self.wrapped)

def __setitem__(self, key: KeyType, value: ValueType) -> None:
self.wrapped[key] = value

def __getitem__(self, key: KeyType) -> ValueType:
return self.wrapped[key]

测试

使用 --disallow-any-explicit 标志运行 mypy 不会导致错误/警告。

关于继承/组合的注意事项

如果确实需要自定义映射,我建议不要将 dict 的继承与使用 self.wrapped dict-field 混合为它可能会在未来造成很多痛苦(我们应该重新定义它的所有方法,或者有时您将使用 self.wrapped 有时不会)。

我们可以简单地使用来自 collections.abc moduleMutableMapping ABC并定义基本方法(如 __getitem__),其余的(keys()valuesitems() 是已定义)。

关于python - 为什么 mypy 提示 Any 作为返回注释,我应该如何注释可以是任何内容的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51458555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com