mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Signature of "pop" incompatible with supertype "MutableSequence" for deque subclass

Open sveinugu opened this issue 1 year ago • 1 comments

Bug Report

Mypy incorrectly reports method signature override inconsistencies with MutableSequence for subclasses of deque, even though the subclass method signature is consistent with the method signature in the deque class. I experienced this for the pop() method, but I suspect this might be the case for other methods where the deque signature overrides the MutableSequence signature, if any.

To Reproduce

Mypy reports an error with the following minimal example:

from collections import deque
from typing import Any


class MyDeque(deque):
    def pop(self) -> Any:
        return super().pop()

Expected Behavior

No error reported for the above code

Actual Behavior

The error reported is as follows:

mypy_pop_error.py:6: error: Signature of "pop" incompatible with supertype "MutableSequence"  [override]
mypy_pop_error.py:6: note:      Superclass:
mypy_pop_error.py:6: note:          def pop(self, index: int = ...) -> Any
mypy_pop_error.py:6: note:      Subclass:
mypy_pop_error.py:6: note:          def pop(self) -> Any

This makes no sense to me as while MutableSequence does specify a variant of pop() with an index parameter (see https://docs.python.org/3/library/stdtypes.html#mutable-sequence-types), the index parameter is not supported by deque (see https://docs.python.org/3/library/collections.html#collections.deque). This is also confirmed by mypy if we e.g. change the method to:

class MyDeque(deque):
    def pop(self, index: int = -1) -> Any:
        return super().pop(index)

Then mypy correctly reports:

mypy_pop_error.py:7: error: Too many arguments for "pop" of "deque"  [call-arg]

This is consistent with runtime:

d = MyDeque([1, 2, 3])
d.pop()

Which results in:

(...)
  File "/PATH/TO/mypy_pop_error.py", line 7, in pop
    return super().pop(index)
TypeError: MyDeque.pop() takes no arguments (1 given)

Your Environment

  • Mypy version used: mypy 1.11.1 (compiled: yes)
  • Mypy command-line flags: --config-file=
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.10.8

sveinugu avatar Aug 06 '24 07:08 sveinugu

I get a similar error for __setitem__ and __delitem__, e.g.:

class MyDeque(deque):
    def __setitem__(self, __key: SupportsIndex, __value: _ObjT) -> None:
        return super().__setitem__(__key, __value)

    def __delitem__(self, __key: SupportsIndex) -> None:
        return super().__delitem__(__key)

sveinugu avatar Aug 24 '24 14:08 sveinugu