I am trying to extend pythons’ list with some custom methods, for that I
am creating an class inheriting from UserList.
I am not sure what is the right way and I would like to get mypy play
nicely with UserList.
I consulted cpython UserList docs and searched inside mypy for
UserList but couldn’t find anything.
Using:
- mypy 0.641
- python 3.7.0
This is a minimal example of what I am trying to achive
from collections import UserList
from typing import List, Optional, Union
class A:
...
class B:
...
class C:
...
TMessage = Union[A, B, C]
class MyList(UserList):
"""Minimal example"""
def __init__(self, data: Optional[List[TMessage]] = None) -> None:
self.data: List[TMessage] = []
if data:
self.data = data[:]
def get_last(self) -> TMessage:
return self.data[-1]
# other methods to be added ...
some_data = [A(), B(), C(), C(), B(), A()]
my_list_a = MyList(some_data)
my_list_b = MyList(some_data)
my_list_b = my_list_a[3:]
Mypy complains as follows
~/tmp ❯❯❯ mypy mypy_userlist.py
mypy_userlist.py:34: error: Argument 1 to "MyList" has incompatible type "List[object]"; expected "Optional[List[Union[A, B, C]]]"
mypy_userlist.py:35: error: Argument 1 to "MyList" has incompatible type "List[object]"; expected "Optional[List[Union[A, B, C]]]"
mypy_userlist.py:37: error: Incompatible types in assignment (expression has type "MutableSequence[Any]", variable has type "MyList")
I could add # type: ignore to the conflicting lines but I would like
to avoid that.
What is the right way to extend the python’s list with custom methods and get mypy happy?