Q: Python 2.0 preliminary features?

Eric Jacobs x at x.x
Tue Oct 12 20:07:53 EDT 1999


Jeremy Hylton wrote:
>
> Ok.  I think I've got it now.  These are the read-only variant of
> closures, right?  So the following will not work?
> 
> def make_accumulator():
>     sum = 0
>     def accumulate(x):
>         sum = sum + x
>         return sum
>     return accumulate

Right. It won't do what you'd expect it to do. This is a problem
with the syntax of Python, rather than any particular method of
implementing closures. The problem is that because Python doesn't
require variables to declared before they are used, the statement
"sum = sum + x" doesn't specify in itself whether a new "sum"
variable is to be created in the innermost scope, or the "sum"
that's in the make_accumulator scope is to be modified. (Or,
for that matter, any scope beyond that.)

This "read-only-ness" really isn't specific to lexical scoping.
It's just the way Python has traditionally done business
whenever multiple namespaces are tied together. It's the
same sort of thing as in standard Python:

class c:
	x = 5

and if I give you an instance of c, you can read my 5 (from
the class namespace) but not modify it (because you always
modify your instance's namespace.) Hence, read-only.




More information about the Python-list mailing list