Python modules

Ben Finney ben+python at
Mon Nov 10 06:12:07 CET 2014

Steve Hayes <hayesstw at> writes:

> I have a book on Python that advocates dividing programs into modules,
> and importing them when needed.

Which book is this? (This is not essential to your question, but it
might help to gauge your broader learning environment.)

> I can understand doing that in a compiled language, where different
> modules can be imported from all sorts of places when the program is
> compiled.

Python is a compiled language; when you run a Python program a necessary
step is to compile the Python source to a bytecode for actual execution.

Usually, the compilation step is done dynamically; but (barring
contrived examples) it is always done prior to running the program.

> But I understand that Python is an interpreted language

The two are not mutually exclusive. The Python interpreter works with
compiled Python code, it does not execute the source directly.

> If I wrote a program in Python like that, and wanted to run it on
> another computer, how would it find all the modules to import at
> run-time, unless I copied the whole directory structure over to the
> other computer?

That's the idea, yes. You need to distinguish between:

* The standard library: installed along with the Python interpreter when
  you install that, and available on the default module search path.

* Third-party modules: installed using your package manager (ideally by
  the operating system package manager), again to a location already
  part of the default module search path on your system.

* Modules specific to the application you're writing: Keep these in a
  known hierarchy, and use the distribution tools to package them to
  keep them together when distributing to oher machines.

Use abolute import for standard library and third-party modules. Use
relative import for application-private modules.

This ensures your aplication's private modules don't conflict with
current or future names of modules from the standard library or third

You are working through the Python tutorial step by step, right?
<URL:> This topic is covered when you
learn about modules <URL:>.

 \       “I am amazed, O Wall, that you have not collapsed and fallen, |
  `\            since you must bear the tedious stupidities of so many |
_o__)                  scrawlers.” —anonymous graffiti, Pompeii, 79 CE |
Ben Finney

More information about the Python-list mailing list