Learning how to write modules in Python 3 is one of the most important and practical skills for building clean, reusable, and scalable Python code — modules are simply .py files containing functions, classes, variables, and executable code that you can import and reuse across multiple scripts, turning small scripts into organised, professional applications and libraries.
In this up-to-date 2025–2026 guide, you’ll master exactly how to write modules in Python 3: creating simple modules, using __name__ == “__main__”, defining functions/classes/variables, organising packages, best practices, import patterns, and common pitfalls. All examples are tested on Python 3.10–3.13.
Key Takeaways – How to Write Modules in Python 3
- Write modules in Python 3 by creating .py files with reusable definitions (functions, classes, variables).
- Use __name__ == “__main__” to run code only when the module is executed directly (not when imported).
- Modules can contain executable code — executed once on first import.
- Organise related modules into packages (directories with __init__.py or implicit namespace packages).
- Prefer explicit imports (import my_module) over wildcards (from my_module import *).
- Follow PEP 8: snake_case names, docstrings, clear module purpose.
- Modules enable code reuse, maintainability, testing, and collaboration — foundation of libraries and large projects.
Prerequisites
- Python 3.8+ installed
- Basic Python knowledge (functions, classes, import)
- Text editor or IDE (VS Code recommended)
1. Creating Your First Module in Python 3
A module is just a .py file. Let’s create hello.py:
# hello.py
def world():
"""Print a friendly greeting."""
print("Hello, World!")
shark = "Sammy"
class Octopus:
def __init__(self, name, color):
self.name = name
self.color = color
def tell_me_about_the_octopus(self):
print(f"This octopus is {self.color}.")
print(f"{self.name} is the octopus's name.")
Now create main_program.py in the same directory:
# main_program.py
import hello
hello.world() # Hello, World!
print(hello.shark) # Sammy
jesse = hello.Octopus("Jesse", "orange")
jesse.tell_me_about_the_octopus()
# This octopus is orange.
# Jesse is the octopus's name.
Run:
python main_program.py
You just wrote modules in Python 3 and imported them!
2. Using name == “main” – Run Code Only When Executed Directly
Modules often have test/demo code that should run only when the file is run directly (not imported):
# hello.py (updated)
def world():
print("Hello, World!")
shark = "Sammy"
if __name__ == "__main__":
# This block runs only when you do: python hello.py
print("This is the hello module running directly!")
world()
print(f"Shark name: {shark}")
Now:
- python hello.py → runs the test code
- import hello in another file → no test code runs
This is the best practice when writing modules in Python 3.
3. Writing Packages – Multiple Modules Organised Together
A package is a directory containing modules and an __init__.py file (can be empty in modern Python).
Directory structure:
aquarium/creatures.py:
def list_fish():
return ["shark", "eel", "octopus"]
main.py:
from aquarium import creatures
print(creatures.list_fish()) # ['shark', 'eel', 'octopus']
You just wrote modules in Python 3 organised as a package!
4. Best Practices When Writing Modules in Python 3 (2025–2026)
- Use descriptive module names: data_processing.py > dp.py
- Include docstrings (PEP 257) at module and function level
- Define __all__ to control wildcard imports (rarely needed):
__all__ = ['world', 'Octopus'] # only these are imported with *
- Follow PEP 8: imports at top, snake_case, 79-char lines
- Use type hints:
def greet(name: str) -> str:
return f"Hello, {name}!"
- Avoid top-level executable code — put in if __name__ == “__main__”:
- Group related functions/classes in one module
- Write tests in a separate tests/ directory
How to Write Modules in Python 3 – FAQ (2025–2026)
- How do I write modules in Python 3?
Create a .py file with functions/classes/variables — simplest way to write modules in Python 3. - What does if name == “main” do in Python 3?
Runs code only when the file is executed directly, not when imported — essential when writing modules in Python 3. - How do I organise multiple modules in Python 3?
Put them in a directory with __init__.py → becomes a package. - Can modules in Python 3 have executable code?
Yes — runs once on import, but put tests/demo in __main__ block. - What’s the difference between module and package in Python 3?
Module = single .py file; Package = directory of modules with __init__.py.
Summary
You now know exactly how to write modules in Python 3: creating .py files, defining reusable code, using __name__ == “__main__”, organising packages, best practices, and modern conventions.
Mastering how to write modules in Python 3 transforms small scripts into structured, reusable libraries — the foundation of clean, maintainable, and collaborative Python projects.
Recommended Next Tutorials
- How to Import Modules in Python 3 (Advanced Patterns)
- Python Packages & Project Structure (2025–2026)
- Writing Python Libraries & Publishing to PyPI
- Python __init__.py & Namespace Packages
- Build a Reusable Utility Module Project