1

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:

  • Is this correct? (I'm pretty sure it is, but I haven't found any explicit statement to this end.)
  • If so, is there an immutable equivalent to MutableSequence that includes, e.g., tuple and str, but not list?
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
flotzilla
  • 1,181
  • 1
  • 13
  • 23

1 Answers1

3
  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.

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46