Written and maintained by CASRAI Editorial Board
Last updated
A module in Python is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended, so a file called qc_tools.py is a module named qc_tools. Anything you can define in that file (functions, classes, constants) becomes available to other code once it imports the module. The sections below follow one research example from a script to a reusable module, then cover what Python prints, where it looks for modules and why a stray file name can break an import.
What a module is used for in research
Analysis code usually starts as one script that cleans data, computes a statistic and draws a figure. Moving the reusable parts into a module lets a notebook, a pipeline step and a colleague’s script all call the same function instead of each keeping a slightly different copy. That single source of the calculation is the practical link to computational reproducibility: if the function changes, it changes everywhere it is imported, and the change can be recorded in one place. A module is also the unit you test; the guide to unit testing shows how a small function in a module is checked on its own.
Python has only one type of module object. Modules written in Python, in C or in anything else are all modules, and an import statement treats them the same way (Python reference, The import system).
Install or access
A module you write yourself needs no installation: save a file with the .py suffix and import it from code that can find it (see the search order below). Python itself comes from the official download at python.org, and its standard library modules (math, statistics, sys and others) are available once Python is installed. Modules from other projects are installed as distribution packages, which is a separate idea explained in the comparison table further down.
Step-by-step: turn a script into a module
The example below uses a small z-score function. The same steps apply to any file you want to reuse.
- Create the module file. Save the following as
qc_tools.py:def zscores(values): mean = sum(values) / len(values) sd = (sum((v - mean) ** 2 for v in values) / (len(values) - 1)) ** 0.5 return [round((v - mean) / sd, 2) for v in values] if __name__ == "__main__": print(zscores([4.1, 5.0, 6.2, 5.5])) - Import it from another file or an interactive session opened in the same directory. There are three common forms, and they differ in what they add to the namespace:
import qc_toolsadds only the module nameqc_toolsto the current namespace, so you callqc_tools.zscores(...).from qc_tools import zscoresimports the function but does not define the nameqc_tools.import qc_tools as qcbinds the module to a shorter name, andfrom qc_tools import zscores as zrenames a single function. This is the pattern behind lines such as import matplotlib.pyplot as plt.
The Python tutorial also describes
from module import *, which imports every name except those beginning with an underscore (unless the module defines__all__). - Run the file as a script with
python qc_tools.py. The code runs with__name__set to"__main__", so the block underif __name__ == "__main__":executes and prints the result. - Import it instead of running it. When another file imports
qc_tools, the guarded block does not run, because the module’s__name__is then"qc_tools". The Python tutorial states it directly: if the module is imported, the code is not run. That guard is what lets one file serve as both a command-line script and a library.
Output and how to read it
Running python qc_tools.py prints the list below. Importing the module prints nothing, because the guarded line is skipped.
[-1.25, -0.23, 1.13, 0.34]
Three built-in checks tell you what Python has loaded:
qc_tools.__name__returns'qc_tools'. The module’s name is available as the global variable__name__.dir(qc_tools)lists every name the module defines. Besides the double-underscore entries Python adds itself, the list ends with'zscores'. With no argument,dir()lists the names you have defined in the current session. It does not list built-in functions and variables; those live in the modulebuiltins.import sys; print(sys.path)shows the list of directories Python searches, in order.
After the first import, Python may also write a compiled copy of the module into a __pycache__ folder next to it, named like qc_tools.cpython-33.pyc (the Python tutorial’s example is __pycache__/spam.cpython-33.pyc). It checks the source file’s modification date against the compiled copy. A program does not run any faster from a .pyc file; the only thing that is faster is how quickly the module loads.
Where Python looks for a module
When you write import qc_tools, the interpreter first checks sys.modules, a cache of every module already imported in this session. If the module is not there, it goes through the finders in sys.meta_path, which by default are three: one for built-in modules, one for frozen modules, and one for the import path, which searches the directories in sys.path. The tutorial gives the order for sys.path:
- The directory containing the input script, or the current directory when no script is given.
- The directories in the
PYTHONPATHenvironment variable. - An installation-dependent default, which includes
site-packageswhere installed packages go.
Programs can modify the list after startup, for example with sys.path.append('/path/to/folder'). Because the script’s directory is placed ahead of the standard library path, a file in your project folder is found before a standard library module with the same name. If nothing matches, Python raises ModuleNotFoundError.
Troubleshooting
ModuleNotFoundError: No module named ‘qc_tools’
Python searched sys.modules, the built-in and frozen finders and every folder in sys.path and found no match. Print sys.path and confirm that the folder holding qc_tools.py is in it. The usual fixes are to run Python from that folder, to add the folder to PYTHONPATH, or to install your code as a package. Also check the spelling: the module name is the file name without .py.
A local file hides a library with the same name
If your project folder contains a file named after a library or standard library module, for example statistics.py or random.py, import statistics loads your file instead. This follows from the search order above: the script’s directory comes first. Rename your file and restart the session.
You edited a module and the old behavior remains
Once a module is in sys.modules, Python reuses it for later imports in the same session. Deleting its entry from sys.modules forces a fresh search on the next import, and restarting the interpreter or kernel does the same. In a notebook, restart the kernel before trusting a re-run result.
Code runs when you only wanted to import
Statements at the top level of a module run on import. Move anything that reads files, prints or fits a model under the if __name__ == "__main__": guard.
Module, package, library and distribution: which word means what
| Term | What it means | Example |
|---|---|---|
| Module | A file containing Python definitions and statements; the file name plus .py is the module name. |
qc_tools.py |
| Package | A module that contains submodules. Dotted names express this: the module name A.B designates a submodule B in a package A. Any module with a __path__ attribute is treated as a package, and a directory normally carries an __init__.py file. |
from lab import qc_tools |
| Import package | What the Python Packaging User Guide calls the thing you import. It is a Python module. | PIL |
| Distribution package | A piece of software that you can install. It can provide an import package whose name differs from its own. | The distribution Pillow provides the import package PIL |
The last two rows explain a common stumble: the name you give to the installer is not always the name you write after import. “Library” is an informal word for a collection of reusable code; the Python documentation uses module and package. Analysis environments that pin installed distributions are covered in the guide to sharing a reproducible conda environment.
Alternatives to a separate module file
A module file is not the only place to keep reusable code. Each option below is built from the same language features.
| Option | When it fits | Limit |
|---|---|---|
| Keep the function in the script | One-off analysis that nobody else will run. | Other files cannot import it without running the whole script, unless it uses the __name__ guard. |
| Single module file | A handful of related functions shared by a few scripts or notebooks in one project folder. | Found only when its folder is on sys.path. |
Package (folder with __init__.py) |
Several related modules, with dotted imports and relative imports such as from . import echo. |
The main module of a program has no package, so it must use absolute imports. |
| Notebook cell | Exploration and teaching. | Not a module: another file imports modules, not cells. Stable functions can be moved into a module and imported back into the notebook. |
For a worked example of reusing analysis code across a project, see the guide to Python for exploratory data analysis.
FAQ
What is a module in Python?
A module is a file containing Python definitions and statements. Its name is the file name without the .py suffix, and importing it makes its functions, classes and variables available to other code.
What is the difference between a module and a package?
A package is a module that can contain other modules. In a dotted name such as A.B, B is a submodule of the package A. A directory is treated as a regular package when it contains an __init__.py file, although namespace packages exist that do not need one.
What is the difference between a module and a library?
“Library” is an everyday word for reusable code and has no formal meaning in the language. A library you install is a distribution package that provides one or more import packages or modules, and the install name can differ from the import name.
What does if __name__ == "__main__": do?
It runs the indented block only when the file is executed directly, for example with python qc_tools.py. When the file is imported, __name__ holds the module name instead, so the block is skipped.
Where does Python look for modules?
It checks sys.modules first, then built-in and frozen modules, then the directories in sys.path: the script’s directory, PYTHONPATH and the installation defaults including site-packages.
Does a .pyc file make my program faster?
No. A program does not run faster from a .pyc file; only the loading of the module is quicker.
Sources
- Python Software Foundation, The Python Tutorial, section 6: Modules (checked 2026-10-29).
- Python Software Foundation, The Python Language Reference: The import system (checked 2026-10-29).
- Python Packaging Authority, Distribution package vs. import package (checked 2026-10-29).








