The future of Python immutability

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Sep 5 00:06:18 EDT 2009


On Fri, 04 Sep 2009 06:36:59 -0700, Adam Skutt wrote:

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

This is a side-effect of writing code that relies on global variables. 
Global variables are generally a bad idea. Global constants are fine.



> The variables themselves, since they obey pointer semantics,

What do you mean by "variables"? Do you mean names?

What are 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).

Assuming you mean names must be forbidden from being rebound, no, 
incorrect. It's only names which are shared between both threads which 
must not be re-bound. If you have names local to the thread, you can 
change them all you want without affecting any other thread.



-- 
Steven



More information about the Python-list mailing list