The future of Python immutability

Adam Skutt askutt at gmail.com
Sat Sep 5 13:57:21 CEST 2009


On Sep 5, 12:06 am, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:
> 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.

Nope, the variables don't have to be global to have this problem, they
just have to be shared:

    >>> a = 3
    >>> b = lambda x: x + a
    >>> print b(3)
    6
    >>> a = 4
    >>> print b(3)
    7

Passing any lambda between threads will cause the problem I described
above, regardless of whether the variables captured are global or
not.

> What do you mean by "variables"? Do you mean names?
In the case of python I mean the name and the value, since all
variables in Python are pointers.  (Worrying about the difference
though, is semantics)
>
> What are pointer semantics?
Assignment to the variable causes it to point to another object (as
opposed to assigning a new value to the current object, like a C++
reference) and copying the variable does not create a copy of the
referred object (which necessarily implies their lifecycles are
independent).

> 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.
What does it matter, seeing as Python lacks the ability altogether?

Thanks,
Adam



More information about the Python-list mailing list