[Tutor] importing into a function

Jim Mooney cybervigilante at gmail.com
Wed Jul 10 21:02:16 CEST 2013


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?

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 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?

-- 
Jim

Although the darling of health faddists, there is no such thing as
canola oil, since there is no canola plant - it's genetically modified
rapeseed oil given a nicer name ;')


More information about the Tutor mailing list