[Tutor] Newbie trying to understand modules and code reuse

Alan Gauld alan.gauld at blueyonder.co.uk
Thu Feb 5 17:23:31 EST 2004

> I'm having a difficult time trying to understand modules
> with python. I used to write php applications and am used
> to including files

In Python you don't include files you import names.
This is an important distinction.

> My problem is, I don't know how to write a module.
> I have read the manuals and it just doesn't make sense yet.

OK, I dunno which bits you read but a module in Python is
just a file full of python code. Lets call it mymodule.py

If you do

import mymodule

you make the name of the module available in your file.
At the same time Python will execute the file and thus
any function or class definitions will be executed and
the functions and classes will be available for use.
BUT their names will be inside the mymodule object.

To access anything inside the module you need to prepend
it with the module object name:


If the file name is long you might like to rename the module
by importing it like this:

import mymodule as m

Now we can access the function like this:


The module object remains the same we have just given it a
shorter name.

The other way to get at the contents of a module is to do this:

from mymodule import myfunction

This brings the name myfunction into your file but not the
name mymodule nor any of the other names within mymodule.
You can also "from mymodule import *" but that's usually
a bad idea since it brings all the names from mymodule into
your file, potentially overwriting some of them.

> Ultimately I'd like to create 2 "include files".

Two modules

> 1 will be a class file that I plan to reuse throughout my

This is a good idea.

> 1 file will be a list of variables.

THis is an extremely bad idea. The whole idea of modules
controlling names is to avoid global variables spilling
over from one module to another. Its much better to keep
the variables within the modules where they are needed.
You can access them by prefixing with the parent module's

> I tried create a file and putting it in my /python/lib
> directory and importing it. Surprisingly I was able to
> import it but I was unable to access the variables or
> methods in the file.

AS I described above you import the name of the module
into your local namespace. You do not import the file itself.
Thats why we "import mymodule" and not "mymodule.py"

> Perhaps I should use something else for code reuse?

You have the right idea but just need to adapt from
the C/C++/PHP style of copy n paste include to the more
theoretically sound importing of names.

You might like to read both the modules and namespaces topics
in my tutorial.

Alan G
Author of the Learn to Program web tutor

More information about the Tutor mailing list