Engineering Computing

Scripts, Modules, and Imports

As we have seen, the main code for a Python program is written in a file called a script. There are a few reasons we often want to use multiple files for a single program:

  1. For large programs, a single file becomes unwieldy or difficult to navigate.
  2. Portions of our program, like function and class definitions, are self-contained and potentially useful for other programs.
  3. A code library (with its own files) is available to perform certain tasks without writing that code ourselves (see section 2.3).

In these cases, files containing definitions and statements (usually constants, functions, and classes) called modules can be imported to a main script. We often write our own modules for the first two cases above; that is, when our script gets long or certain definitions may be useful for other programs. For example, if we have defined a function do_something() in a module file a_module.py placed in the same directory as our main script, we can import the module and use that function in the main script with the following statements:

import a_module         # Import the module
a_module.do_something() # Call the imported function

Note that the function is available as an attribute of a_module (sans .py); that is, to access the function do_something(), we must call a_module.do_something(). This keeps us from accidentally overwriting names in the main main script or from other modules. Occasionally, we may want a specific definition from a module to be directly available in the script. This can be achieved with the following statements:

from a_module import do_something # Import function from the module
do_something()                    # Call the imported function

Occasionally, the name of a module is longer than is convenient to use within a script. In this case, we can give the module a nickname, as in

import a_module as am   # Import the module
am.do_something()       # Call the imported function

For a project with several modules, it is best to move modules into subdirectories with names that clearly indicate their functionality. For instance, with a module in one subdirectory blue_things/cyanotype.py and another module in another subdirectory red_things/redscale.py, importing these modules requires the following statements:

import blue_things.cyanotype
import red_things.redscale

Note that the dot “.” indicates that a directory contains the module that follows.

Online Resources for Section 2.2

No online resources.