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 npPython 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.
# This notebook imports `mymod.py` and the `mypack` package, which live next to it
# in the course repository. Google Colab only opens the notebook itself, so grab
# them from GitHub when they are missing.
import sys
if 'google.colab' in sys.modules:
import os
import urllib.request
url = "https://raw.githubusercontent.com/caam37830-sci-comp/notes/main/00_python/"
files = [
"mymod.py",
"mypack/__init__.py",
"mypack/functions.py",
"mypack/more.py",
"mypack/mypack.py",
"mypack/subpackage/__init__.py",
"mypack/subpackage/functions.py",
]
for f in files:
directory = os.path.dirname(f)
if directory:
os.makedirs(directory, exist_ok=True)
urllib.request.urlretrieve(url + f, f)import mymod
mymod.plus1(1)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
import mymod as mm
mm.plus1(1)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:
from mymod import plus1, myclass
print(myclass(1,2))
print(plus1(1))We can import every public name in a module using *:
from mymod import *
plus1(1)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
dir(mymod)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:
help(mymod)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 hereAn 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.pyIn Jupyter, the %run magic runs a file as a script in the same way:
%run mymod.pyIf the file is imported as a module, __name__ is set to the name of the module instead, so the scripting block is skipped.
mymod.__name__Renaming the module with as only changes the name we use to refer to it. The module’s own __name__ stays the same:
import mymod as mm
mm.__name__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 moreThe leading . makes these relative imports, which look for modules inside the same package as the __init__.py file.
import mypackdir(mypack)hello is defined in mypack/mypack.py, and from .mypack import * put it directly into the mypack namespace:
mypack.hello()from . import functions made mypack/functions.py available as mypack.functions, so we can call cube without a separate import:
mypack.functions.cube(3)We can import a submodule from a package into a new namespace. Its __name__ records where it sits in the package:
import mypack.functions as fun1
fun1.__name__square is also in mypack/functions.py
fun1.square(2)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:
hasattr(mypack, 'subpackage')We have to import the submodule explicitly:
import mypack.subpackage.functions as fun2
fun2.plus2(3)Importing a submodule also attaches it to its parent package, so the full name now works too:
mypack.subpackage.functions.plus2(3)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:
import mymod # does not re-read mymod.py
sys.modules['mymod'] is mymodThis 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:
import importlib
importlib.reload(mymod)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 2Conventions¶
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¶
Move the
Rationalclass from Object-Oriented Programming into a modulerational.py, and import it into a new notebook. Add anif __name__ == '__main__':block that prints a few results, such asRational(1, 2) + Rational(1, 3). Check that they are printed bypython rational.py, but not byimport rational.With
rational.pyimported in a notebook, add a new method to the class inrational.py(e.g.__mul__). Can you use it without restarting the kernel? Make it work usingimportlib.reload, and then using%autoreload. DoRationalobjects you created before reloading have the new method?Edit
mypack/__init__.pyso thatplus2can be called asmypack.plus2(3)straight afterimport mypack.Use
np.__file__to find where NumPy is installed on your computer. Which entry ofsys.pathis it under?