How to implement overload of `__setitem__` for `MutableSequence`?
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
I'm trying to implement my own MutableSequence but struggling with the proper way to implement the @overload
Here's my code example:
from typing import Iterable
from typing import List
from typing import MutableSequence
from typing import Union
from typing import overload
class RecordBehaviourList(MutableSequence[str]):
def __init__(self, lst: List[str]) -> None:
self._lst = lst
@overload
def __getitem__(self, index: int) -> str:
...
@overload # noqa: F811 # TODO: flake8 3.8
def __getitem__(self, index: slice) -> MutableSequence[str]:
...
def __getitem__( # noqa: F811 # TODO: flake8 3.8
self,
index: Union[int, slice],
) -> Union[str, MutableSequence[str]]:
return self._lst[index]
@overload
def __setitem__(self, index: int, value: str) -> None:
...
@overload # noqa: F811 # TODO: flake8 3.8
def __setitem__(self, index: slice, value: Iterable[str]) -> None:
...
def __setitem__( # noqa: F811 # TODO: flake8 3.8
self,
index: Union[int, slice],
value: Union[str, Iterable[str]],
) -> None:
self._lst[index] = value
def __delitem__(self, index: Union[int, slice]) -> None:
del self._lst[index]
def insert(self, index: int, value: str) -> None:
self._lst.insert(index, value)
I've taken the overload definitions from this example (?) but perhaps I'm doing this incorrectly?
For now I can # type: ignore but seems non-ideal
Here's my version information and current output
$ mypy --version
mypy 0.740
$ mypy t3.py
t3.py:39: error: Invalid index type "Union[int, slice]" for "List[str]"; expected type "int"
t3.py:39: error: Incompatible types in assignment (expression has type "Union[str, Iterable[str]]", target has type "str")
Found 2 errors in 1 file (checked 1 source file)
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne damit, das Beispiel in t3.py mit mypy 0.740 zu reproduzieren, und vergleiche die aus typeshed verlinkten Overload-Definitionen. Untersuche, warum die Implementierung von setitem für List[str] abgelehnt wird; abgeschlossen ist die Untersuchung, wenn die korrekte unterstützte Typisierung festgestellt oder ein Diagnoseproblem in mypy bestätigt wurde.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 25/100