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 https://stephensugden.com/crash_into_python/CodeOrganization.html and https://docs.python.org/3/tutorial/modules.html

Paths

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.

Modules

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

import foo

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

from foo import fun1

makes fun1 available from foo without requiring a prefix.

Using

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 foo.py) 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 foo.py has

from .bar import fun2

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

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.

Packages

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