- Create your own Python modules
- Understand the __name__ == '__main__' pattern
- Organize code across multiple files
- Use module docstrings and documentation
Creating Modules
You've used modules made by others. Now it's time to create your own! Creating modules helps you organize code, avoid repetition, and share functionality across projects.
The great news: creating a module is incredibly simple – just create a Python file!
Creating Your First Module
Any .py file is a module! Create greetings.py:
# greetings.py
"""Module for greeting functions."""
def say_hello(name):
"""Return a hello greeting."""
return f"Hello, {name}!"
def say_goodbye(name):
"""Return a goodbye message."""
return f"Goodbye, {name}!"
# Constants
DEFAULT_NAME = "World"
Now use it in another file:
# main.py
import greetings
print(greetings.say_hello("Alice"))
print(greetings.DEFAULT_NAME)
The name == 'main' Pattern
This pattern lets a file work both as a module AND as a standalone script:
# calculator.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
# This only runs when executed directly
if __name__ == "__main__":
# Test code
print(f"2 + 3 = {add(2, 3)}")
print(f"2 × 3 = {multiply(2, 3)}")
How __name__ Works
When you RUN the file directly:
$ python calculator.py
__name__ = "__main__" → Test code RUNS
When you IMPORT the file:
import calculator
__name__ = "calculator" → Test code SKIPPED
This lets you include tests/demos that don't run on import!
Module Best Practices
# utils.py
"""
Utility functions for data processing.
This module provides helper functions for common
data manipulation tasks.
"""
__all__ = ['process_data', 'clean_text'] # Public API
# Public functions
def process_data(data):
"""Process and return cleaned data."""
return _validate(data)
def clean_text(text):
"""Remove extra whitespace from text."""
return ' '.join(text.split())
# Private function (starts with _)
def _validate(data):
"""Internal validation - not exported."""
return data if data else []
# Module-level code
_cache = {} # Private module variable
Key Takeaways
Remember These Points
Any .py file is automatically a module
if __name__ == "__main__":
Code here only runs when file executed directly
Add docstrings for documentation
_underscore names are "private" (convention)
__all__ controls what 'import *' exports
