Python modules and packages: organise larger programs

A module is a Python file that holds code you can reuse, and a package is a folder that holds related modules together. Instead of keeping every function in one long file, you put each job in its own module, then import the parts you need into the main program. The main program stays short, and each module can be read, tested, and changed on its own.
This matters as soon as a program grows past one screen of code. In a single file, a change to one part means scrolling past unrelated parts, and a name used in one place can clash with a name used somewhere else. Modules give each part its own space, and imports make it clear where each function comes from. The official Python tutorial describes a module as a file holding definitions and statements, and a package as a way of structuring modules with dotted names.
Use a module that already exists
Python ships with a standard library, which is a set of modules for common jobs. The math module, for example, holds functions for numbers, and the random module holds functions for random choices. You do not need to install anything to use them. You import the module, then call a function from it with a dot.
import math
import random
print(math.sqrt(16))
print(random.choice(["red", "green", "blue"]))
The first program prints 4.0, because the square root of 16 is 4. The second prints one colour from the list, chosen at random, so the output changes from run to run. The import line tells the reader where sqrt and choice come from, which is clearer than a bare function name that could come from anywhere. If you only need one function, you can import that name directly, as shown below. That form is shorter, but it hides the source, so use it for names that are already clear in context.
from math import sqrt
print(sqrt(25))
Write your own module
Writing a module is simpler than it sounds. Create a new file in the same folder as your main program, give it a clear name that ends in .py, and put functions in it. Suppose you are building a small shop program, and you need to work out prices with tax. Put the price functions in a file called prices.py, and keep the main program in main.py.
# prices.py
def with_tax(price, rate):
return price + price * rate
def without_tax(total, rate):
return total / (1 + rate)
Now the main program can import prices and call its functions. The call prices.with_tax(100, 0.2) returns 120.0, because 20 percent of 100 is 20, and 100 plus 20 is 120. The main program does not need to know how the tax is worked out. It only needs the module name and the function name, and the details stay in prices.py where they can be changed in one place.
# main.py
import prices
total = prices.with_tax(100, 0.2)
print(total)
One more pattern is worth learning early. Code in a module file runs when the file is imported, so a test print left at the bottom of prices.py would run every time main.py imports it. To stop that, put demo code inside a guard that only runs when the file is run directly, as shown below. When prices.py is imported, the guard is false and the demo does not run. When prices.py is run on its own, the guard is true and the demo runs, which is useful for a quick check.
# prices.py, demo block at the bottom
if __name__ == "__main__":
print(with_tax(100, 0.2))
From modules to packages
A package groups modules that belong together. In a shop program, you might have one module for prices, one for stock, and one for orders. Keeping them in a folder called shop, with the main program outside that folder, makes the structure clear. You then import with a dotted name, such as import shop.prices, which reads as the prices module inside the shop package.
| Form | What it means | When to use it |
|---|---|---|
| import prices | Import a module in the same folder | Small programs with a few files |
| from prices import with_tax | Import one name from a module | When one function is used often and its source is clear |
| import shop.prices | Import a module inside a package folder | Larger programs with grouped modules |
| from shop.prices import with_tax | Import one name from a package module | When the full dotted path would clutter every call |
Common mistakes to watch for
Naming your own file after a standard library module is a common trap. If you save a file called math.py or random.py in your project folder, Python may import your file instead of the standard module, and calls that worked before will start failing in strange ways. Use a distinct name for your own files, such as my_math.py or shop_math.py, and the problem goes away. If an import that used to work suddenly breaks after you add a file, check the new file name first.
Circular imports are another trap. They happen when module A imports module B, and module B imports module A. Python cannot finish either import, because each one waits for the other. The fix is usually to move the shared code into a third module that both A and B import, so neither one depends on the other. If you find two modules that need each other, that shared part is often a new module waiting to be made.
A third mistake is importing inside a function when the import belongs at the top of the file. Imports at the top make dependencies visible at a glance, and they run once when the module loads. An import hidden inside a function still works, but a reader has to find it to know the module depends on it. Keep imports at the top, except for the rare case where an import would create a circular import and moving it is the only simple fix.
Limits of this guide
Modules and packages organise code, but they do not fix a program whose logic is wrong. Splitting a broken function into its own file leaves the same broken function, only in a different place. Fix the logic first, in one file if needed, and split the code once the logic is clear. Splitting too early can also hurt, because it forces a reader to jump between files to follow a simple idea.
This guide also does not cover installing third party packages, virtual environments, or publishing a package for others to use. Those steps build on the ideas here, but they need their own setup and their own checks. The files guide is a useful companion, because modules are files, and the first program guide shows the run command that modules depend on. Start with files in one folder, then add a package folder only when the program has clear groups of modules.
Worked example: split a small program into two modules
A program that grows past one file is easier to manage when each file holds one job. The example below splits a greeting program into a helpers module and a main file. The helpers module holds a greeting function, and the main file imports that function and uses it. Each file can then be read and tested on its own, which is the main benefit of splitting code.
# File: helpers.py
def greet(name):
return "Hello, " + name
# File: main.py
from helpers import greet
print(greet("Maya"))
Run main.py from the folder holding both files, and the output should be the greeting. The import line tells Python to load helpers.py, find the greet function inside it, and make that function available under its name in main.py. If the files sit in different folders, the import will fail, because Python looks in the folder of the running program and in its standard locations, rather than searching the whole computer.
Try adding a second function to helpers.py, such as a farewell function, and import it in main.py as well. That small change shows the pattern in action. The helpers file grows by one function, the main file grows by one import name, and the main flow stays short. That separation is what lets a program grow without its main file becoming a long list of unrelated functions.
Import forms in a table
Python offers several import forms, and each one suits a different situation. The table below lists the common forms, with a plain description of what each one brings into the current file. The choice affects how long the names are in the code, and how clear it is where each name came from.
| Form | What it brings in | When it suits |
|---|---|---|
| import helpers | The module, under its name | When the module name clarifies the call |
| from helpers import greet | One name from the module | When one function is used often |
| import helpers as h | The module, under a short name | When the module name is long |
| from helpers import * | Many names, without showing them | Rarely, because the source of each name is hidden |
The star import form is the one to avoid in most code, because it brings in names without listing them, so a reader cannot tell where a name came from without opening the module. It can also clash with names already in the file, quietly replacing a function or value. Listing the imported names explicitly costs a few extra words, and it makes the code far easier to follow.
Aliasing a module with as is useful when a module name is long, yet the alias should still hint at the original name. A short alias that gives no hint, such as a single letter for a module used in many places, saves typing while costing clarity. A clear alias, such as importing a statistics helper as stats, keeps the call readable without repeating a long module name each time.
Packages, and the __init__ file in plain terms
A package is a folder of modules, with a special file that marks the folder as a package. That file is named __init__.py, and it can be empty, or it can hold setup code that runs when the package is imported. The folder name becomes the package name, and modules inside it are imported with a dotted path, such as from shop.helpers import greet, where shop is the folder and helpers is the module inside it.
# Folder layout, as text:
# shop/__init__.py
# shop/helpers.py
# main.py
# In main.py:
from shop.helpers import greet
The __init__ file also controls what a package offers at its top level. A package can import selected names in its __init__ file, so users of the package can import them from the package name directly, rather than from a module inside it. That convenience is worth adding once the package has a stable shape, yet it is not needed for a first package, where importing from the module directly is clear enough.
Relative imports, which start with a dot, refer to modules in the same package, and they appear in larger projects where a module must import a neighbour without naming the whole package path. Beginner code usually uses absolute imports, which name the full path from the top, because absolute imports are easier to read and to move. Relative imports become useful when a package is renamed, because they keep working without editing every import line.
Troubleshooting import errors step by step
An import error usually means Python could not find the module, or it found the module yet could not find the named item inside it. The first check is the folder. Confirm the module file sits in the same folder as the running program, or in a folder on the search path, and confirm the file name spelling, including capital letters, matches the import exactly.
The second check is the name inside the module. A ModuleNotFoundError points at the module itself, while an ImportError for a name points at the item inside a module that was found. That distinction narrows the search. A missing module is a folder or spelling problem, while a missing name is a spelling problem inside the module, or a function that was renamed without updating the import.
The third check is circular imports, where two modules import each other. When module A imports module B, and module B imports module A, each one needs the other to finish loading first, which can leave a name undefined at the moment it is used. The fix is usually to move the shared part into a third module that both can import, which breaks the circle and gives the shared code a clear home.
Frequently asked questions
Why does importing a module run code at the top level of that file?
Python runs the module file once when it is first imported, so top level statements in that file run at import time. That is why function definitions are safe at the top level, while a call that prints or reads a file will also run on import. The guard in this guide stops a demo block from running when the file is imported.
How do I share code between two folders in one project?
Put the shared code in a module inside a package, and run the program from the project folder so Python can find that package. If the program is run from a different folder, Python may not find the module, and the import will fail. Keeping one clear project folder and running from it avoids most of these errors.
When should I split a file into modules?
Split when one file holds two jobs that change for different reasons, such as reading data and printing a report. If you have to scroll past unrelated code to find the part you need to change, that part is a candidate for its own module. Do not split a short file that does one job well.
What is the difference between a module and a package?
A module is a single file of Python code, while a package is a folder of modules marked by an __init__.py file. A module is imported by its file name, while a module inside a package is imported with a dotted path that starts with the folder name.
How do I stop a module's test code from running on import?
Guard the test code with a check that the file is being run directly, rather than imported. Code under that guard runs when the file is run as a program, and it is skipped when another file imports the module.
When should I avoid a star import?
Avoid it in most code, because it brings in names without listing them, so a reader cannot tell where each name came from. List the imported names explicitly, which makes the code easier to follow and avoids silent clashes.


