>> That would be solved if, instead of marking variables in inner scopes >> that refer to outer scopes, it were the other way round, and >> variables in the outer scope were marked as being rebindable in inner >> scopes. ... Guido> This would only apply to *assignment* from inner scopes, not to Guido> *use* from inner scopes, right? (Otherwise it would be seriously Guido> backwards incompatible.)
Given that the global keyword or something like it is here to stay (being preferable over some attribute-style access) and that global variable writes needs to be known to the compiler for future efficiency reasons, I think we need to consider modifications of the current global statement. The best thing I've seen so far (I forget who proposed it) is
'global' vars [ 'in' named_scope ]
where named_scope can only be the name of a function which encloses the function containing the declaration. In Greg's example of inc_x_by nested inside f, he'd have declared:
global x in f
in inc_x_by. The current global statement (without a scoping clause) would continue to refer to the outermost scope of the module.
This should be compatible with existing usage. The only problem I see is whether the named_scope needs to be known at compile time or if it can be deferred until run time. For example, should this
import random def outer(a): x = a def inner(a): x = 42 def innermost(r): if r < 0.5: global x in inner else: global x in outer x = r print " inner, x @ start:", x innermost(random.random()) print " inner, x @ end:", x print "outer, x @ start:", x inner(a) print "outer, x @ end:", x outer(12.73)
be valid? My thought is that it shouldn't.