__all__ = ["Error", "encode", "decode"]     # Export these only.

from __future__ import featurename



# runme.py

def tester():
    print "It's Christmas in Heaven..."

if __name__ == '__main__':         # Only when run
    tester()                        # Not when imported



% python
>>> import runme
>>> runme.tester()
It's Christmas in Heaven...



% python runme.py
It's Christmas in Heaven...



# min.py 

def minmax(test, *args):
    res = args[0]
    for arg in args[1:]:
        if test(arg, res):
            res = arg
    return res

def lessthan(x, y): return x < y
def grtrthan(x, y): return x > y

print minmax(lessthan, 4, 2, 1, 5, 6, 3)        # self-test code
print minmax(grtrthan, 4, 2, 1, 5, 6, 3)



# min.py 

print 'I am:', __name__

def minmax(test, *args):
    res = args[0]
    for arg in args[1:]:
        if test(arg, res):
            res = arg
    return res

def lessthan(x, y): return x < y
def grtrthan(x, y): return x > y

if __name__ == '__main__':
    print minmax(lessthan, 4, 2, 1, 5, 6, 3)        # self-test code
    print minmax(grtrthan, 4, 2, 1, 5, 6, 3)



% python min.py
I am: __main__
1
6



>>> import min
I am: min
>>> min.minmax(min.lessthan, 's', 'p', 'a', 'm')
'a'



>>> import sys
>>> sys.path
['', 'D:\\PP3ECD-Partial\\Examples', 'C:\\Python25', ...more deleted...]

>>> sys.path.append('C:\\sourcedir')         # extend module search path
>>> import string                            # all imports search the new dir



>>> sys.path = [r'd:\temp']                  # change module search path
>>> sys.path.append('c:\\lp3e\\examples')    # for this process only.
>>> sys.path
['d:\\temp', 'c:\\lp3e\\examples']

>>> import string
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ImportError: No module named string



import longmodulename as name

import longmodulename
name = longmodulename
del longmodulename          # Don't keep original name.

from module import longname as name



from .spam import name

from __future__ import  absolute_import      # required till 2.7?

import string            # will always find the standard library's version

from . import string      # will search this package first



from .string import name1, name2        # import names from mypkg.string
from . import string                    # import mypkg.string
from .. import string                   # import string from parent directory



import string                               # import standard lib string

from mypkg import string                    # import mypkg.string, absolute

from . import string                        # import mypkg.string, relative

from .string import name1, name2            # import names from mypkg.string

from .. import spam                         # import a sibling of mypkg

from . import D                 # imports A.B.D
from .. import E                # imports A.E
from ..F import G               # imports A.F.G



M.name                          # Qualify object.
M.__dict__['name']              # Index namespace dictionary manually.
sys.modules['M'].name           # Index loaded-modules table manually.
getattr(M, 'name')              # Call built-in fetch function.



# mydir.py
# A module that lists the namespaces of other modules

verbose = 1

def listing(module):
    if verbose:
        print "-"*30
        print "name:", module.__name__, "file:", module.__file__
        print "-"*30

    count = 0
    for attr in module.__dict__.keys():      # Scan namespace.
        print "%02d) %s" % (count, attr),
        if attr[0:2] == "__":
            print "<built-in name>"           # Skip __file__, etc.
        else:
            print getattr(module, attr)       # Same as .__dict__[attr]
        count = count+1

    if verbose:
        print "-"*30
        print module.__name__, "has %d names" % count
        print "-"*30

if __name__ == "__main__":
    import mydir
    listing(mydir)      # Self-test code: list myself



C:\python> python mydir.py
------------------------------
name: mydir file: mydir.py
------------------------------
00) __file__ <built-in name>
01) __name__ <built-in name>
02) listing <function listing at 885450>
03) __doc__ <built-in name>
04) __builtins__ <built-in name>
05) verbose 1
------------------------------
mydir has 6 names
------------------------------



# somefile.py 

func1()               # Error: "func1" not yet assigned

def func1():
    print func2()     # Okay:  "func2" looked up later

func1()               # Error: "func2" not yet assigned

def func2():
    return "Hello"

func1()               # Okay:  "func1" and "func2" assigned


>>> import "string"
  File "<stdin>", line 1
    import "string"
                  ^
SyntaxError: invalid syntax



x = "string"
import x



>>> modname = "string"
>>> exec "import " + modname       # Run a string of code.
>>> string                         # Imported in this namespace
<module 'string'>



>>> modname = "string"
>>> string = __import__(modname)
>>> string
<module 'string'>



# nested1.py
X = 99
def printer(): print X



# nested2.py
from nested1 import X, printer      # Copy names out.
X = 88                              # Changes my "X" only!
printer()                           # nested1's X is still 99



% python nested2.py
99



# nested3.py
import nested1                    # Get module as a whole.
nested1.X = 88                    # Okay: change nested1's X
nested1.printer() 

% python nested3.py
88



>>> from module1 import *     # bad: may overwrite my names silently
>>> from module2 import *     # worse: no way to tell what we get!
>>> from module3 import *
>>> . . .

>>> func()                    # huh???



from module import X       # X may not reflect any module reloads!
 . . . 
reload(module)             # Changes module, but not my names
X                          # Still references old object

import module              # Get module, not names.
 . . . 
reload(module)             # Changes module in-place.
module.X                   # Get current X: reflects module reloads



from module import function
function(1, 2, 3)

reload(module)

import module
reload(module)
function(1, 2, 3)

import module
reload(module)
from module import function
function(1, 2, 3)



# A.py
import B              # Not reloaded when A is
import C              # Just an import of an already loaded module

% python
>>> . . . 
>>> reload(A)



# reloadall.py

import types

def status(module):
    print 'reloading', module.__name__

def transitive_reload(module, visited):
    if not visited.has_key(module):              # Trap cycles, dups.
        status(module)                           # Reload this module
        reload(module)                           # and visit children.
        visited[module] = None
        for attrobj in module.__dict__.values():     # For all attrs
            if type(attrobj) == types.ModuleType:    # Recur if module
                transitive_reload(attrobj, visited)
        
def reload_all(*args):
    visited = {  }
    for arg in args:
        if type(arg) == types.ModuleType:
            transitive_reload(arg, visited)

if __name__ == '__main__':
    import reloadall                # Test code: reload myself
    reload_all(reloadall)           # Should reload this, types




#File: recur1.py
X = 1
import recur2             # Run recur2 now if it doesn't exist.
Y = 2


#File: recur2.py
from recur1 import X      # Okay: "X" already assigned
from recur1 import Y      # Error: "Y" not yet assigned


>>> import recur1
Traceback (innermost last):
  File "<stdin>", line 1, in ?
  File "recur1.py", line 2, in ?
    import recur2
  File "recur2.py", line 2, in ?
    from recur1 import Y   # Error: "Y" not yet assigned
ImportError: cannot import name Y

