[Python-ideas] Allow imports to a global name
Sven Marnach
sven at marnach.net
Tue Apr 10 20:27:11 CEST 2012
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], so the correct code should be
global pylab
import pylab as _pylab
pylab = _pylab
I don't see why we shouldn't allow the shorter version -- it is
certainly easier to read.
The behaviour of pylab might be considered a questionable design
choice. I've encountered the above non-conforming, but working code
out in the wild several times, though, so the language specification
might as well allow it.
Cheers,
Sven
[1]: http://docs.python.org/dev/reference/simple_stmts.html#the-global-statement
More information about the Python-ideas
mailing list