Using Modules
You want to use a Python module in your program.
Use the import command:
import random |
Discussion
There is a very large number of modules (sometimes called libraries) available for Python. Many are included with Python as standard and others can be downloaded and installed into Python.
Standard Python libraries include modules for random numbers, database access, various Internet protocols, object serialization, and many more.
One consequence of having so many modules is that there is the potential for conflict—for example, if two modules have a function of the same name. To avoid such conflicts, when importing a module, you can specify how much of the module is accessible.
For example, if you just use a command like this:
import random |
there is no possibility of any conflicts because you will only be able to access any functions or variables in the module by prefixing them with random.. (Incidentally, we will be meeting the random package in the next recipe.)
If, on the other hand, you use the following command, everything in the module will be accessible without your having to put anything in front of it. Unless you know what all the functions are in all the modules you are using, there is a much greater chance of conflict.
from random import * |
In between these two extremes, you can explicitly specify those components of a module that you need within a program so that they can be conveniently used without any prefix.
For example:
>>> from random import randint >>> print(randint(1,6)) 2 >>> |
A third option is to use the as keyword to provide a more convenient or meaningful name for the module when referencing it.
>>> import random as R >>> R.randint(1, 6) |
See Also
For a definitive list of the modules included with Python, see http://docs.python.org/2/library/.