I just like to share this... please feel free to comment/suggest on it
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | def import_once(modulenames, silent=1):
## import_once
## Fedmich Last modified: 3:38 PM 5/15/2006
## version 1.1
## Usage:
## import_once('os')
## import_once( ["os", 'sys'] )
if type(modulenames) is list:
pass
elif type(modulenames) is tuple:
pass
else:
modulenames = [modulenames]
imported = 0
for modulename in modulenames:
print modulename
if globals().has_key(modulename):
if not silent: print """Already imported module "%s"...""" % modulename
imported +=1
else:
try:
if not silent: print """%s is not yet imported so import it now...""" % modulename
globals()[modulename] = __import__(modulename, globals(), locals(), [])
imported += 1
except:
if not silent: print """Error while importing "%s"...""" % modulename
return (imported == len(modulenames) ) #return true if every modules are successfuly imported
print import_once( ("os", "sys") )
import_once( "sys")
import_once("oyster")
import_once("psyco", silent=0) #silent is used for debugging...
print os
print sys
print os.path.basename(r"c:\WINNT")
|
newer version...
Motivation? The import statement already has run-once semantics, so I'm not sure I see the purpose of this.
I made this because I was using mutiple classes from multiple scripts and those scripts usually have similar "import os", "import sys". I have then notice that it is slow when it reimports the module... After I used import_once('os'), the difference on speed is really noticeable on my SLOW computer. btw, I was using it on a CGI server.
Thanks for the comment