For Python, modules are source files that can be imported into a program. They can contain any Python structure and run when imported. They are compiled when first imported and stored in file (with file extension ".pyc" or ".pyo"), have their own namespaces and support Doc Strings. They are singleton objects (only one instance is loaded into memory, which is available globally for the program).
The modules are located by the interpreter through the list of folders
PYTHONPATH (sys.path), which usually includes the current directory first.
The modules are loaded with the
import statement. Thus, when using a module structure, it is necessary to identify the module. This is called absolute import.
import os print os.name
You can also import modules with relative form:
from os import name print name
By avoiding problems such as variable obfuscation, the absolute import is considered a better programming practice than the relative import.
Example of module:
# File calc.py # Function defined in module def average(list): return float(sum(list)) / len(list)
Exemple of module usage:
# Imports calc module import calc l = [23, 54, 31, 77, 12, 34] # Calls the function defined in calc print calc.media(l)
The main module of a program has the variable
__name__ equals to
__main__, thus it is possible to test if the main module:
if __name__ == "__main__": # Code here will only be runned # if it is the main module # and not when it is imported by another program pass
That way it is easy to turn a program into a module.
Another module example:
""" modutils => utility routines for modules """ import os.path import sys import glob def find(txt): """find modules with name containing the parameter """ resp =  for path in sys.path: mods = glob.glob('%s/*.py' % path) for mod in mods: if txt in os.path.basename(mod): resp.append(mod) return resp
Exemplo de uso do módulo:
from os.path import getsize, getmtime from time import localtime, asctime import modutils mods = modutils.find('xml') for mod in mods: tm = asctime(localtime(getmtime(mod))) kb = getsize(mod) / 1024 print '%s: (%d kbytes, %s)' % (mod, kb, tm)
/usr/lib/python2.7/xmlrpclib.py: (50 kbytes, Fri Apr 19 16:20:45 2013) /usr/lib/python2.7/xmllib.py: (34 kbytes, Fri Apr 19 16:20:45 2013) /usr/lib/python2.7/dist-packages/libxml2.py: (335 kbytes, Wed May 1 14:19:10 2013) /usr/lib/python2.7/dist-packages/drv_libxml2.py: (14 kbytes, Wed May 1 14:19:10 2013)
Splitting programs into modules makes it easy to reuse and locating faults in the code.