- A module is a file containing Python definitions and statements.
- A module's name is available through the
__name__variable. - A module can be used by a script using the
importstatement. - A module can contain executable statements and function definitions.
- The statements are only executed when the module is first imported via
importstatement.
#moduleA.py
print __name__
def print_str(str):
print str
#script.py
import moduleA
moduleA.print_str('hello')
##output
moduleA
hello- Each module has its own symbol table.
- Using
from module import ayou can import specific names from a module. from module import *imports all names except the ones beginning with an underscore.
if __name__=='__main__':
#execute some code
# python <module.py>dir(module)lists the names defined in a moduledir()lists the names defined in the current module
- For grouping a collection of modules
#sample package hierarchy
packageA/
__init__.py
packageB/
__init__.py
moduleB.py
#usage
import packageA.packageB.moduleB
or
from packageA.packageB import moduleB
moduleB.func()from a.b import c <= c can be a package/module/function/variable/class
import a.b.c<= c has to be a package or a module, not a function/variable/class