[Python-ideas] Wild idea about mutability

Rob Cliffe rob.cliffe at btinternet.com
Wed Jun 1 18:26:07 EDT 2016


I was prompted to post this after seeing comments on "Proposal to change 
List Sequence Repetition (*) so it is not useless for Mutable Objects" 
that you cannot in general tell whether an object is mutable or not.

Well, why shouldn't you be able to tell?  Python is superb at 
introspection, but ISTM there's a gap here.  Here's an idea for Python N 
(N>=4):  Every object has a boolean __mutable__ attribute.  It would 
e.g. be False for ints and strings,  True by default for objects that 
can be mutable, such as lists and dicts. It could be an optional extra 
argument to mutable object constructors (so you have the option of 
making them immutable):

     L = list(somesequence, mutable=False)

There could also be a syntax for list/set literals and dictionary 
displays to indicate that they should be immutable (just as we preface 
literal strings with 'r' to indicate raw strings).  I'm not sure what; I 
thought of f[1,2,3] for a literal immutable ("frozen") list, but that's 
already valid syntax.

You can "freeze" a mutable object by changing its __mutable__ attribute 
from True to False.  You are not allowed to change it from False to 
True, nor to mutate an object that has it False.

I am sure there must be advantages in being able to tell if an object is 
mutable or not.  (Perhaps "hashable" equals "not mutable" ?)

Now:  You don't need the frozenset class.  You just have a set with 
__mutable__ = False.  And you can freeze dicts (classes? modules?) etc., 
to make sure users of your code don't mess with them.

And (fasten your safety belts): You don't need tuples.  You just have a 
list with __mutable__ = False.  And you don't have to explain to 
beginners one of the most FAQ "Why do we need lists and tuples?"

Best wishes (and sorry I can't seem to get my e-mail out of double 
vertical spacing mode),

Rob Cliffe




More information about the Python-ideas mailing list