Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Modules and Packages

Open in Colab

Jupyter notebooks are great for some things, but they aren’t so great if we want to define a large library of functions to use. Once a function is useful in more than one notebook or script, it should live in a .py file that each of them can import.

You have probably noticed that we are able to import functions to use from numpy using the import keyword

import numpy
import numpy as np

Python also comes with a standard library of modules, such as math, os, and random, which are imported the same way. You can do this with your own code by writing your own Python modules and packages.

Modules

A Python module is simply a .py file which contains definitions we would like to use. For instance, mymod.py, which sits in the same directory as this notebook, contains

"""
A simple Python module
"""

def plus1(x):
    """
    returns x + 1
    """
    return x + 1


class myclass:
    """
    simple class in a simple module
    """
    def __init__(self, a, b):
        self.a = a
        self.b = b


if __name__ == '__main__':
    print("mymod.py is being run as a script!")
    print("plus1(1) = {}".format(plus1(1)))

We’ll come back to the if __name__ == '__main__': block in the next section. To use these definitions, we import the module by its file name.

By default, the contents of the module will be imported into a namespace with the same name as the file (dropping the .py extension). We can re-name the namespace using the as keyword

We can also import specific functions or classes from a module using the from keyword, as in from module import function. The imported names can then be used without the mymod. prefix:

We can import every public name in a module using *:

This is handy for quick interactive work, but avoid it in code you want to keep. It hides where each name came from, and it silently replaces anything you had already defined with the same name. For example, from numpy import * replaces Python’s built-in sum, min, max, abs, and round with NumPy’s versions, so afterwards max(3, 5) raises an error instead of returning 5 (NumPy reads the 5 as an axis).

A module can define a list of names called __all__ to control what import * brings in. Without one, import * brings in every name that doesn’t start with an underscore.

You can see what is available in the mymod namespace using dir

The names surrounded by double underscores are set by Python when it loads the module. For instance, __doc__ holds the docstring at the top of mymod.py, and __file__ records where the module was loaded from. help collects the docstrings from the whole module into a readable summary, including the file location:

Modules vs. Scripts

What is the difference between a module and a script? Both are plain text files with a *.py extension.

Conceptually, a module groups related functions, classes, and variables that we would like to use and re-use, without needing to redefine in our interpreter every time. Typically, we use modules with an import statement. A script contains code that does something. This might include defining classes and functions, but usually also includes some sort of task such as analyzing data in a *.csv file, which it wouldn’t make sense to do in an import statement.

There isn’t really a clear cut line between modules and scripts - you might run a *.py file that was written for a module as a script, or import a *.py file that was written as a script.

If you want to have a file that can be used as both a module and a script, you can put the “scripting” part of the file in a block that begins with

if __name__ == '__main__':
    # scripting code here

An example can be found in mymod.py

__name__ is a global variable, which is set to __main__ when the file is executed from the command line, as in

python mymod.py

In Jupyter, the %run magic runs a file as a script in the same way:

If the file is imported as a module, __name__ is set to the name of the module instead, so the scripting block is skipped.

Renaming the module with as only changes the name we use to refer to it. The module’s own __name__ stays the same:

Packages

Python packages are contained in a directory with an __init__.py file. These directories may contain multiple modules (*.py files), and group related modules into a single hierarchical namespace.

They can also have nested directories with __init__.py files (sub-packages). These directories might also contain other sorts of files such as documentation files or shared object libraries.

The mypack directory next to this notebook is a small example:

mypack/
├── __init__.py
├── mypack.py          # defines hello()
├── functions.py       # defines square(x) and cube(x)
├── more.py            # defines power(x, n)
└── subpackage/
    ├── __init__.py    # empty
    └── functions.py   # defines plus2(x)

When we import mypack, Python runs mypack/__init__.py, and every name defined there becomes an attribute of mypack. This means you can use the __init__.py file to automate import of modules inside a package, or modify namespaces. Here, mypack/__init__.py contains

from .mypack import *
from . import functions
from . import more

The leading . makes these relative imports, which look for modules inside the same package as the __init__.py file.

hello is defined in mypack/mypack.py, and from .mypack import * put it directly into the mypack namespace:

from . import functions made mypack/functions.py available as mypack.functions, so we can call cube without a separate import:

We can import a submodule from a package into a new namespace. Its __name__ records where it sits in the package:

square is also in mypack/functions.py

Subpackages

We can also have subpackages in packages (subdirectories of our directory).

plus2 is defined in mypack/subpackage/functions.py. But mypack/__init__.py never imports subpackage, so import mypack alone doesn’t load it:

We have to import the submodule explicitly:

Importing a submodule also attaches it to its parent package, so the full name now works too:

Packages you install behave the same way. NumPy’s __init__.py imports numpy.linalg, so import numpy as np is enough to use np.linalg. Matplotlib’s __init__.py does not import matplotlib.pyplot, which is why we write import matplotlib.pyplot as plt in the plotting notes.

Changing a Module After Importing It

Python only runs a module’s code the first time it is imported, and stores the result in the dictionary sys.modules. Later import statements for the same module just look it up there, without reading the file again:

This is a common surprise when you write a module and use it from a notebook at the same time: you fix a bug in the .py file, re-run the import cell, and the old code still runs. You can either restart the kernel, or reload the module using importlib.reload:

reload runs the file again and updates the mymod namespace in place. It does not update names you copied out of the module with from mymod import plus1. Those still refer to the old function until you run the from import again.

IPython’s autoreload extension automates this by reloading modules before each cell runs:

%load_ext autoreload
%autoreload 2

Conventions

By convention, Python packages and modules should have short, all-lowercase names. Underscores can be used in module names if they help readability, but are discouraged in package names. See PEP 8 for reference.

PEP 8 also has rules for imports. Two of them:

  • Put imports at the top of the file (or in the first cells of a notebook), so a reader can see at a glance what the code depends on.

  • Avoid from module import *, for the reasons above.

Beyond PEP 8, the scientific Python community uses standard aliases for common packages, such as import numpy as np, import matplotlib.pyplot as plt, and import pandas as pd. Sticking to them makes your code easier for others to read.

Exercises

  1. Move the Rational class from Object-Oriented Programming into a module rational.py, and import it into a new notebook. Add an if __name__ == '__main__': block that prints a few results, such as Rational(1, 2) + Rational(1, 3). Check that they are printed by python rational.py, but not by import rational.

  2. With rational.py imported in a notebook, add a new method to the class in rational.py (e.g. __mul__). Can you use it without restarting the kernel? Make it work using importlib.reload, and then using %autoreload. Do Rational objects you created before reloading have the new method?

  3. Edit mypack/__init__.py so that plus2 can be called as mypack.plus2(3) straight after import mypack.

  4. Use np.__file__ to find where NumPy is installed on your computer. Which entry of sys.path is it under?