[Python-ideas] Allow imports to a global name

Steven D'Aprano steve at pearwood.info
Wed Apr 11 02:22:31 CEST 2012

Sven Marnach wrote:
> Sometimes it is useful to do a import to a global name inside a
> function.  A common use case is the 'pylab' module, which must be
> imported *after* the backend has been set using 'matplotlib.use()'.
> If the backend is configuration-dependent, the statement
>     import pylab
> will usually be inside a function, but the module should be available
> globally, so you would do
>     global pylab
>     import pylab
> While this code works (at least in CPython), the current language
> specification forbids it [1]

I quote:

     Names listed in a global statement must not be defined as
     formal parameters or in a for loop control target, class
     definition, function definition, or import statement.


I can understand that it makes no sense to declare a function parameter as 
global, and I can an argument in favour of optimizing for loops by ensuring 
that the target is always a local rather than global. But what is the 
rationale for prohibiting globals being used for classes, functions, and imports?

It seems like an unnecessary restriction, particularly since CPython doesn't 
bother to enforce it. The semantics of "global x; import x" is simple and obvious.

+1 on removing the unenforced prohibition on global class/def/import inside 


More information about the Python-ideas mailing list