A Beginner's Python Tutorial/Importing Modules

Last lesson we covered the killer topic of Classes. As you can remember, classes are neat combinations of variables and functions in a nice, neat package. Programming lingo calls this feature encapsulation, but reguardless of what it is called, it's a really cool feature for keeping things together so the code can be used in many instances in lots of places. Of course, you've got to ask, "how do I get my classes to many places, in many programs?". The answer is to put them into a module, to be imported into other programs.

As you see, a module looks pretty much like your normal Python program.

So what do we do with a module? We import bits of it (or all of it) into other programs.

To import all the variables, functions and classes from moduletest.py into another program you are writing, we use the import operator. For example, to import moduletest.py into your main program, you would have this:

Code Example 2 - mainprogram.py

### mainprogam.py### IMPORTS ANOTHER MODULEimport moduletest

This assumes that the module is in the same directory as mainprogram.py, or is a default module that comes with python. You leave out the '.py' at the end of the file - it is ignored. You normally put all import statements at the beginning of the python file, but technically they can be anywhere. In order to use the items in the module in your main program, you use the following:

Code Example 3 - mainprogram.py continued

### USING AN IMPORTED MODULE# Use the form modulename.itemname# Examples:print moduletest.ageofqueen
cfcpiano = moduletest.Piano()
cfcpiano.printdetails()

As you see, the modules that you import act very much like the classes we looked at last lesson - anything inside them must be preceeded with modulename. for it to work.

What is the point of this? Well, maybe you could use it to make your code a little more readable. If we get into heaps of modules inside modules, it could also remove that extra layer of crypticness.

If you wanted to, you could import everything from a module is this way by using from modulename import *. Of course, this can be troublesome if there are objects in your program with the same name as some items in the module. With large modules, this can easily happen, and can cause many a headache. A better way to do this would be to import a module in the normal way (without the from operator) and then assign items to a local name:

Code Example 5 - mainprogram.py continued

### ASSIGNING ITEMS TO A LOCAL NAME# Assigning to a local name
timesfour = moduletest.timesfour# Using the local nameprint timesfour(565)

This way, you can remove some crypticness, AND have all of the items from a certain module.