Creating Python Modules
Learn Python through interactive, bite-sized lessons. Practice with real code challenges and build projects step-by-step.
Start Python Journey →Python modules are essential for organizing and reusing code. They allow developers to break down complex programs into manageable, reusable components.
What is a Python Module?
A module is a file containing Python definitions and statements. It can define functions, classes, and variables that can be used in other Python programs.
Creating a Module
To create a module, simply write Python code in a file with a .py extension. For example:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
PI = 3.14159
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return PI * self.radius ** 2
Using a Module
To use a module in another Python script, use the import statement. There are several ways to import modules:
1. Importing the entire module
import mymodule
print(mymodule.greet("Alice"))
circle = mymodule.Circle(5)
print(circle.area())
2. Importing specific items
from mymodule import greet, PI
print(greet("Bob"))
print(PI)
Best Practices
- Use meaningful names for your modules.
- Keep modules focused on a specific functionality.
- Include docstrings to document your module and its contents.
- Use relative imports for modules within the same package.
- Avoid circular imports between modules.
Module Search Path
Python searches for modules in the following locations:
- The current directory
- Directories listed in the PYTHONPATH environment variable
- Standard library directories
- Site-packages directories for third-party packages
You can view the module search path using the sys.path list from the Python sys Module.
Module vs. Script
When a Python file is run directly, its __name__ variable is set to '__main__'. This allows you to include code that runs only when the file is executed as a script, not when it's imported as a module:
# mymodule.py
def some_function():
pass
if __name__ == '__main__':
print("This runs only when executed directly")
some_function()
Related Concepts
To further enhance your understanding of Python modules, explore these related topics:
- Importing Python Modules
- Python Built-in Modules
- Creating Python Packages
- Python Package Management (pip)
By mastering module creation and usage, you'll be able to write more organized, maintainable, and reusable Python code.