[Tutor] importing into a function
eryksun
eryksun at gmail.com
Wed Jul 10 23:16:44 CEST 2013
On Wed, Jul 10, 2013 at 3:57 PM, Dave Angel <davea at davea.name> wrote:
>>
>> Sure enough it did. The question is - does importing into a function
>> ever make sense? It occurred to me that if you use from module
>> import * , putting it in a function
>
> Can't be done. Locals of a function are all known at compile time.
That depends. 2.x issues a warning and disables optimization, so the
function's locals use a dict:
>>> from inspect import CO_OPTIMIZED
>>> def f(): from Tkinter import *
...
<stdin>:1: SyntaxWarning: import * only allowed at module level
>>> f.__code__.co_flags & CO_OPTIMIZED
0
I'm not saying this is a good idea. It isn't compatible with 3.x, you
lose the ability to create a closure (i.e. a nested function with free
variables), you lose the efficiency of the fast locals array, and
every call has to create and update a locals dict.
More information about the Tutor
mailing list