Python-Ref > Basic usage > Modules > Using modules
 
 

^^->

Using modules

Python comes packed with a huge standard library that contains functions for almost any possible programming task. In order to ease the maintenance of the code and prevent namespace collisions (functions with same names overriding each other) Python has the concept of modules. A module usually contains functions, classes and constants specific to one problem or class of problems.
Usage of modules is demonstrated in many examples on this site and therefore I provide only one short example to show how to import modules in different ways.
Expand/Shrink
Zdroj: (modules1.1.py)
  1   import string   # import a module
  2   print string.ascii_lowercase   # print a constant from a module
  3   print string.capwords   # a function from a module
  4   
  5   
  6   from time import time   # import function time from module time
  7   print time()
  8   
  9   
 10   from math import sin, cos, pi   # import more things from a module
 11   print sin( pi/4)
 12   print cos( 0.5)**2 + sin(0.5)**2
 13   
 14   
 15   from calendar import *   # import everything from a module
 16   print isleap( 2004)
 17   print leapdays( 2000, 2010)
 18   
 19   
 20   import xml.dom.minidom as mini   # import a module under different name
 21   print mini
stdout:
abcdefghijklmnopqrstuvwxyz
<function capwords at 0x2af2af99f848>
1204113572.47
0.707106781187
1.0
True
3
<module 'xml.dom.minidom' from '/usr/lib64/python2.4/site-packages/_xmlplus/dom/minidom.pyc'>
Doba běhu: 49.4 ms
Please note that "from XXX import *" is considered dangerous because you can never be sure of all the things that you will import and that will polute your namespace. Such imported things might override some of the previously imported or defined objects and problems arrising from this are often hard to find.
All the modules in the example above are standard Python modules, comming with the Python distribution. On the following page I show how to create your own modules.