Welcome, guest | Sign In | My Account | Store | Cart

I just like to share this... please feel free to comment/suggest on it

Python, 40 lines
 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")

3 comments

Federico Garcia Jr. (author) 16 years, 3 months ago  # | flag

newer version...

newer version, can now import from list

Note: the first param is a list..
import_once( ['os', 'sys'] )

Thanks :D
Hamish Lawson 16 years, 3 months ago  # | flag

Motivation? The import statement already has run-once semantics, so I'm not sure I see the purpose of this.

Federico Garcia Jr. (author) 16 years, 3 months ago  # | flag

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

Created by Federico Garcia Jr. on Mon, 15 May 2006 (PSF)
Python recipes (4591)
Federico Garcia Jr.'s recipes (2)

Required Modules

  • (none specified)

Other Information and Tasks