Skip to main content
v2026.11,858 entries · CC-BY 4.0

What Is a Module in Python? Imports, sys.path and Examples

A Python module is a .py file you can import. See how to turn a research script into one, how imports are found on sys.path, and how to fix import errors.

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.

  1. 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]))
  2. 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_tools adds only the module name qc_tools to the current namespace, so you call qc_tools.zscores(...).
    • from qc_tools import zscores imports the function but does not define the name qc_tools.
    • import qc_tools as qc binds the module to a shorter name, and from qc_tools import zscores as z renames 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__).

  3. Run the file as a script with python qc_tools.py. The code runs with __name__ set to "__main__", so the block under if __name__ == "__main__": executes and prints the result.
  4. 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 module builtins.
  • 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:

  1. The directory containing the input script, or the current directory when no script is given.
  2. The directories in the PYTHONPATH environment variable.
  3. An installation-dependent default, which includes site-packages where 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

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about What Is a Module in Python? Imports, sys.path and Examples

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →

Ask CASRAI · Regulatory Radar

Research-admin question? Get an answer that links its sources.

An AI assistant specialized in research administration. Every answer links its sources to check before you act. 2 questions free, no account. $29/month after.

  • Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.
  • Every answer numbers its sources and links each one, so you can check the source yourself.