Modules & Packages
Real-world Python projects aren’t single files. They are split across multiple files (modules) and directories (packages). Understanding how to organize code and manage dependencies is crucial.1. Modules
A Module is simply a Python file (.py). Any Python file can be imported by another.
Importing
You can import the whole module or specific parts.__name__ == "__main__"
This is a common idiom. It checks if the file is being run directly (like python main.py) or imported.
2. Packages
A Package is a directory containing Python modules. Historically, it required a__init__.py file (though Python 3.3+ makes this optional, it’s still good practice).
3. The Standard Library
Python is famous for being “Batteries Included”. It has a massive standard library built-in.pathlib (Modern File Paths)
Stop using os.path.join. Use pathlib. It works on Windows, Mac, and Linux seamlessly.
json (Data Serialization)
JSON is the language of the web. Python handles it natively.
datetime (Dates & Times)
4. Virtual Environments (venv)
The Golden Rule of Python: Never install packages globally. Always use a virtual environment.
A virtual environment creates an isolated folder for your project’s dependencies. This prevents “Dependency Hell” where Project A needs Library v1.0 and Project B needs Library v2.0.
Setup
(venv) C:\Project>). Now, when you run pip install, packages go into this folder, not your system.
5. Package Management (pip)
pip is the package installer for Python. It fetches packages from PyPI (Python Package Index).
Example: Using requests
requests is the most popular Python library. It makes HTTP requests simple.
Summary
- Modules:
.pyfiles. - Packages: Folders with
__init__.py. - Standard Library: Learn
pathlib,json,datetime. - venv: Always isolate your projects.
- pip: The tool to install external libraries.