Python Dependencies
Python Dependencies
1. Introduction
When building Python programs, you often need to use additional functionality that
isn't available in the core language. This is where modules, packages, libraries, and
dependencies come in. Understanding how they work is essential for writing efficient,
modular, and maintainable Python code.
2. Key Definitions
Module: A file containing Python code (.py file) that defines functions,
classes, and variables which can be imported and reused in other programs.
PyPI (Python Package Index): The official online repository where Python
developers can publish and share their packages.
3. What is a Module?
Example:
# math_module.py
PI = 3.1416
def area_of_circle(radius):
return PI * radius ** 2
Built-in Modules
Python includes many built-in modules that provide a wide range of functionality:
Example:
import math
print(math.sqrt(16))
4. What is a Package?
Structure Example:
my_package/
__init__.py
geometry.py
algebra.py
Usage Example:
from my_package import geometry
Packages are ideal for large applications where code needs to be grouped logically.
5. Third-party Packages
These are packages developed by the Python community and shared via repositories
like PyPI (Python Package Index).
Popular Examples:
pip list
To uninstall a package:
Example requirements.txt:
numpy==1.24.0
pandas>=1.3.0
requests
7. Virtual Environments
A virtual environment creates a separate space for your Python project. It prevents
version conflicts and keeps your global Python installation clean.
# Deactivate
deactivate
8. Importing in Python
Examples:
import math
from datetime import datetime
import numpy as np
Avoid using wildcard imports (from module import *) as it clutters the namespace
and can lead to conflicts.
Example Structure:
my_project/
main.py
utils/
__init__.py
helpers.py
data/
tests/
test_helpers.py
requirements.txt
README.md
Tips:
Keep configuration files (like .env, .gitignore, etc.) in the root folder
10. Summary
Understanding and using these elements correctly is crucial for efficient, collaborative,
and scalable Python development.