Python Modules and Packages
A module lets you write a set of functions and variables once, in a single file, and then reuse them across multiple programs without duplication.
Try it: What import Really Does
What happens on import: Python checks sys.modules, searches sys.path in order (first match wins), creates the module object, runs its top level once, then binds a name — the module, one function, or an alias — in the importing namespace; plus packages, __name__ == "__main__", ModuleNotFoundError and ImportError.
How it works
- If the name is already in sys.modules, reuse that module object: its code does not run again.
- Otherwise search each sys.path entry in order (the script's folder first); the first match wins, none raises ModuleNotFoundError.
- Create an empty module object, store it in sys.modules, then run the file's top level once (its __name__ is the module name, so a __main__ guard is skipped).
- import m binds m to the module; import m as x binds x; from m import f binds only f (ImportError if m has no f).
- A package runs its __init__.py first; submodules are found on the package's __path__ and become attributes of the package.
Default run (19 steps): $ python main.py — sys.path starts as [/project, /venv/site-packages, /usr/lib/python3.12]: the script's folder, then site-packages, then the standard library. Only our own modules are shown in sys.modules below. … Done. Printed: helpers loaded, __name__ = helpers | Hi Ann | Hi Ann.
Simplified: A fixed virtual project (main.py, helpers.py, pkg/, a site-packages folder and a one-file stand-in for the standard library). Built-in and frozen modules, .pyc caching, relative imports and namespace packages are not modelled; only our own modules are listed in sys.modules.
Loading the simulation…
The Problem: Code Duplication Across Programs
Imagine you write a function to calculate the area of a circle. It works perfectly in your first program. Now you need that same function in a second program, and a third, and a tenth. You could copy and paste the function into every new file, but that creates a maintenance nightmare: if you find a bug in the function, you have to fix it in ten places. If you want to improve the function, you update ten copies. This is the problem modules solve.
A module lets you write a set of functions and variables once, in a single file, and then reuse them across multiple programs without duplication.
What Is a Module?
A module is simply a .py file containing functions, variables, or classes that you want to reuse. There is nothing special about the file itself—it is just Python code organized in a way that makes it easy to import into other programs. When you create a module, you are creating a reusable library of code.
Module: A .py file containing functions, variables, or classes designed to be imported and reused by other Python programs.
The simplest real way to create a module is to write a regular file with a .py extension containing the functions and variables to be reused. You do not need to do anything special—no decorators, no special syntax, no registration step. Just write your code in a .py file, and it becomes a module that other programs can import.
Creating Your First Module
Let us create a concrete example. Suppose you have a file called math_tools.py in your project directory. Inside it, you write two functions that you know you will use in multiple programs.
That is it. math_tools.py is now a module. It contains two functions and two variables, all available for other programs to import and use.
Importing and Using a Module
Now imagine you have a second program in the same directory called my_program.py. You want to use the functions from math_tools.py without rewriting them. You import the module using the import statement.
Circle area: 78.53975
Rectangle area: 40
PI value: 3.14159When you write import math_tools, Python looks for a file called math_tools.py in the same directory (or in the Python path). It loads the file and makes all its functions and variables available through the module name. You access them using dot notation: module_name.function_name() or module_name.variable_name.
How Code Reuse Actually Works
When you import a module into a program, Python does not copy the code into your program. Instead, it creates a connection to the module file. The functions and variables live in one place—the module file—and multiple programs can access them. This is the key benefit: you maintain the code in one location, and all programs that import it automatically use the updated version.
This design means that if you fix a bug in circle_area() inside math_tools.py, all three programs automatically benefit from the fix the next time they run. You do not have to update the function in three separate places.
Modules vs. Packages
As your code grows, you may end up with many modules. A package is a way to organize multiple modules into a directory structure. While a module is a single .py file, a package is a directory containing multiple .py files and a special file called __init__.py.
Package: A directory containing multiple .py module files and an __init__.py file, used to organize related modules into a namespace.
For example, if you have multiple related modules like math_tools.py and string_tools.py, you might organize them into a package called utilities. Inside the utilities directory, you would place both modules and an __init__.py file. Then other programs can import from the package using syntax like: from utilities import math_tools or from utilities.math_tools import circle_area.
The Python Standard Library
One program can import another module to make use of its functionality. This is exactly how the Python Standard Library itself is used from ordinary programs. The Standard Library is a collection of pre-built modules that come with Python, covering everything from file I/O to mathematics to web requests. You have already used it whenever you wrote import math or import random.
The Python Standard Library is a collection of pre-written modules that ship with Python. You access them the same way you access your own modules: with the import statement.
When you write import math, Python finds the math module (which is part of the Standard Library) and loads it. The math module contains functions like sqrt(), sin(), and cos() that are already written and tested. You do not have to write them yourself. This is the power of modules and packages: they let you stand on the shoulders of giants, reusing code that others have written.
Common Mistakes When Creating and Using Modules
Common mistake Forgetting that the module file must be in the same directory as the program that imports it (or in the Python path)
What it looks likeYou create math_tools.py in a subfolder called tools/, but your program is in the main directory and tries to import math_tools. Python cannot find it.
Why it failsPython searches for modules in specific locations. If the module is not in the same directory or in a directory listed in the Python path, the import fails.
Do this insteadEither place the module in the same directory as your program, or add the module's directory to the Python path using sys.path.append().
Common mistake Using the wrong import syntax and then trying to call functions without the module name
What it looks likeYou write import math_tools, but then call circle_area(5) instead of math_tools.circle_area(5).
Why it failsWhen you use import
module_name, the functions are not added to your program's namespace directly. You must use the module name as a prefix.Do this insteadEither use import math_tools and call math_tools.circle_area(5), or use from math_tools import circle_area and then call circle_area(5) directly.
Common mistake Editing a module file and expecting the changes to appear in a running program without restarting
What it looks likeYou fix a bug in math_tools.py, but the program that imported it is still running and uses the old version.
Why it failsPython loads a module into memory when it is first imported. Changes to the file are not automatically reloaded during execution.
Do this insteadRestart the program to reload the updated module.
Common mistake Creating a package directory without an __init__.py file
What it looks likeYou create a directory called utilities with math_tools.py inside, but forget to create __init__.py.
Why it failsPython uses
__init__.pyto recognize a directory as a package. Without it, Python treats the directory as a regular folder, not a package.Do this insteadCreate an empty __init__.py file in the package directory.
Modules Written in Other Languages
While the simplest way to create a module is to write a .py file, modules can also be written in a different underlying language that the Python interpreter itself is written in, such as C. These compiled modules offer performance benefits for computationally intensive tasks. However, for most learning purposes and typical use cases, Python modules are sufficient and much easier to create and maintain.
Most modules you will create and use are written in Python. Some advanced modules in the Standard Library are written in C for speed, but you import them the same way.
Practice: Create and Import Your Own Module
Create a module called greetings.py that contains two functions: one that returns a greeting in English and one that returns a greeting in Spanish. Then create a second program that imports the greetings module and calls both functions, printing the results.
Hints
- Your
greetings.pyfile should contain two simple functions, each returning a string. - In your second program, use import greetings to load the module.
- Call the functions using
greetings.function_name(). - Make sure both files are in the same directory.
Summary
- 1A module is a .py file containing functions, variables, or classes designed to be reused across multiple programs.
- 2The simplest way to create a module is to write a regular Python file with the code you want to reuse.
- 3You import a module using the import statement, which makes its functions and variables available through dot notation (
module_name.function_name). - 4Multiple programs can import the same module, ensuring that code is maintained in one place and all programs benefit from updates and bug fixes.
- 5A package is a directory containing multiple modules and an
__init__.pyfile, used to organize related modules into a namespace. - 6The Python Standard Library is a collection of pre-built modules that come with Python and are imported the same way as your own modules.
At a glance
- Modules solve the code-duplication problem by letting you write functions and variables once and reuse them across multiple programs.
- A module is simply a .py file; there is nothing special about its creation—just write your code and save it with a .py extension.
- Import a module using the import statement, then access its functions and variables using dot notation.
- A package is a directory of related modules, organized with an
__init__.pyfile. - The Python Standard Library is a collection of pre-built modules that you access the same way as your own modules.