Department of Engineering

IT Services

Multiple File Python

Here are some notes about issues arising when you use code from many files. They're adapted from and


Things can only be imported if they're in a folder where Python searches. A list of these folders is stored in sys.path. This is initialised with the folder containing the input script, the value of the Unix environmental variable PYTHONPATH and the installation default list of system folders. Users can add to it if they wish.


A module is any python source file on your python library path. If you have a file called then

import foo

makes everything declared in the top level of accessible if the prefix foo. is used. Using

from foo import fun1

makes fun1 available from foo without requiring a prefix.


from foo import *

imports all names from foo except those beginning with _ (an underscore). This can be risky because you may import things that have the same name as existing functions.

When you run a Python module directly (e.g. python the code in the module will be executed, just as if you imported it, but with the __name__ variable set to __main__. That means that by adding this code at the end of your module:

if __name__ == "__main__":

you can make some code run only if the file is run directly.

If foo is imported, and has

from .bar import fun2

(note the extra dot) then a file called will be sought in the same folder as

Each module has its own private symbols, which won't clash with a user’s global variables.The built-in function dir() is used to find out which names a module defines. Without arguments, dir() lists the names you have defined currently.


A package is used for bundling modules together. Any folder on your python path that contains a file name is a package, and can contain modules or more packages.