[Tutor] importing into a function

Dave Angel davea at davea.name
Wed Jul 10 21:57:37 CEST 2013


On 07/10/2013 03:02 PM, Jim Mooney wrote:
> Boy, is the list busy. Python must have been mentioned on USA today,
> or something ;')
>
> Anyway, I was reading the datamodel, and it mentioned imported modules
> going out of scope, which seemed odd, since I thought they were global
> and never went out, or am I thinking wrong?

You're confusing two separate things.  Once something is imported, it 
stays imported.  sys.modules has a reference to it, and normally, it's 
never forgotten.

However, the name you assigned locally may go out of scope quite 
readily.  And next time the function does the import, it'll basically 
turn into a simple assignment, something like:
   def testimp(imp):
        math = sys.modules["math"]


>
> Anyway, I figured an import would go out of scope it if was in a function:
>
> #Using C:\Python33\python.exe on Win 7 in c:\python33\jimprogs
>
> def testimp(inp):
>      import math
>      return math.sqrt(inp)
>
> print(testimp(25)) # result - 5.0
>
> print(math.sqrt(25)) # result error traceback, math undefined
>
> 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.


> protects you from invisible
> namespace pollution by a big module with a lot of names. But importing
> has to be a big overhead. So does importing into a function make sense
> at any time, or is it a dead end?
>

Importing is a lot quicker than you realize.  Over a hundred modules are 
imported for you before your script even starts.  But more importantly, 
they are cached.

However, a large module that is NOT preloaded by the interpreter, and 
that may not be actually needed, is a good candidate for loading inside 
a function, or even conditionally at top-level.

The other, less important, reason might be just to spread out the 
startup overhead by deferring a tiny bit of it till later.



-- 
DaveA



More information about the Tutor mailing list