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.
In [1]:
import os
print os.name
You can also import modules with relative form:
In [2]:
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:
In [ ]:
# File calc.py
# Function defined in module
def average(list):
return float(sum(list)) / len(list)
Exemple of module usage:
In [4]:
# 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:
In [6]:
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:
In [ ]:
"""
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:
In [7]:
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)
Splitting programs into modules makes it easy to reuse and locating faults in the code.
In [1]:
Out[1]: