For built-in Python types, list
is mutable but tuple
is not. For other sequences, is there a way to tell whether they are mutable or not? Like a mutable sequence usually has .pop()
, .insert()
, or .extend()
member function? Do all mutable sequences and immutable sequences inherit from separate built-in types, which then can be used to differentiate them?
You can check whether the type is a subclass of the collections.abc.MutableSequence
abstract base class (or collections.MutableSequence
in Python 2):
>>> issubclass(list, MutableSequence)
True
>>> issubclass(tuple, MutableSequence)
False
>>> isinstance([], MutableSequence)
True
>>> isinstance((), MutableSequence)
False
Note that unlike some ABCs (e.g., Collection
and Iterable
, which provide hooks for issubclass
/isinstance
) this one requires its subclasses to be explicitly registered, so this may not work out-of-the-box with all sequence-ish types.
However, you can manually register a type as a subclass using MutableSequence.register(MyType)
, as long as the required abstract methods are implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With