[Python-ideas] Allow imports to a global name

Nick Coghlan ncoghlan at gmail.com
Wed Apr 11 02:59:47 CEST 2012


On Wed, Apr 11, 2012 at 10:36 AM, Guido van Rossum <guido at python.org> wrote:
> +1

Ditto. FWIW, I'm actually in favour of dropping everything after the
"or" in that paragraph from the language spec, since we don't enforce
*any* of it. Aside from formal parameter definitions (which explicitly
declare local variables), name binding operations are just name
binding operations regardless of the specific syntax.

With global:

>>> def f():
...   global x
...   for x in (): pass
...   class x: pass
...   def x(): pass
...   import sys as x
...
>>> f()
>>> x
<module 'sys' (built-in)>

With nonlocal:

>>> def outer():
...   x = 1
...   def inner():
...     nonlocal x
...     for x in (): pass
...     class x: pass
...     def x(): pass
...     import sys as x
...   inner()
...   return x
...
>>> outer()
<module 'sys' (built-in)>

By contrast:

>>> def f(x):
...   global x
...
  File "<stdin>", line 1
SyntaxError: name 'x' is parameter and global
>>> def outer(x):
...   def inner(x):
...     nonlocal x
...
SyntaxError: name 'x' is parameter and nonlocal

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list