🐍 PYTHON
Le Langage Universel — Guide Complet & Bonnes Pratiques
2025 — Python 3.12+ | Web, Data Science, IA, Automation
1. Introduction à Python
Python est un langage de programmation de haut niveau, interprété et polyvalent créé par Guido
van Rossum en 1991. Sa philosophie est simple : le code doit être lisible, élégant et expressif. "Il
devrait y avoir une seule manière évidente de faire les choses."
💡 Le Zen de Python
"Simple vaut mieux que complexe. Lisible compte. Explicite vaut mieux qu'implicite. Les erreurs ne
devraient jamais passer silencieusement." — Tim Peters, PEP 20
1.1 Pourquoi Python domine en 2025 ?
▶ N°1 mondial : premier langage de programmation selon l'index TIOBE 2025
▶ Versatilité : web, data science, IA/ML, automatisation, scripting, DevOps
▶ IA/ML natif : TensorFlow, PyTorch, scikit-learn, LangChain sont en Python
▶ Syntaxe claire : code lisible, facile à apprendre et à maintenir
▶ Communauté : 500 000+ packages sur PyPI, millions de développeurs
▶ Entreprises : Google, Netflix, NASA, Instagram, Spotify l'utilisent massivement
1.2 Les domaines de Python
Domaine Frameworks/Libs Exemples d'usage
Web Backend FastAPI, Django, Flask APIs REST, sites web
Data Science Pandas, NumPy, Jupyter Analyse de données
IA / ML PyTorch, TensorFlow, sklearn ML, deep learning, LLM
Automatisation Selenium, Playwright, pyauto Web scraping, bots RPA
DevOps/Cloud boto3, Ansible, Fabric AWS, infra as code
Finance QuantLib, zipline, backtrader Trading, analyse quant
Cybersécurité Scapy, Requests, paramiko Pentesting, scripts
Jeux Pygame, Ursina Prototypage de jeux
2. Installation & Environnement
2.1 Installation avec pyenv (recommandé)
# pyenv = gérer plusieurs versions Python (comme nvm pour Node)
# Installation Linux/Mac
curl [Link] | bash
# Installer la dernière version stable
pyenv install 3.12.4
pyenv global 3.12.4
# Vérification
python --version # Python 3.12.4
pip --version # pip 24.x
# Windows : télécharger [Link] ou utiliser winget
winget install [Link].3.12
# Mise à jour pip
python -m pip install --upgrade pip
2.2 Environnements virtuels
# ✅ TOUJOURS utiliser un environnement virtuel par projet !
# Créer un venv avec venv (intégré Python 3.3+)
python -m venv .venv
# Activer (Linux/Mac)
source .venv/bin/activate
# Activer (Windows)
.venv\Scripts\activate
# Votre prompt change : (.venv) user@host:~/projet$
# Gérer les dépendances
pip install fastapi uvicorn pandas
pip freeze > [Link] # Sauvegarder les dépendances
pip install -r [Link] # Restaurer sur un autre machine
# Alternative moderne : uv (10-100x plus rapide que pip)
pip install uv
uv venv && source .venv/bin/activate
uv pip install fastapi uvicorn # Beaucoup plus rapide !
2.3 Structure d'un projet Python
mon_projet/
├── src/
│ └── mon_projet/
│ ├── __init__.py
│ ├── models/ # Modèles de données
│ │ └── [Link]
│ ├── services/ # Logique métier
│ │ └── user_service.py
│ ├── api/ # Routes API (FastAPI)
│ │ └── [Link]
│ └── [Link] # Configuration
├── tests/
│ ├── unit/
│ └── integration/
├── .venv/ # Jamais versionner !
├── .env # Variables d'env (jamais versionner)
├── .gitignore # .venv/, __pycache__/, .env
├── [Link] # Config moderne du projet
└── [Link]
3. Python Moderne — Fonctionnalités Clés
3.1 Type Hints — Python typé (3.5+)
# Python moderne utilise les type hints partout
from typing import Optional, Union, Literal
from [Link] import Sequence, Callable
# Fonctions typées
def greet(name: str, age: int = 0) -> str:
return f"Bonjour {name}, tu as {age} ans"
# Types complexes
def process_users(
users: list[dict[str, str | int]],
callback: Callable[[str], bool] | None = None,
) -> list[str]:
return [u["name"] for u in users if [Link]("active")]
# Dataclasses — remplacement moderne de __init__
from dataclasses import dataclass, field
@dataclass
class User:
id: int
name: str
email: str
role: Literal["admin", "user"] = "user"
tags: list[str] = field(default_factory=list)
def is_admin(self) -> bool:
return [Link] == "admin"
user = User(id=1, name="Alice", email="alice@[Link]")
print(user.is_admin()) # False
3.2 Pydantic — Validation de données
# pip install pydantic
from pydantic import BaseModel, EmailStr, Field, field_validator
from datetime import datetime
class UserCreate(BaseModel):
name: str = Field(min_length=2, max_length=50)
email: EmailStr
age: int = Field(ge=18, le=120)
password: str = Field(min_length=8)
@field_validator("name")
@classmethod
def name_must_not_contain_numbers(cls, v: str) -> str:
if any([Link]() for char in v):
raise ValueError("Le nom ne peut pas contenir de chiffres")
return [Link]() # Capitalise chaque mot
# Validation automatique
try:
user = UserCreate(name="alice2", email="invalid", age=15, password="short")
except ValidationError as e:
print([Link]()) # Détail des erreurs en JSON
valid_user = UserCreate(name="alice", email="alice@[Link]", age=25,
password="secure123")
print(valid_user.model_dump()) # {"name": "Alice", "email": "alice@[Link]",
...}
4. FastAPI — API Web Moderne & Rapide
FastAPI est le framework Python le plus moderne pour créer des APIs REST. Il combine la
performance d'ASGI (async), la validation automatique avec Pydantic, et génère la documentation
Swagger/OpenAPI automatiquement.
🚀 Performance FastAPI
FastAPI est l'un des frameworks Python les plus rapides — comparable à [Link] et Go pour les
opérations I/O. Il utilise Starlette (ASGI) et Uvicorn comme serveur asynchrone.
# pip install fastapi uvicorn[standard] pydantic[email] sqlalchemy
# src/[Link]
from fastapi import FastAPI, HTTPException, Depends, status
from [Link] import CORSMiddleware
from pydantic import BaseModel, EmailStr
from typing import Annotated
app = FastAPI(
title="Mon API",
description="Guide complet FastAPI 2025",
version="1.0.0",
)
# CORS — Permettre les requêtes depuis le frontend
app.add_middleware(
CORSMiddleware,
allow_origins=["[Link] # Vite dev
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Modèles Pydantic
class UserCreate(BaseModel):
name: str
email: EmailStr
class UserResponse(BaseModel):
id: int
name: str
email: str
model_config = {"from_attributes": True} # SQLAlchemy support
# Routes
@[Link]("/users", response_model=list[UserResponse])
async def get_users(skip: int = 0, limit: int = 20):
"""Récupère la liste des utilisateurs avec pagination."""
return await db.fetch_all(f"SELECT * FROM users LIMIT {limit} OFFSET {skip}")
@[Link]("/users", response_model=UserResponse, status_code=201)
async def create_user(user: UserCreate):
"""Crée un nouvel utilisateur. Email doit être unique."""
existing = await db.fetch_one("SELECT id FROM users WHERE email = :email",
{"email": [Link]})
if existing:
raise HTTPException(status_code=409, detail="Email déjà utilisé")
return await db.execute_and_return(user.model_dump())
@[Link]("/users/{user_id}", response_model=UserResponse)
async def get_user(user_id: int):
user = await db.fetch_one("SELECT * FROM users WHERE id = :id", {"id":
user_id})
if not user:
raise HTTPException(status_code=404, detail="Utilisateur introuvable")
return user
# Lancer : uvicorn [Link]:app --reload
# Docs auto : [Link]
4.1 Dépendances & Injection
# Depends() = injection de dépendances (auth, DB, pagination)
from fastapi import Depends
from [Link] import HTTPBearer, HTTPAuthorizationCredentials
security = HTTPBearer()
async def get_current_user(
credentials: HTTPAuthorizationCredentials = Depends(security)
) -> User:
token = [Link]
try:
payload = verify_token(token)
user = await get_user_by_id(payload["sub"])
if not user:
raise HTTPException(status_code=401)
return user
except Exception:
raise HTTPException(status_code=401, detail="Token invalide")
# Route protégée
@[Link]("/me", response_model=UserResponse)
async def get_me(current_user: User = Depends(get_current_user)):
return current_user
# Pagination réutilisable
from dataclasses import dataclass
@dataclass
class Pagination:
page: int = 1
size: int = 20
@property
def offset(self) -> int:
return ([Link] - 1) * [Link]
@[Link]("/posts")
async def get_posts(pagination: Pagination = Depends()):
return await fetch_posts([Link], [Link])
5. Python Data Science — Pandas & NumPy
5.1 Pandas — Manipulation de données
# pip install pandas numpy matplotlib seaborn
import pandas as pd
import numpy as np
# Créer un DataFrame
df = [Link]({
"name": ["Alice", "Bob", "Charlie", "Diana"],
"age": [25, 30, 35, 28],
"salary": [50000, 60000, 75000, 55000],
"department": ["Tech", "HR", "Tech", "Finance"],
})
# ✅ Opérations courantes
[Link]() # Structure du DataFrame
[Link]() # Statistiques descriptives
df[df["age"] > 28] # Filtrage
[Link]("department")["salary"].mean() # Agrégation
df.sort_values("salary", ascending=False) # Tri
# Méthode chaînée (recommandée)
result = (
df
.query("age > 25")
.groupby("department")
.agg(avg_salary=("salary", "mean"), count=("name", "count"))
.sort_values("avg_salary", ascending=False)
.reset_index()
)
# Lecture de fichiers
df = pd.read_csv("[Link]", parse_dates=["created_at"])
df = pd.read_excel("[Link]", sheet_name="Sheet1")
df = pd.read_json("[Link]")
# Export
df.to_csv("[Link]", index=False)
df.to_parquet("[Link]") # Format columnar très rapide
5.2 NumPy — Calcul scientifique
import numpy as np
# Arrays NumPy — plus rapides que les listes Python
arr = [Link]([1, 2, 3, 4, 5])
matrix = [Link]([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
# Opérations vectorisées (sans boucles)
arr * 2 # [2, 4, 6, 8, 10]
arr[arr > 3] # [4, 5]
[Link](arr) # 3.0
[Link](arr) # Écart-type
# Algèbre linéaire
[Link](matrix, matrix) # Produit matriciel
[Link](matrix) # Inverse
eigenvals, eigenvecs = [Link](matrix)
# Génération de données
[Link](42) # Reproductibilité
[Link](0, 1, (100, 3)) # Distribution normale
[Link](0, 2*[Link], 100) # 100 points de 0 à 2π
# Broadcasting — opérations sur arrays de formes différentes
a = [Link]([[1], [2], [3]]) # shape (3, 1)
b = [Link]([10, 20, 30]) # shape (3,)
a + b # [[11, 21, 31], [12, 22, 32], [13, 23, 33]]
6. Machine Learning avec scikit-learn
# pip install scikit-learn
from sklearn.model_selection import train_test_split, cross_val_score
from [Link] import StandardScaler, LabelEncoder
from [Link] import RandomForestClassifier, GradientBoostingClassifier
from [Link] import classification_report, confusion_matrix
from [Link] import Pipeline
import pandas as pd
# 1. Charger et préparer les données
df = pd.read_csv("[Link]")
X = [Link]("target", axis=1)
y = df["target"]
# 2. Split train/test (toujours avant tout !)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y
)
# 3. Pipeline — preprocessing + modèle
pipeline = Pipeline([
("scaler", StandardScaler()), # Normalisation des features
("model", RandomForestClassifier(
n_estimators=200,
max_depth=10,
random_state=42,
n_jobs=-1, # Utiliser tous les CPU
)),
])
# 4. Entraînement
[Link](X_train, y_train)
# 5. Évaluation
y_pred = [Link](X_test)
print(classification_report(y_test, y_pred))
# 6. Cross-validation — évaluation robuste
scores = cross_val_score(pipeline, X, y, cv=5, scoring="f1_macro")
print(f"F1 moyen : {[Link]():.3f} ± {[Link]():.3f}")
# 7. Sauvegarde du modèle
import joblib
[Link](pipeline, "[Link]")
loaded_model = [Link]("[Link]")
7. Python Asynchrone — asyncio
import asyncio
import aiohttp # pip install aiohttp
# Fonction asynchrone simple
async def fetch_url(session: [Link], url: str) -> dict:
async with [Link](url) as response:
response.raise_for_status()
return await [Link]()
# ✅ Requêtes parallèles — beaucoup plus rapide que séquentiel
async def fetch_all_users() -> list[dict]:
urls = [
"[Link]
"[Link]
"[Link]
]
async with [Link]() as session:
tasks = [fetch_url(session, url) for url in urls]
results = await [Link](*tasks, return_exceptions=True)
return [r for r in results if not isinstance(r, Exception)]
# ✅ Timeout et gestion d'erreurs
async def safe_fetch(url: str, timeout: float = 5.0)-> dict | None:
try:
async with [Link](
timeout=[Link](total=timeout)
) as session:
return await fetch_url(session, url)
except ([Link], [Link]) as e:
print(f"Erreur: {e}")
return None
# Lancer le code async
if __name__ == "__main__":
users = [Link](fetch_all_users())
8. Tests avec pytest
# pip install pytest pytest-asyncio pytest-cov httpx
# tests/test_users.py
import pytest
from httpx import AsyncClient
from [Link] import app
# Fixture — données réutilisables
@[Link]
def sample_user() -> dict:
return {"name": "Alice", "email": "alice@[Link]", "age": 25}
@[Link]
async def async_client():
async with AsyncClient(app=app, base_url="[Link] as client:
yield client
# Test unitaire simple
def test_user_validation():
from [Link] import UserCreate
user = UserCreate(name="Alice", email="alice@[Link]", age=25)
assert [Link] == "Alice"
assert [Link] == "alice@[Link]"
# Test que la validation rejette les mauvaises données
def test_user_validation_fails():
from pydantic import ValidationError
with [Link](ValidationError):
UserCreate(name="A", email="invalid", age=10)
# Test d'API async
@[Link]
async def test_create_user(async_client, sample_user):
response = await async_client.post("/users", json=sample_user)
assert response.status_code == 201
data = [Link]()
assert data["name"] == sample_user["name"]
assert "id" in data
# Lancer : pytest tests/ -v --cov=src --cov-report=html
9. Bonnes Pratiques Python
9.1 Style & PEP 8
Élément Convention Exemple
Variables/fonctions snake_case user_name, get_users()
Classes PascalCase UserService, ApiClient
Constantes UPPER_SNAKE_CASE MAX_RETRIES, API_URL
Modules snake_case user_service.py
Packages lowercase mypackage/
Privé (convention) _préfixe _internal, _helper()
Longueur de ligne Max 88 caractères Via Black formatter
9.2 Outils de qualité de code
# Installation des outils
pip install ruff black mypy pre-commit
# [Link] — configuration centralisée
[[Link]]
line-length = 88
target-version = ["py312"]
[[Link]]
line-length = 88
select = ["E", "F", "I", "N", "W", "UP"] # Rules activées
[[Link]]
strict = true
python_version = "3.12"
# Commandes
black . # Formatage automatique
ruff check . # Linting ultra-rapide (remplace flake8, isort)
mypy src/ # Vérification des types
pytest --cov # Tests avec couverture
10. Écosystème Python 2025
Catégorie Recommandé Alternative
Web API FastAPI Django REST, Flask
ORM SQLAlchemy 2.0 Tortoise ORM, Django ORM
Validation Pydantic v2 attrs, dataclasses
HTTP client httpx requests, aiohttp
Tests pytest + httpx unittest
Format/Lint ruff + black flake8 + isort
Types mypy pyright
Env/Deps uv poetry, pip-tools
Data Science pandas + polars Dask (big data)
ML scikit-learn XGBoost, LightGBM
Deep Learning PyTorch TensorFlow, JAX
LLM/IA Gen LangChain, LlamaIndex Haystack
Task Queue Celery + Redis rq, dramatiq
Monitoring Sentry + Prometheus Datadog, NewRelic
🚀 Stack Python Web Production 2025
FastAPI + Pydantic v2 + SQLAlchemy 2.0 + PostgreSQL + Redis + Celery + Docker + GitHub
Actions + Sentry. Pour Data/IA : Jupyter + Pandas + Polars + PyTorch + MLflow.
11. Ressources
▶ [Link] — Documentation officielle Python 3
▶ [Link] — Documentation FastAPI
▶ [Link] — Pydantic v2
▶ [Link] — Tutoriels de qualité en anglais
▶ [Link] — Chercher des packages Python
▶ [Link] — Python Enhancement Proposals
✅ Résumé
Python est en 2025 le langage le plus populaire au monde, et pour de bonnes raisons : sa
polyvalence couvre le web, la data science, l'IA et l'automatisation. FastAPI, Pydantic et les type
hints ont transformé Python en un langage moderne, robuste et agréable à utiliser en production.