What are Python Modules?
A module is simply a
.py file containing Python code — such as variables, functions, and classes. Modules allow you to organize your code into logically related pieces.python
Importing Modules
Use the
import keyword to bring code from another file into your current script.python
Using __name__ == "__main__"
Python executes all code in a module when it's imported. To prevent certain code from running during an import (like tests or a main script), wrap it in a special
if block.python
Python Packages: Code Organizations
A package is a collection of modules organized in a directory. Any directory containing an
__init__.py file is treated as a Python package.text
python
__init__.py: Package Initialization
This file is executed when the package is imported. It can be empty, or used to:
- Control exports: Expose sub-modules for easier access.
- Initialize global state: Setup needed whenever the package is used.
python
Relative vs Absolute Imports
- Absolute:
from my_project.utils import helper(Always starts from project root). - Relative:
from . import helperorfrom ..auth import login. (Uses dots.to represent parent or sibling directories).
Best Practice: Use absolute imports whenever possible. They are clearer and less prone to breaking if you move your scripts.
Finding Modules: The sys.path
When you
import something, Python looks for it in these locations (in order):- Current Directory (where the script is running).
- PYTHONPATH: Environment variable with additional paths.
- Standard Library: Built-in modules like
os,sys,math. - Site-Packages: Third-party libraries installed with
pip.
python
External Packages with pip
The Python Package Index (PyPI) hosts hundreds of thousands of open-source libraries.
- Install:
pip install requests - Install specific version:
pip install Flask==2.0.1 - Freeze requirements:
pip freeze > requirements.txt(Save your project's dependencies!)
Summary
| Term | Description |
|---|---|
| Module | A single .py file |
| Package | A folder of modules + __init__.py |
| Standard Library | Built-in modules (os, sys, json) |
| PyPI | Online repository of Python packages |
| Pip | Command-line tool to install packages |
| Relative Import | Import using . (sibling) or .. (parent) |
| PYTHONPATH | Environment variable for search paths |