[Python] Implement a minimal collections.abc sequence with type hints

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    How does a minimal implementation of a Sequence from collections.abc, together with the correct type hints, look like?

    My current version is the following (with warnings from basedpyright):

    from collections.abc import Sequence
    from typing import override

    class MySeq(Sequence[float]):
    def __init__(self):
    self._data: list[float] = list()

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

    @override
    def __getitem__(self, key) -> float: # Type annotation is missing for parameter "key"
    return self._data[key] # Return type is unknown

    • How do I type hint key? Just key: int is not accepted by the type checker. It gives the warning: "slice[Any, Any, Any]" is not assignable to "int". What choices do I have here?
    • What is wrong with the return type? The full warning is "float" is not assignable to "Sequence[float]"

    Continue reading...

Compartilhe esta Página