英文:
How to avoid mypy complaints when inheriting from a built-in collection type?
问题
运行mypy
在这样的代码上:
class MySpecialList(list):
# funky extra functionality
会给我带来以下错误:
我可以通过根本不继承list
或忽略此错误来避免它。
但是,我应该如何处理这个问题呢?这不是mypy的bug吗?
英文:
Running mypy
on code like this
class MySpecialList(list):
# funky extra functionality
gives me
my_file.py:42: error: Missing type parameters for generic type "list" [type-arg]
I can avoid this by not inheriting from list
at all or ignoring this error.
But how should I deal with this? Isn't this a bug in mypy?
答案1
得分: 1
这是使用 --disallow-any-generics
(这是 --strict
隐含的)的结果,因为 list
等同于 list[Any]
。您可以通过使用类型变量显式使 MySpecialist
成为泛型来修复它。
from typing import TypeVar
T = TypeVar('T')
class MySpecialList(list[T]):
...
英文:
This is the result of using --disallow-any-generics
(which is implied by --strict
), as list
is equivalent to list[Any]
. You can fix it by making MySpecialist
explicitly generic via a type variable.
from typing import TypeVar
T = TypeVar('T')
class MySpecialList(list[T]):
...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论