Modules

Modules are pre-written packages of code that can be loaded and used in a Python program.
They are similar to libraries in other languages.

Many standard modules exist, such as math, which contains trig and other math functions, and string, which contains useful string-handling functions.

You can also create new modules to encapsulate your own code.

















A module is loaded using the import statement.
Once it's imported, all of a module's functions and variables are accessible, through the module name.

>>> import math
>>> math.sin(1)
0.8414709848078965
>>> math.pi
3.1415926535897931
>>> math.sin(math.pi * 2)
-2.4492127076447545e-16
















The from ... import * statement can be used to avoid having to prefix the functions with the module name.

>>> from math import *
>>> pi
3.1415926535897931
>>> sin(0)
0.0
















Create your own modules by placing the code in a file with the extension ".py".
Don't include the .py extension when importing the module.

/home/dave> cat > mymodule.py
def foo(x):
        return x * 17

/home/dave> python
Python 2.2.2 (#1, Mar 17 2003, 15:17:58)
[GCC 3.3 20030226 (prerelease) (SuSE Linux)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymodule
>>> mymodule.foo(3)
51





next