[Tutor] Understanding (Complex) Modules

bob gailer bgailer at gmail.com
Fri Mar 5 15:27:20 CET 2010


Clarifications:

A module is a file. It may or may not contain python code. If it does 
not an exception will be raised when importing.

Import executes the module's code exactly the same as if the module had 
been run as a script (main program).

References to module objects are stored in a dict (sys.modules)s. You 
will notice many modules that have been "pre-imported":

 >>> import sys
 >>> for x in sys.modules.keys(): print x
...
'copy_reg'
'sre_compile'
'locale'
'_sre'
'functools'
'encodings'
'site'
'__builtin__'
'operator'
'__main__'
'types'
'encodings.encodings'
'abc'
'encodings.cp437'
'errno'
'encodings.codecs'
'sre_constants'
're'
'_abcoll'
'ntpath'
'_codecs'
'nt'
'_warnings'
'genericpath'
'stat'
'zipimport'
'encodings.__builtin__'
'warnings'
'UserDict'
'encodings.cp1252'
'sys'
'codecs'
'os.path'
'_functools'
'_locale'
'signal'
'linecache'
'encodings.aliases'
'exceptions'
'sre_parse'
'os'
 >>>

So all import sys does is:
   sys = sys.modules['sys']

Whereas import foo (assuming we refer to foo.py):
   if 'foo' in sys.modules:
     foo = sys.modules['foo']
   else:
     compile foo.py
     if successful:
       execute the compiled code thus creating a module object
       if successful:
         sys.modules['foo'] = the new module object
         foo = sys.modules['foo']
Herelin lies a gotcha:
   import foo again does NOT recompile; it just reassigns foo = 
sys.modules['foo'].
   reload(foo) will go thru the compile execute assign sequence again.

Notice __main__ - that is the module of the main program.
 >>> sys.modules['__main__']
<module '__main__' (built-in)>
 >>> dir(sys.modules['__main__'])
['__builtins__', '__doc__', '__name__', '__package__', 'sys', 'x']
 >>>

-- 
Bob Gailer
919-636-4239
Chapel Hill NC



More information about the Tutor mailing list