Closures in leu of pointers?

Michael Torrie torriem at gmail.com
Sat Jun 29 10:02:17 EDT 2013


On 06/29/2013 05:21 AM, cts.private.yahoo at gmail.com wrote:
> Thank you.  You reminded me of the (weak) workaround of using arrays
> and confirmed my suspicion that I although I can read the variable, I
> won't be able to write to it.  I still don't understand why not,
> though...

The real problem here is that you don't understand how python variables
work.  And in fact, python does not have variables.  It has names that
bind to objects.  If you assign a value to a name, you're not
overwriting a variable, you're rebinding a name to a new object in the
default scope (unless it's declared global, or nonlocal in python 3, the
latter I assume uses the same scope in which it was first declared, but
I could be wrong).  Since the name is in the local scope, the original
name in the caller's scope is still bound to its original object.

Furthermore, most primitive objects in python (strings, ints, etc) are
immutable, which means they can *never change*.  "Writing" to a variable
simply dereferences the old object (which may still be referenced in the
caller's scope) and creates a new object and binds it to the name.

A list is mutable, which is why it's one solution to emulate a variable.

> As for python 3 ... "nonlocal"?  I see I'm not alone in picking
> obnoxious names ...

nonlocal at least has meaning.



More information about the Python-list mailing list