Module (Python)

Not all of the many functions built into Python are loaded by default - we usually only need a few of them, so that would be very inefficient. Instead, Python organizes functions into modules, which we can load as needed.


Modules are loaded with an import statement:

import moduleName

While import statements can technically be anywhere, programmers usually put them at the beginning of their programs, so the entire program can use them.

To use a function from a module, we then need to preface the function name with the module name and a period. So, for example, if we wanted to use randint and uniform from the random module we'd have to type something like

import random # this should be at the beginning of the program
x = random.randint(1,10) # assigns to x a random integer between 1 and 10 (inclusive)
y = random.uniform(3,4) # assigns to y a random float between 3 and 4

Alternately, we could import only the function(s) we need, rather than the whole module. To do this, we need to specify the functions we want, and where to import them from. This way, because we've explicitly identified the functions we want and where to find them, we don't need to preface them with the name of the module. For example, the following is equivalent to our first example:

from random import randint, uniform
# Note that we don't need 'random.' when we import this way:
x = randint(1,10) # assigns to x a random integer between 1 and 10 (inclusive).
y = uniform(3,4) # assigns to y a random float between 3 and 4

Finally, we can combine the previous two methods, and directly import the entire contents of a module with an asterisk:

from random import *

This will import each function in the random module. Then, as in the second example above, we won't have to preface each one with random. whenever we use them.

However, this method is somewhat risky, because if you accidentally import two functions with the same name from different modules only the second version will be accessible. Hence, it's usually better to use the first method described above - naming the module explicitly eliminates any possible ambiguity.

Making Your Own Modules

Any Python file can also be imported as a module. For example, suppose we defined a function myFunc in Then in any other program (saved in the same directory) we could use myFunc by typing

import myProg #note that we omit the .py

Note that when importing a program Python runs the program, so in the above example myProg would be run when it's imported (if there is anything to run, that is). It's possible you'd want to import a module without running the code it contains, but how to do so is beyond the scope of Intro to Programming.

See Also

Python 3.2 Documentation