Python输入列表的子类

时间:2019-02-27 20:30:26

标签: python python-3.x list subclass python-typing

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

private Predicate[] criarRestricoes(FilterDTO filter, CriteriaBuilder builder, Root<Director> root) {

        List<Predicate> predicates = new ArrayList<>();
        Date today = new Date();

        if (filter.getRegistrationDate() != null) {

            predicates.add(builder.between(root.get("registrationDate").as(Date.class), today, filter.dateParam));

        } 

       if (!StringUtils.isEmpty(filter.getCnpj())) {

            predicates.add(builder.equal(???????????, ???????????????);

        } 

        return predicates.toArray(new Predicate[predicates.size()]);
    }

我想包括键入内容,以便进行以下操作。

class A(list):
   def __init__(self):
      list.__init__(self)

2 个答案:

答案 0 :(得分:3)

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')

现在,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"

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

请注意,这很有用,因为如果您尝试这样做:

class HomogeneousList(collections.abc.MutableSequence, typing.Generic[T]):
    ....

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

def append(self, item: T) -> None:
    self._data.append(item)

首先删除了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

答案 1 :(得分:2)

在 Python 3.9 之前,您可以使用:

import typing

class A(typing.List[str]):
    pass

这向您的类型检查器表明 A 类的元素应该是 str 类型。在运行时,这与创建 list 的子类的行为相同。 PEP 484 指定打字系统的行为方式。特别是,this section of the PEP 中的示例执行的操作与您要求的类似,但使用 typing.Dict 而不是 typing.List

在 Python 3.9+ 中,您可以use the built-in type instead of importing from typing。类变为:

class A(list[str]):
    pass