Skip to content
Python for Quantitative Finance / Files, Exceptions, and Modules

Modules and Organizing Code Across Files

Every program built so far has lived in a single file. That is fine for a script of a few dozen lines, but it breaks down the moment a program grows — multiple people working on the same file is a recipe for conflicting edits, and a single enormous file is hard to navigate even alone. Modules are Python's mechanism for splitting a program across multiple .py files while still letting each file use code defined in the others. This note covers import, the dot-notation access it introduces, and why Python's module system is designed the way it is — to protect against exactly the kind of accidental name clash that a large, multi-author program would otherwise be vulnerable to.
Learning objectives. By the end of this note you should be able to:
  • write a module (a .py file of definitions) and import it from another file, accessing its contents via dot notation;
  • explain why a module has its own private symbol table, and how this prevents a name defined in one file from silently colliding with a same-named variable elsewhere;
  • state the difference between import module_name and from module_name import *, and why this vault avoids the latter;
  • recognise that a module's top-level statements run only once per interpreter session, and predict the resulting behaviour when a module is edited mid-session.

In this lesson

  1. Modules: a .py file of definitions
  2. Why modules have their own private symbol table
  3. Modules run their top-level code once

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.