Suggestion: Python global scope

Carl Banks pavlovevidence at gmail.com
Tue Jul 15 12:39:02 EDT 2008


On Jul 15, 7:57 am, Anonymous Bastard <bast... at example.org> 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.

No way.  You'd need to find another keyword.  "localize" might be a
better word to use.


> 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.

What would it print if you changed P to this?

def P():
     X = 2
     print X
     global X
     print X
     X = 3

Would it print 1, 2, 1, 1 or 1, 2, 1, 3?


> '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.

Do you have a specific use case in mind?  Where would this sort of
thing be useful?

(The be sure, I can think of a use case for something like this,
namely optimizing away hash lookups for frequently used globals.  But
such an optimization doesn't justify new syntax, especially when you
can already do it only slightly less conveniently.)


Carl Banks



More information about the Python-list mailing list