Q: Python 2.0 preliminary features?

skaller skaller at maxtal.com.au
Tue Oct 12 15:51:20 EDT 1999


Jeremy Hylton wrote:
> 
> I don't understand why you need the global declaration in g.
> 
>     def f():
>        x = 0
>        def g():
>           global x
>           def h():
>             global x
>             x = 1
> 
> At compile time, you should know which scopes have local variables
> named x and which have global declarations for x.  If g does not have
> a local variable named x, then the global declaration in h can't
> sensibly mean the local variable x in g's scope.
>
	Sure it can!! This is standard Python:

	def q():
		global x
		x = 1

Here, there is no 'global' variable x, it is in fact created
by executing q. There is no way to 'know' which scope a nested
function's 'global' statement refers to without a convention.
The Python convention is 'module scope, always', which also
applies to all non-local variables on reading.

However, there is a new factor here I overlooked: a function
can gave a local variable that is NOT visible in the function,
not even in an 'exec': one which is local because it is declared
global in a function nested in it.

> The requirement that there be a global declaration in every
> intervening scope seems unnecessary and error-prone.  If you miss one
> global statement, you get either weird behavior or exceptions.

	You are right it may be error prone, but _something_ is necesary.
 
> This isn't exactly compatible with the current semantics for global,
> but it would only cause problems for really obscure code, like this:
> 
>     x = 12
>     def spam():
>         x = 1
>         def eggs():
>             global x
>             y = x - 2
> 
> Under current global semantics, the x in eggs would refer to the
> global variable x with the value 12.  Under the new semantics, the x
> in eggs would refer to the local variable x in spam with the value 1.
> So it would break some code, but not very much; only code that uses
> multiple nested functions that use the same name for local and global
> variables.

Your rule would only work if the variable was, in fact, created by the
enclosing function before it was used in the enclosed function.
This is contrary to the current rule, where the enclosing function
is taken as module scope.

-- 
John Skaller, mailto:skaller at maxtal.com.au
1/10 Toxteth Rd Glebe NSW 2037 Australia
homepage: http://www.maxtal.com.au/~skaller
downloads: http://www.triode.net.au/~skaller




More information about the Python-list mailing list