Suggestion: Python global scope

André andre.roberge at gmail.com
Tue Jul 15 10:44:08 EDT 2008


On Jul 15, 10:13 am, Nick Dumas <drako... at gmail.com> wrote:
> The function of the global keyword is to 'push' local variables to the
> global scope. If you want to 'import' a variable into a local scope,
> pass the variable to your function/method as an argument.
> Anonymous Bastard wrote:
> > I've been tossing this idea in my mind for some time now:
>
> > In Python, declaring a variable using the global statement automatically
> > makes it available in all subsequent scopes.
>
> > But to me, it makes more sense to use the global statement to 'import' a
> > variable from the global scope into the current scope. For instance:
>
> > [code]
> > global X
> > X = 1
>
> > def P():
> >     X = 2
> >     print X
> >     global X
> >     print X
>
> > print X
> > P()
> > print X
> > [code]
>
> > Currently, this will print 1, 2, 2 and 2. But if global would be limited
> > to current scope, it would print 1, 2, 1, 1.
>
> > 'X = 2' would work on the local version of X, 'global X' will 'import'
> > the global X into the local scope, so any actions on X would reference
> > the global X, rather than previous X.
>
Alternatively, inside the function, you can have
_X = X
and use _X afterwards.  This is a lot more explicit imo.  Giving a
different meaning to "global" like the one you suggest would make it
extremely difficult to mimic its current behaviour - whereas what you
want to do can be done with a simple change assignment (or passing an
argument to the function).

Ask yourself: given change Y that I propose to Python, how would I
still be able to do Z which is the current behaviour and is found to
be useful by others?

André



More information about the Python-list mailing list