[Python-ideas] Allow imports to a global name

Guido van Rossum guido at python.org
Wed Apr 11 02:36:46 CEST 2012


+1

--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 [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.
>
> http://docs.python.org/dev/**reference/simple_stmts.html#**
> the-global-statement<http://docs.python.org/dev/reference/simple_stmts.html#the-global-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 functions.
>
>
> --
> Steven
>
> ______________________________**_________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/**mailman/listinfo/python-ideas<http://mail.python.org/mailman/listinfo/python-ideas>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20120410/5982c1cf/attachment.html>


More information about the Python-ideas mailing list