[Python-ideas] Allow imports to a global name
Guido van Rossum
guido at python.org
Wed Apr 11 02:36:46 CEST 2012
--Guido van Rossum (sent from Android phone)
On Apr 10, 2012 5:23 PM, "Steven D'Aprano" <steve at pearwood.info> wrote:
> 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 
> 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
> 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 functions.
> Python-ideas mailing list
> Python-ideas at python.org
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-ideas