A First Look at Module Files
Earlier in this chapter, we saw how to run module files (i.e., text files containing Python statements) from the operating-system shell’s command line. It turns out that we can also run module files from Python’s interactive command line by importing or reloading them, as we’d normally do from other system components. The details of this process are covered in Chapter 5, but since this turns out to be a convenient way to save and run examples, we’ll give a quick introduction to the process.
The basic idea behind importing modules is that importers may gain access to names assigned at the top level of a module file. The names are usually assigned to services exported by the modules. For instance, suppose we use our favorite text editor to create the one-line Python module file myfile.py, shown in the following code snippet. This may be one of the world’s simplest Python modules, but it’s enough to illustrate basic module use:
title = "The Meaning of Life"
Notice that the filename has a .py suffix: this
naming convention is required for files imported from other
components. Now we can access this module’s variable
title in other components two different ways,
either by importing the module as a whole with an
import statement and qualifying the module by the
variable name we want to access:
% python
Start Python>>> import myfile
Run file, load module as a whole>>> print myfile.title
Use its names: '.' qualificationThe Meaning of Life
or by fetching (really, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access