Low Orbit Flux Logo 2 F

Python Tutorial 2.7 - Part 2

( Modules, Packages, and Classes )


This is part two of our Python 2.7 tutorial. In this section we will be covering modules and classes.

Modules

This is a very simple example of a module.

module1.py


# example module

a = 1
b = 2

def function1(n): 
   pass

def function2(n): 
   result = 5
    result += a
   return result

This example shows how to import and use a module.

test1.py


import module1


module1.function1(5)
module1.function2(8)

print(module1.__name__)

f1 = module1.function1      # assign a local name
f1(5)

When a module is imported, any executable statements are run. This only happens the first time the module is imported. They are generally meant to initialize the module.

Each module has a symbol table. This basically consists of all global variables from within the module.


module1.a             # access modules global variables
module1.b             # access modules global variables

You can show which names are defined in a module using dir(). This will list variables, functions, modules, etc. It doesn't list built-in functions and variables. There is a module named __builtin__ that can be used to show built-in names.


import module1, sys
dir(module1)         # show names in module1
dir(sys)             # show names in sys
dir()                # show currently defined names (default)


import __builtin__
dir(__builtin__)     # show built-in names

Module / Script - Dual Use

It is possible to check the name of the current module. It is stored in a global variable called __name__.

When a module is run directly, the variable __name__ is set to __main__. Using this, you can use the module as a script and still import it as a module. This will only run if when the module is executed as a script. This is great for testing when developing a module.


if __name__ == "__main__":
    pass
    # more code here

Importing Modules


# import names directly into the symbol table 
#  does NOT import the actual module name
from module1 import function1, function2 

                           
# import all names except ones starting with an underscore                   
# avoid doing this as it leads to messy code
from module1 import *      
                                         

# import module or function using a different name
import module1 as m1                            
from module1 import function1 as f1i     


# reload a module in case it was changed 
# while the script was running
reload(modulename)       

Import Path

When importing a module ( ex: module1 ) the system will search for the module in the following places:

sys.path is

sys.path in constructed from:

You can change the path with list operations if you want. For example:


import sys
sys.path.append('/opt/custom/lib')

Compiled and Optimized Files

Compiled .pyc files: