Writing modules

Up to now we have uses python in an interactive way, using ipython. It is useful, however, to put your code in a module so you can use it again.

A module in python is nothing more than a collection of simple text files that contain python code. In the simplest case a module is a single file.

Creating your first python file

We will create now your first module. First, create a folder that will contain all your future modules, e.g. mymodules. Then, open a text editor (e.g. notepad, notepad++, gedit, ...) and write inside a python commands:

print "This is my first file"

Now, save the file with a name you choose, giving the extension .py, e.g. first_file.py. Save the file in the folder you just created.

You can now open a command line (terminal) and run the file, using the command:

python first_file.py

All the command in the file will now be executed and you should see the message “This is my first file” appear in the command line.

Importing the module

You can now use the same from ipython or even from within other python modules. To import the module, start ipython and navigate to the folder where you stored the file for example:

cd /home/user/mymodules/

using the path to your own folder.

You can now import the module using its name, without the .py extension:

>>> import first_file

When you import a file, all the commands that are in the file are executed. In our case, you should see the text “This is my first file” appear. Admittedly, this is not yet very useful, as your file does not contain any code that you can reuse. Your modules will become more useful when you start using functions, as we will see later.

Import search path

In the above case we had to navigate to the folder were the file was located to use it. This is not very convenient, especially is you have modules located in different folders.

Every time you try to import a module Python will search at a number of locations to find a module with the required name:

  • the current directory
  • a list of directories that are calls the python paths.

You can see which directories are in your python path by running the following commands in ipython:

>>> import sys
>>> print sys.path

The built-in sys module gives you access to a number of system specific variables, like the current version of python and the system path. The second command should give you a list of directories that are currently in the search path of python.

You can add modify the above list and add the folder with your own modules. In this way you don’t need to navigate every time in the folder before importing a module:

>>> sys.path.append['/home/user/mymodules/']

changing again the above string to the location of your folder.

See also

Detailed description of python modules in the official documentation.

The procedure for adding a python path permanently depends on your operating system (e.g. windows or linux and Mac). You can find more information online.