9.1 Modules and Packages
Understanding how to organize code into reusable modules (.py files) and the structure of packages (folders).
As your Python programs grow, managing all the code in a single file becomes impractical, difficult to maintain, and limits reusability. Modules and packages are Python's fundamental mechanisms for organizing, structuring, and reusing code in logical, manageable pieces.
What is a Module?
In its simplest form, a module is just a Python file with the `.py` extension. This file can contain executable code, function definitions, classes, and variables. By grouping related code into a module, you create a self-contained, reusable piece of logic. For example, you could have a `math_helpers.py` module containing various helper mathematical functions.
What is a Package?
When a project grows even larger, you may need to group related modules together. A package is a folder that contains multiple modules or even other sub-packages. For Python to consider a folder a package, it must contain a special file named `__init__.py`. This file can be empty, but its existence is what signals that the folder is a Python package. It can also contain initialization code for the package.
The if __name__ == "__main__" condition
This condition is one of the most powerful and frequently used idioms in Python. Every module in Python has a special built-in variable called `__name__`. When you run a Python file directly from the command line, Python sets the value of `__name__` for that file to `"__main__"`. Conversely, when the file is imported as a module into another file, the value of `__name__` is the name of the module file. This allows us to write code that will only be executed when the file is run as the main program, and not when it is imported. It is the ideal place to put test code or usage examples for your module.
# Example: my_module.py
# def my_function():
# return "This is my function."
#
# if __name__ == "__main__":
# # This code runs only if we execute my_module.py directly.
# print("Running my_module.py as the main program.")
# print(my_function())
# Example: main.py
# import my_module
# # When main.py is executed, the code in the if __name__... block above will not run.
# print("Running main.py")
# print(my_module.my_function())
# Note: The live editor does not support multiple files.
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.