pythonpython-typingabcpython-collections

Sequence vs. MutableSequence


I've been using Sequence in type hints for sequences including mutable lists. Now I've just discovered that there is also MutableSequence. As far as I can tell, Sequence is a superclass of MutableSequence, i.e., Sequence includes both mutables like list and immutables like tuple, while MutableSequence only includes the former.

Two questions:


Solution

    1. Yes.

    2. No — in Python, you can only define interfaces (of which Sequence and MutableSequence are two examples) in terms of the presence of certain methods/behaviours; you cannot define an interface in terms of the absence of certain methods/behaviours.

    I would recommend reading the source code for collections.abc, which I personally find much more illuminating than the documentation.