How to satisfy Typing.Sequence using Structural typing #8287
-
I was reading the docs when I tried to implement the methods mentioned to remove Pylance errors in vscode. I don't want to inherit from # testing Sequence class
from typing import Collection, Container, Iterable, Reversible, Sequence, Sized
class ImplementsSequence:
def __getitem__(self, index: int) -> int:
return 0
def __len__(self) -> int:
return 0
def __contains__(self, item) -> bool:
return False
def __iter__(self):
return (1, 2, 3).__iter__()
def __reversed__(self):
return reversed([1, 2, 3])
def index(self, item):
return 0
def count(self, item):
return 0
Sequence.register(ImplementsSequence) # doesn't change anything with Pylance unfortunately
def accept_Sized(obj: Sized) -> None:
print(len(obj))
def accept_iterable(obj: Iterable[int]) -> None:
for x in obj:
print(x)
def accept_Contains(obj: Container[int]) -> None:
print(1 in obj)
print(4 in obj)
def accepts_Reversible(obj: Reversible[int]) -> None:
for x in reversed(obj):
print(x)
def accepts_Collection(obj: Collection[int]) -> None:
for x in obj:
print(x)
def accepts_sequence(obj: Sequence) -> None:
for x in obj:
print(x)
print(obj[2])
accept_Sized(ImplementsSequence()) # OK
accept_iterable(ImplementsSequence()) # OK
accept_Contains(ImplementsSequence()) # OK
accepts_Reversible(ImplementsSequence()) # OK
accepts_Collection(ImplementsSequence()) # OK
accepts_sequence(ImplementsSequence()) # Error???? The problem is that also unlike other abstract class the error message doesn't tell what method(s) are wrong/missing from the interface.
Is this behavior correct? If so what am I doing incorrectly? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
Pyright is a standards-compliant type checker for Python, which means it follows the rules spelled out in the Python type specification.
In the Python type system, structural types are referred to as “protocols”. You can read about them in the Python type specification here and here. Examples of protocols includes |
Beta Was this translation helpful? Give feedback.
Pyright is a standards-compliant type checker for Python, which means it follows the rules spelled out in the Python type specification.
Sequence
is a nominal type, not a structural type. In the Python type system, type compatibility rules for nominal types is based on static class hierarchies. ClassB
is a subtype of classA
only ifB
derives fromA
. Dynamic registration of ABCs is not (and never will be) supported in the static type system.In the Python type system, structural types are referred to as “protocols”. You can read about them in the Python type specification here and here. Examples of protocols includes
Sized
,Iterable
,Container
, andReversible
. You could create a protocol…