列表子类的 Python 类型

Int*_*per 10 python list subclass python-3.x python-typing

我希望能够定义列表子类的内容。该类将如下所示。

class A(list):
   def __init__(self):
      list.__init__(self)
Run Code Online (Sandbox Code Playgroud)

我想包括打字,以便发生以下情况。

import typing

class A(list: typing.List[str]):  # Maybe something like this
   def __init__(self):
      list.__init__(self)

>> a = A()
>> a.append("a")  # No typing error
>> a.append(1)  # Typing error
Run Code Online (Sandbox Code Playgroud)

jua*_*aga 6

typing方便地提供了 的通用版本collections.MutableSequence,因此具有以下效果:

import typing

T = typing.TypeVar('T')
class HomogeneousList(typing.MutableSequence[T]):
    def __init__(self, iterable: typing.Iterable[T]=()) -> None:
        self._data: typing.List[T]  = []
        self._data.extend(iterable)

    @typing.overload
    def __getitem__(self, index: int) -> T: ...
    @typing.overload
    def __getitem__(self, index: slice) -> HomogeneousList[T]: ...
    def __getitem__(self, index):
        return self._data[index]

    @typing.overload
    def __setitem__(self, index: int,  item: T) -> None: ...
    @typing.overload
    def __setitem__(self, index: slice, item: typing.Iterable[T]) -> None: ...
    def __setitem__(self, index, item):
        self._data[index] = item

    def __delitem__(self, index: typing.Union[int, slice]) -> None:
        del self._data[index]

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

    def insert(self, index: int, item: T) -> None:
        self._data.insert(index, item)


string_list = HomogeneousList[str]()
string_list.append('foo')
string_list.append(42)


int_list = HomogeneousList[int]()
int_list.append(42)
int_list.append('foo')
Run Code Online (Sandbox Code Playgroud)

现在,mypy给出以下错误:

test.py:36: error: Argument 1 to "append" of "MutableSequence" has incompatible type "int"; expected "str"
test.py:41: error: Argument 1 to "append" of "MutableSequence" has incompatible type "str"; expected "int"
Run Code Online (Sandbox Code Playgroud)

打字__getitem__等有一些棘手的方面,因为它们也接受slice对象,但并不可怕。

请注意,这很有用,因为如果您只是尝试执行以下操作:

class HomogeneousList(collections.abc.MutableSequence, typing.Generic[T]):
    ....
Run Code Online (Sandbox Code Playgroud)

至少,MyPy 不会为追加引发错误。AFAIKT 你必须明确添加:'

def append(self, item: T) -> None:
    self._data.append(item)
Run Code Online (Sandbox Code Playgroud)

哪一种删除了很多实用程序collections.abc.MutableSequence。无论如何,幸运的是,打字提供了所有这些开箱即用的通用版本!

请注意,您可以像我展示的那样一般地使用这些,但您也可以执行以下操作:

class StringList(HomogeneousList[str]):
    pass

mylist = StringList([1,2,3]) # mypy error
mylist = StringList('abc') # no error

mylist.append('foo') # no error
mylist.append(42) # mypy error
Run Code Online (Sandbox Code Playgroud)