The future of Python immutability

Adam Skutt askutt at gmail.com
Fri Sep 4 09:36:59 EDT 2009


On Sep 3, 2:03 pm, John Nagle <na... at animats.com> wrote:
>      Suppose, for discussion purposes, we had general "immutable objects".
> Objects inherited from "immutableobject" instead of "object" would be
> unchangeable once "__init__" had returned.  Where does this take us?

You can create this in various ways through metaclasses.  I've done
it, mostly because I was curious to see how hard it would be and if it
actually gained me anything useful.

>      With this mechanism, multi-thread programs with shared data
> structures can be written with little or no explicit locking by
> the programmer.  If the restrictions are made a bit stricter,
> strict enough that threads cannot share mutable unsynchronized data,
> removal of the "global interpreter lock" is potentially possible.
> This is a route to improved performance on modern multi-core CPUs.
Nope, preventing mutation of the objects themselves is not enough.
You also have to forbid variables from being rebound (pointed at
another object).  Consider this simple example:

---------- Thread 1 ---------- | ---------- Thread 2 ----------
a = "Foo"
spawn Thread 2
a = "Bar"                        print "thread 2: %s" % a
print "thread 1: %s" % a

You could see (ignoring the fact the output isn't ordered):
"thread 1: Bar"
"thread 2: Foo"
or:
"thread 1: Bar"
"thread 2: Bar"

so the fact "Foo" and "Bar" are immutable isn't enough to solve the
problem.  The variables themselves, since they obey pointer semantics,
must also be forbidden from being reseated (i.e., they must be
references in the C++ sense or become 'T const * const' pointers).

Thanks,
Adam



More information about the Python-list mailing list