typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

Validity of `collections.deque` as `typing.Sequence`

Open einarwar opened this issue 1 year ago • 2 comments

Hi

Based on this discussion on pyright: https://github.com/microsoft/pyright/discussions/7989#discussioncomment-9548709

A collections.deque is a valid typing.Sequence. However, typing.Sequence allows being sliceable, while a collections.deque does not support slicing. This makes room to make errors that is not caught by static type checkers like pyright and mypy.

It seems like this normally would be reported, but the errors are suppressed by type-ignore comments found here.

Is there any other way of handling this so that trying to slice a deque would result in a type-error?

einarwar avatar May 27 '24 12:05 einarwar

Considering that deque doesn't derive from (Mutable)Sequence at runtime, we should at least try to remove that base class. This might be too disruptive, but an exploratory PR would be welcome.

srittau avatar May 27 '24 12:05 srittau

See https://github.com/python/cpython/issues/113313 for some previous discussion on this. Considering that isinstance(deque(), MutableSequence) evaluates to True at runtime, and that this is the only respect in which deque is not a true Sequence, I think we've probably currently got the best compromise available. But exploratory PRs to gauge the possible impact of a change are of course always welcome :-)

AlexWaygood avatar May 27 '24 12:05 AlexWaygood