如何在继承内置集合类型时避免mypy的投诉?

huangapple go评论71阅读模式
英文:

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]):
    ...

huangapple
  • 本文由 发表于 2023年4月13日 23:30:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76007269.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定