Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a sequence is mutable or not?

Tags:

python

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?

like image 874
Thomson Avatar asked Apr 24 '17 07:04

Thomson


1 Answers

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.

like image 171
Will Vousden Avatar answered Sep 21 '22 17:09

Will Vousden