Python Modules and Packages: How to Organize Your Code
A short Python script can fit in one file. As a project grows, that file can become difficult to read, reuse, and maintain. Python modules and packages give you a practical way to split related code into clear pieces—and bring those pieces together with imports.
This guide walks through modules, packages, __init__.py, import styles, the standard library, third-party packages, and project organization with examples you can adapt.
What Is a Python Module?
A module is a Python file. A file ending in .py can hold functions, classes, variables, and code. Importing a module makes its names available to another file; Python also runs the module's top-level code the first time it is imported in a process.
Make a small module
Save a few related calculator operations in calculator.py:
# calculator.py
PI = 3.14159
def add(a, b):
return a + b
def subtract(a, b):
return a - bUse that module from another file
Keep your program's starting point in main.py and call the module's functions with dot notation:
# main.py
import calculator
print(calculator.add(5, 3)) # 8
print(calculator.subtract(10, 4)) # 6
print(calculator.PI) # 3.14159The import calculator statement makes the module available under the name calculator. Its functions and values are then accessed with a dot, such as calculator.add(). This keeps it clear where each name came from.
How Python Imports Work
Python includes several import forms. Choose one that keeps the source of each name clear.
Import a whole module
import math
print(math.sqrt(16)) # 4.0Use the module prefix when you call its contents.
Use an alias
import numpy as np
values = np.array([1, 2, 3])An alias is a shorter name for an imported module. Use familiar aliases when a library has one.
Import selected names
from math import sqrt, pi
print(sqrt(25))
print(pi)This makes selected names available directly. Avoid from math import * in most project code: it can fill the current namespace and make it harder to see where a value came from.
What Is a Python Package?
A package groups related modules in a directory. For example, a small utilities package could keep string helpers and number helpers apart while making them easy to import.
my_project/
├── main.py
└── utilities/
├── __init__.py
├── strings.py
└── numbers.pyIn a regular package, __init__.py marks the directory as a package. Modern Python can also support namespace packages without that file, but including it is a clear choice for a regular project.
Import modules from a package
# main.py
from utilities import strings, numbers
print(strings.clean_text(" Hello "))
print(numbers.double(5))Packages are useful when an application has clear areas of responsibility. A data project, for instance, might group data loading, cleanup, and model preparation into separate modules.
What Belongs in __init__.py?
Python runs a package's __init__.py when the package is imported. It can be empty, or expose a small, convenient public interface:
# utilities/__init__.py
from .strings import clean_text
from .numbers import doubleKeep initialization lightweight. Avoid slow work, network calls, or complex application logic there, because imports should stay predictable and quick.
Absolute and Relative Imports
Imports between package files can use an absolute path from the project or a relative path from the current package.
Absolute import
from utilities.strings import clean_textThis spells out the package path and is often easiest for a new reader to follow.
Relative import
from .strings import clean_text
from ..shared import settingsA single dot refers to the current package; two dots refer to its parent. Relative imports can be concise within related modules. Use one consistent style and avoid mixing styles without a reason.
Python's Standard Library
The standard library is a collection of modules that comes with Python, so you can use many common tools without installing anything.
osandpathlibhelp work with files and paths.sysexposes interpreter and system information.datetimehandles dates and times.jsonreads and writes JSON data.mathprovides common mathematical functions.randomgenerates pseudo-random values.reworks with regular expressions.collectionsprovides specialized container types.
Example: format the current time
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))Knowing what the standard library offers can save you from installing a dependency or rebuilding a tool that Python already provides.
Install Third-Party Packages with pip
When Python's built-in tools are not enough, third-party libraries can add features for web requests, data analysis, machine learning, and more. The Python Package Index (PyPI) is a major source for these packages. Use Python's module form of pip so the installer matches the interpreter you are using:
python -m pip install requestsInstall project dependencies inside a virtual environment instead of globally. A virtual environment keeps one project's packages separate from other projects and from the system Python installation.
# Create a virtual environment
python -m venv .venv
# Activate it on macOS or Linux
source .venv/bin/activate
# On Windows PowerShell, use:
# .venv\Scripts\Activate.ps1
python -m pip install requestsActivate the environment before installing or running dependencies. When finished, leave it with deactivate. Record project dependencies in a requirements file so others can recreate the environment.
The if __name__ == "__main__" Pattern
A Python file can be run directly or imported by another file. Python sets its special __name__value to "__main__" when it is the program being run. A guard lets you keep a runnable entry point without running it just because another module imports your functions.
# calculator.py
def add(a, b):
return a + b
def main():
print("Running as a script")
print(add(2, 3))
if __name__ == "__main__":
main()Running python calculator.py calls main(). Importing calculator from another file defines the functions but skips the guarded block.
Common Module and Package Mistakes
- Shadowing a standard module: avoid filenames such as
random.pyorjson.py, which can hide the standard-library module with the same name. - Creating circular imports: move shared code into a third module or redesign the dependency direction when two modules rely on each other.
- Using wildcard imports:
from module import *hides the origin of names and can cause collisions. - Installing everything globally: separate environments help prevent package-version conflicts between projects.
- Putting too much code in
__init__.py: keep package startup clear and light. - Using vague filenames:
data_cleaning.pytells readers more thanutils.py.
Best Practices for Organizing Python Code
- Give each module a clear purpose and use descriptive filenames.
- Group related functions and classes rather than splitting every function into its own file.
- Keep package initialization small and avoid side effects during imports.
- Prefer imports that make the source of names easy to recognize.
- Use a virtual environment for each project and document its dependencies.
- Add a short module docstring that explains what the file is responsible for.
- Keep a consistent folder layout so teammates can find code quickly.
How Real Python Projects Use Packages
- Web development: Django apps can separate models, views, and URLs.
- Data science: loading, preprocessing, and modeling can live in focused modules.
- Automation: file handling, API requests, and logging can be reused across scripts.
- Machine learning: libraries such as scikit-learn organize algorithms into subpackages.
Python Modules and Packages Interview Questions
Practise answering these in your own words, with a small example for each:
- What is the difference between a module and a package?
- What is
__init__.pyused for? - How do absolute imports differ from relative imports?
- What does
if __name__ == "__main__"do? - How can you reduce the chance of circular imports?
- What is included in Python's standard library?
A concise explanation is often best: a module is one Python file, while a package groups modules in a directory. Then describe a project example that shows how you would organize related code.
Frequently Asked Questions
What are modules and packages in Python?
A module is a Python file that can contain functions, classes, and values. A package groups related modules in a directory.
How do I create a Python module?
Create a .py file, add your code, and import that file by its module name from another Python file.
What is the purpose of __init__.py?
In a regular package, it marks the directory as a package and can expose a small public interface. Keep code in it lightweight.
How are absolute and relative imports different?
Absolute imports name the path from the project package, while relative imports use dots to refer to the current or parent package.
How do I install a Python package?
Use python -m pip install package_name, preferably after activating the virtual environment for your project.
What is the Python standard library?
It is the collection of modules included with Python, such as datetime, json, math, and pathlib.
What causes common Python import problems?
Frequent causes include naming a file after a standard module, circular imports, wildcard imports, and missing project dependencies.
Conclusion
Modules and packages help Python projects grow without turning into one difficult-to-navigate file. Start by grouping related code, use imports that make dependencies clear, and keep each package's purpose easy to understand. Add a virtual environment as soon as your project needs external libraries.
You do not need to wait for a project to become large before organizing it. A few thoughtfully named modules can make code easier to reuse, test, and share with teammates.
Build Your Next Python Project with Confidence
Explore the Python course in Viman Nagar, Pune, for structured lessons, hands-on projects, and mentor guidance—from core programming concepts to practical project organization.
Continue learning: Browse all free Python guides →
