Bienvenue sur Python
Python est un langage de programmation polyvalent de haut niveau connu pour sa lisibilité et son large support communautaire. Développé au début des années 1990, il met l'accent sur une syntaxe claire et concise, ce qui en fait un excellent choix pour les débutants comme pour les professionnels. La vaste bibliothèque standard de Python et son écosystème florissant de packages tiers lui permettent d'être utilisé dans de nombreux domaines, du développement Web et de l'analyse de données à l'intelligence artificielle et au calcul scientifique. Sa facilité d'apprentissage, associée à ses puissantes fonctionnalités, fait de Python une compétence précieuse pour quiconque cherche à se lancer dans la programmation ou à faire progresser sa carrière technologique.
Introduction à Python
Comment installer Python et écrire votre premier "Hello, World!" programme.
Python est l'un des langages de programmation les plus populaires en raison de sa simplicité et de sa polyvalence. Que vous soyez débutant ou codeur expérimenté, installer Python et exécuter votre premier script est un processus simple.
Étape 1 : Téléchargez et installez Python
-
Visitez le site Web officiel
Accédez à Python.org et téléchargez la dernière version stable de Python pour votre système d'exploitation (Windows, macOS ou Linux). -
Exécutez le programme d'installation
-
Pour Windows : double-cliquez sur le fichier
.exetéléchargé et cochez "Ajouter Python au PATH" avant de cliquer sur "Installer". Maintenant". -
Pour Mac : téléchargez le programme d'installation de macOS et suivez les instructions de configuration.
-
Pour Linux : utilisez le gestionnaire de packages (par exemple, pour Ubuntu).
shsudo apt install python3 -
Vérifier l'installation
Ouvrez un terminal ou une invite de commande et tapez :
shpython --version
ou
shpython3 --version
Cela devrait afficher la version de Python installée.
Étape 2 : Choisissez un IDE ou un éditeur de code
Python est livré avec IDLE, un environnement de développement intégré (IDE), idéal pour les débutants. Cependant, les utilisateurs plus avancés préfèrent souvent les éditeurs tels que :
-
VS Code – Léger et puissant, avec des extensions Python.
-
PyCharm – IDE riche en fonctionnalités pour les développeurs professionnels.
-
Jupyter Notebook – Idéal pour la science des données et le codage interactif.
Pour les débutants, lancer IDLE (installé avec Python) est le moyen le plus simple de commencer à coder.
Étape 3 : Écrivez et exécutez votre premier script Python
-
Utilisation de IDLE :
-
Ouvrir IDLE.
-
Cliquez sur Fichier → Nouveau fichier.
Tapez le code suivant :
pythonprint("Hello, World!") -
-
Enregistrez le fichier avec une extension
.py(par exemple,hello.py). -
Exécutez-le en sélectionnant Exécuter → Exécuter le module ou en appuyant sur
F5. -
Utilisation de la ligne de commande :
-
Ouvrez un terminal ou une invite de commande.
-
Accédez au dossier dans lequel vous avez enregistré
hello.py. -
Exécutez le script en tapant :
python bonjour.py -
-
Vous devriez voir le résultat :
Bonjour tout le monde !
Félicitations ! Vous avez installé Python avec succès et exécuté votre premier script. 🎉
Pour plus de détails, visitez la documentation officielle de Python à docs.python.org. Bon codage ! 🚀
Syntaxe de python
1. Indentation Python (pas d'accolades pour les blocs)
Python utilise indentation (espaces) pour définir des blocs de code au lieu d'accolades {} comme dans d'autres langages. Cela rend le code Python plus lisible, mais signifie également qu'une indentation incorrecte entraînera des erreurs.
Exemple correct :
pythonif 5 > 3:
print("Five is greater than three") # Proper indentation
Exemple incorrect (déclenche une erreur d'indentation) :
pythonif 5 > 3:
print("This will cause an error!") # No indentation
Python applique l'indentation pour une meilleure structure et lisibilité du code. L'indentation recommandée est de 4 espaces par niveau.
2. Indexation base zéro
Python suit indexation de base zéro, ce qui signifie que le premier élément d'une séquence (comme une liste, une chaîne ou un tuple) commence à index 0, et non à 1.
Exemple :
pythonfruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Outputs: apple
print(fruits[2]) # Outputs: cherry
Exemple incorrect (IndexError) :
pythonprint(fruits[3]) # IndexError: list index out of range
Puisque Python commence à compter à partir de 0, toute tentative d'accès à un index égal ou supérieur à la longueur de la séquence entraîne une erreur.
3. Commentaires en Python
Les commentaires aident les développeurs à comprendre le code en ajoutant des explications. Python prend en charge à la fois les single-line et les commentaires multi-lignes.
Commentaire sur une seule ligne :
python# This is a single-line comment
print("Hello, World!") # Inline comment
Commentaire sur plusieurs lignes :
python"""
This is a multi-line comment.
It is often used for documentation.
"""
print("Hello, World!")
Bien que les guillemets triples puissent être utilisés pour les commentaires sur plusieurs lignes, ils sont principalement destinés aux docstrings, qui sont des commentaires spéciaux placés dans des fonctions de documentation.
4. Sensibilité à la casse
Python est sensible à la casse, ce qui signifie qu'il traite les lettres majuscules et minuscules différemment. Les noms de variables, les noms de fonctions et les mots-clés doivent être utilisés de manière cohérente.
Exemple :
pythonmyVar = 5
MyVar = 10
print(myVar) # Outputs: 5
print(MyVar) # Outputs: 10 (different variable)
Ici, myVar et MyVar sont considérées comme deux variables différentes en raison de leur capitalisation.
Exemple incorrect :
pythonPrint("Hello") # NameError: name 'Print' is not defined
Les fonctions intégrées de Python comme print() doivent être écrites en minuscules.
5. Variables et saisie dynamique
Python est typé dynamiquement, ce qui signifie que vous n'avez pas besoin de déclarer explicitement le type d'une variable. Le type est déterminé automatiquement en fonction de la valeur attribuée.
Exemple :
pythonx = 10 # Integer
y = 3.14 # Float
z = "Hello" # String
print(type(x)) # Outputs: <class 'int'>
print(type(y)) # Outputs: <class 'float'>
print(type(z)) # Outputs: <class 'str'>
Réaffectation de différents types de données :
pythona = 5 # Initially an integer
a = "Python" # Now reassigned as a string
print(a) # Outputs: Python
Étant donné que Python autorise le typage dynamique, le type d'une variable peut changer pendant l'exécution.
Conclusion
Comprendre la syntaxe de base de Python est essentiel pour écrire du code propre et efficace. Les principaux points à retenir sont :
-
Python applique indentation au lieu d'accolades pour les blocs de code.
-
Indexation de base zéro signifie que le premier élément d'une séquence est à l'index
0. -
Comments améliore la lisibilité du code et peut être une seule ligne (
#) ou multiligne (""" """). -
Python est sensible à la casse, donc
Varetvarsont traités comme différents variables. -
Python prend en charge le typage dynamique, permettant aux variables de changer de type.
La maîtrise de ces bases fournira une base solide pour l'apprentissage de concepts Python plus avancés. Bon codage ! 🚀
imprimer
La fonction print() en Python est utilisée pour afficher la sortie à l'écran. C'est l'une des fonctions les plus couramment utilisées, notamment pour le débogage et l'interaction avec l'utilisateur. Dans ce petit guide, nous explorerons différentes manières d'utiliser efficacement print(), notamment comment imprimer plusieurs valeurs, formater la sortie et contrôler les séparateurs et les caractères de fin.
1. Base print() Utilisation
La façon la plus simple d'utiliser print() est de passer une chaîne ou un nombre entre parenthèses :
pythonprint("Hello, World!") # Outputs: Hello, World!
print(42) # Outputs: 42
Vous pouvez imprimer plusieurs valeurs en les séparant par une virgule ,:
pythonprint("Hello", "Python") # Outputs: Hello Python
Par défaut, Python insère un espace entre les valeurs.
2. Utilisation du paramètre sep
Le paramètre sep contrôle le séparateur entre plusieurs valeurs dans print(). Par défaut, il s'agit d'un espace, mais vous pouvez le remplacer par n'importe quoi d'autre :
pythonprint("apple", "banana", "cherry", sep=", ")
# Outputs: apple, banana, cherry
pythonprint("Python", "is", "fun", sep="-")
# Outputs: Python-is-fun
```<h2><span style="font-family: Roboto;">3. Utilisation du paramètre <code inline="">end</code></span></h2>
<p><span style="font-family: Roboto;">Par défaut, <code inline="">print()</code> ajoute une nouvelle ligne (<code inline="">\n</code>) à la fin de la sortie. Vous pouvez modifier ce comportement à l'aide du paramètre <code inline="">end</code> :</span></p>
```python
print("Hello", end=" ")
print("World!")
# Outputs: Hello World! (on the same line)
Ici, end=" " remplace la nouvelle ligne par défaut par un espace.
4. Variables d'impression
Vous pouvez imprimer des variables comme des chaînes littérales :
pythonname = "Alice"
age = 25
print("Name:", name, "Age:", age)
# Outputs: Name: Alice Age: 25
Vous pouvez également utiliser f-strings pour un résultat plus propre :
pythonprint(f"Name: {name}, Age: {age}")
# Outputs: Name: Alice, Age: 25
5. Impression de caractères spéciaux
Utilisez des séquences d'échappement pour formater la sortie :
pythonprint("Hello\nWorld!") # \n adds a new line
print("This is a tab:\tPython") # \t adds a tab space
```<hr />
<h2><span style="font-family: Roboto;">Conclusion</span></h2>
<p><span style="font-family: Roboto;">La fonction <code inline="">print()</code> est un outil puissant en Python qui vous permet d'afficher la sortie de différentes manières. Points clés à retenir :</span></p>
<ul>
<li>
<p><span style="font-family: Roboto;">Utilisez <code inline="">print(value1, value2, …)</code> pour imprimer plusieurs valeurs.</span></p>
</li>
<li>
<p><span style="font-family: Roboto;">Modifiez le séparateur en utilisant <code inline="">sep="custom_separator"</code>.</span></p>
</li>
<li>
<p><span style="font-family: Roboto;">Ligne de contrôle se terminant par <code inline="">end="custom_end"</code>.</span></p>
</li>
<li>
<p><span style="font-family: Roboto;">Utilisez <code inline="">f-strings</code> pour un meilleur formatage.</span></p>
</li>
</ul>
<p><span style="font-family: Roboto;">La maîtrise de <code inline="">print()</code> facilitera grandement le débogage et la gestion des sorties en Python.</span></p>
Variables
Les variables sont utilisées pour stocker des données en Python. Ils agissent comme des conteneurs nommés pour des valeurs de différents types (nombres, chaînes, etc.). Les variables Python doivent suivre certaines règles de dénomination :
- Le nom d'une variable doit commencer par une lettre ou un trait de soulignement (
__). - Un nom de variable ne peut pas commencer par un chiffre.
- Une variable ne peut pas utiliser de mots-clés Python réservés (voir le module
keyword).
1. Création de variables
En Python, les variables sont créées automatiquement lorsque vous leur attribuez une valeur à l'aide de l'opérateur d'affectation =.
Aucune déclaration explicite n’est nécessaire.
pythona = 10
b = "Hello"
c = 3.14
print(a, b, c) # Outputs: 10 Hello 3.14
2. Affectation de plusieurs variables
En cas de modification de deux variables ou plus à la fois et d'utilisation de certaines valeurs pour des calculs en cours, il est utile de changez-le simultanément.
pythona, b = 4, 5
print(a) # Outputs: 4
print(b) # Outputs: 5
```<h2><span style="font-family: Roboto;">3. Utilisation de l'entrée pour créer des variables</span></h2>
<p><span style="font-family: Roboto;">
Des variables peuvent également être créées à partir de la saisie de l'utilisateur à l'aide de la fonction <code>input()</code>.
Par défaut, <code>input()</code> renvoie une chaîne, mais vous pouvez la convertir en d'autres types si nécessaire.
</span></p>
```python
name = input("Enter your name: ")
age = int(input("Enter your age: ")) # type conversion to integer
print("Hello", name, "you are", age, "years old.")
4. Conversion de type
Parfois, vous devrez peut-être effectuer une conversion entre types de données (par exemple, d'une chaîne à un entier).
Les fonctions courantes incluent int(), float() et str().
pythonnum_str = "123"
num = int(num_str) # convert string to integer
print(num, type(num)) # Outputs: 123 <class 'int'>
pi = 3.1415
print(str(pi)) # convert float to string → "3.1415"
5. Opérateurs et variables
Les variables peuvent être utilisées avec arithmetic, comparaison, et d'autres opérateurs d'affectation. Voir les sections dédiées aux opérateurs pour plus de détails et d'exemples.
Opérations binaires en Python
1. Opérateurs arithmétiques
Les opérateurs arithmétiques effectuent des calculs mathématiques entre deux opérandes. Python prend en charge l'addition, la soustraction, la multiplication, la division, le modulo, la division au sol et l'exponentiation.
Exemples :
pythona = 15
b = 4
print(a + b) # 19 (addition)
print(a - b) # 11 (subtraction)
print(a * b) # 60 (multiplication)
print(a / b) # 3.75 (true division)
print(a // b) # 3 (floor division)
print(a % b) # 3 (modulus)
print(a ** b) # 50625 (exponentiation)
Les opérateurs arithmétiques renvoient toujours une nouvelle valeur sans modifier les variables d'origine.
2. Opérateurs de comparaison
Les opérateurs de comparaison comparent deux valeurs et renvoient un résultat booléen (True ou False).
Ceux-ci incluent l’égalité, l’inégalité, supérieur/inférieur et leurs combinaisons.
Exemples :
pythonx = 7
y = 10
print(x == y) # False (equal to)
print(x != y) # True (not equal to)
print(x > y) # False
print(x < y) # True
print(x >= 7) # True
print(y <= 7) # False
Les résultats de comparaison sont souvent utilisés dans des instructions ou des boucles if pour contrôler le déroulement du programme.
3. Opérateurs logiques
Les opérateurs logiques combinent des valeurs booléennes et renvoient True ou False.
Les trois opérateurs sont et, or et not (unaire).
Exemples :
pythonis_sunny = True
is_warm = False
print(is_sunny and is_warm) # False (both must be True)
print(is_sunny or is_warm) # True (at least one is True)
print(not is_warm) # True (negates the value)
Les opérateurs logiques sont fréquemment utilisés dans des conditions, par ex. vérifier plusieurs exigences à la fois.
4. Opérateurs au niveau du bit
Les opérateurs au niveau du bit agissent sur les représentations binaires d'entiers.
Ils incluent & (AND), | (OR), ^ (XOR), << (décalage à gauche) et >> (à droite). décalage).
Exemples :
pythona = 6 # binary: 110
b = 3 # binary: 011
print(a & b) # 2 (binary 010)
print(a | b) # 7 (binary 111)
print(a ^ b) # 5 (binary 101)
print(a << 1) # 12 (binary 1100, shifted left by 1)
print(b >> 1) # 1 (binary 001, shifted right by 1)
Les opérations au niveau du bit sont souvent utilisées dans la programmation de bas niveau, la cryptographie ou l'optimisation des performances.
5. Opérateurs d'affectation
Les opérateurs d'affectation attribuent des valeurs aux variables. Ils peuvent également combiner l’affectation avec des opérations arithmétiques ou au niveau du bit.
Exemples :
pythonx = 10 # simple assignment
x += 5 # equivalent to x = x + 5 → 15
x -= 3 # equivalent to x = x - 3 → 12
x *= 2 # equivalent to x = x * 2 → 24
x //= 4 # equivalent to x = x // 4 → 6
x %= 4 # equivalent to x = x % 4 → 2
x **= 3 # equivalent to x = x ** 3 → 8
Les opérateurs d'affectation sont des raccourcis permettant de mettre à jour une variable en place, ce qui rend le code plus concis.
Entiers
Les entiers sont des nombres entiers, positifs, négatifs ou nuls. Ils constituent l'un des types numériques de base de Python et sont utilisés pour les opérations mathématiques.
1. Création d'entiers
Des entiers peuvent être créés en attribuant des valeurs entières aux variables :
pythona = 10
b = -5
c = 0
print(a, b, c)
2. Opérations sur les entiers
Les entiers prennent en charge diverses opérations arithmétiques :
pythonprint(5 + 3) # Addition
print(5 - 3) # Subtraction
print(5 * 3) # Multiplication
print(5 / 3) # Division (returns float)
print(5 // 3) # Floor division
print(5 % 3) # Modulus
3. Conversion de type
Conversion d'autres types en entiers :
pythonnum = int("123")
print(num) # Outputs: 123
num = int(3.1415)
print(num) # Outputs: 3
Flotteurs
Les flotteurs représentent des nombres réels pouvant avoir des parties fractionnaires. Ils constituent un autre type numérique de base en Python et sont essentiels pour les calculs décimaux.
1. Création de flotteurs
Des flotteurs peuvent être créés en attribuant des valeurs décimales aux variables :
pythona = 3.1415
b = -0.5
c = 100.0
print(a, b, c)
2. Opérations flottantes
Les flotteurs prennent en charge diverses opérations arithmétiques :
pythonprint(2.5 + 1.5) # Addition
print(5.0 / 2) # Division
print(3.1415 ** 2) # Exponentiation
print(7.3 % 3) # Modulus
3. Conversion de type
Conversion d'autres types en flottants :
pythonnum = float("123.45")
print(num) # Outputs: 123.45
num = float(3)
print(num) # Outputs: 3.0
num = float(5.5)
print(num) # Outputs: 5.5
Les Booléens en Python
Le type de données bool représente les valeurs de vérité : True et False. En Python, bool est une sous-classe de int (avec True == 1 et False == 0).
Chaînes
Les chaînes sont des séquences de caractères utilisées pour représenter du texte. Ils sont immuables et peuvent être définis à l'aide de guillemets simples, doubles ou triples pour les chaînes multilignes.
1. Création de chaînes
Les chaînes peuvent être créées à l'aide de différents types de guillemets :
pythona = 'Hello, World!'
b = "Python is great"
c = """This is a
multi-line string"""
print(a, b, c, sep='\n')
2. Opérations sur les chaînes
Les chaînes prennent en charge diverses opérations telles que la concaténation et la répétition :
pythonprint("Hello" + " World") # Concatenation
print("Hello" * 3) # Repetition
print("Hello"[0]) # Accessing characters
print("Hello"[1:3]) # Slicing
3. Méthodes de chaîne
Les chaînes ont diverses méthodes intégrées de manipulation :
pythontext = "hello world"
print(text.upper()) # Outputs: HELLO WORLD
print(text.lower()) # Outputs: hello world
print(text.replace("world", "earth")) # Outputs: hello earth
Fonctions de chaîne
Les chaînes disposent de nombreuses méthodes utiles pour couper, diviser et remplacer du texte.
Découpage avec .strip()
pythontext = " hello world "
print(text.strip()) # "hello world"
print(text.lstrip()) # "hello world "
print(text.rstrip()) # " hello world"
Diviser les chaînes
pythonline = "apple,banana,cherry"
print(line.split(",")) # ['apple', 'banana', 'cherry']
words = "one two three".split()
print(words) # ['one', 'two', 'three']
Remplacement du texte
pythonsentence = "I like cats"
print(sentence.replace("cats", "dogs"))
# "I like dogs"
Joindre des chaînes
pythonparts = ["2025", "09", "26"]
date = "-".join(parts)
print(date) # "2025-09-26"
Pièges courants
.strip()supprime les espaces par défaut, mais vous pouvez transmettre des caractères :"hello!!".strip("!")..split()sans arguments se divise sur n'importe quel espace, pas seulement des espaces..replace()remplace toutes occurrences, sauf si vous transmettez un troisième argument (nombre maximum)..join()exige que tous les éléments soient des chaînes (et non des nombres).
Formatage des chaînes et méthodes de casse
Python propose plusieurs méthodes pour formater les chaînes et ajuster leur casse. Cela permet de créer une sortie dynamique et de contrôler l'apparence du texte.
Formatage avec .format()
python# Insert values into placeholders {}
template = "The sum of {0} and {1} is {2}"
msg = template.format(2, 4, 2+4)
print(msg) # The sum of 2 and 4 is 6
# Named placeholders
info = "Name: {name}, Age: {age}".format(name="Alice", age=30)
print(info)
Conversion de cas
pythontext = "Hello World"
print(text.upper()) # "HELLO WORLD"
print(text.lower()) # "hello world"
Partitionnement des chaînes
pythonline = "user:password"
print(line.partition(":"))
# ('user', ':', 'password')
.partition() se divise en un tuple en 3 parties :
texte avant, le séparateur lui-même et le texte après.
Pièges courants
- L'utilisation de
.format()avec des clés manquantes ou incorrectes génèreKeyErrorouIndexError. .upper()/.lower()créent une nouvelle chaîne, ils ne modifient pas l'original..partition()se divise uniquement lors de la première occurrence du séparateur.
Listes
Les listes sont des séquences polyvalentes et mutables utilisées pour stocker des collections d'éléments. Ils sont définis entre crochets [] et prennent en charge diverses opérations de modification et d'accès.
1. Création d'une liste
Définir une liste avec divers éléments :
pythonmy_list = [1, 2, 3, "Python", True]
print(my_list)
2. Accès et modification des listes
Les listes prennent en charge l'indexation, le découpage et les méthodes de modification de leur contenu :
python# Accessing an element
print(my_list[3]) # Outputs: Python
# Changing an element
my_list[1] = "changed"
print(my_list)
# Appending a new element
my_list.append("new item")
print(my_list)
3. Compréhensions des listes
Les compréhensions de listes fournissent un moyen concis de créer des listes en itérant sur des séquences et en appliquant éventuellement des conditions :
python# Creating a list of squares for numbers 0 to 9
squares = [x**2 for x in range(10)]
print(squares)
Listes d'indexation
En Python, les listes sont des collections ordonnées et vous pouvez accéder aux éléments en utilisant leur index. L'indexation commence à 0 pour le premier élément. Les indices négatifs comptent à partir de la fin de la liste, -1 étant le dernier élément.
Indexation de base
pythonfruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Outputs: apple
print(fruits[-1]) # Outputs: cherry
Modification d'éléments via l'index
pythonnumbers = [10, 20, 30]
numbers[1] = 25
print(numbers) # Outputs: [10, 25, 30]
Pièges courants
- IndexError: Accès à un index en dehors de la plage de la liste.
- Mutable vs Immuable : Seules les listes mutables peuvent être modifiées via l'indexation ; les tuples ne prennent pas en charge l'affectation.
Listes de découpage
Slicing vous permet d'extraire une partie d'une liste en utilisant la syntaxe list[start:stop:step]. L'index start est inclusif, stop est exclusif et step définit l'intervalle.
Découpage de base
pythonnumbers = [0, 1, 2, 3, 4, 5]
print(numbers[1:4]) # Outputs: [1, 2, 3]
print(numbers[:3]) # Outputs: [0, 1, 2]
print(numbers[3:]) # Outputs: [3, 4, 5]
print(numbers[::2]) # Outputs: [0, 2, 4] - every 2nd element
Inverser une liste
pythonprint(numbers[::-1]) # Outputs: [5, 4, 3, 2, 1, 0]
Pièges courants
- L'index Stop est exclusif ;
list[start:stop]n'inclut pas l'élément àstop. - Les indices négatifs peuvent être délicats ; assurez-vous qu'ils sont utilisés correctement avec la longueur de la liste.
- Slicing renvoie une nouvelle liste ; il ne modifie pas l'original à moins qu'il ne soit réaffecté.
Fonctions et méthodes spécifiques à une liste
Python fournit de nombreuses fonctions et méthodes intégrées spécifiquement pour les listes afin de manipuler, interroger et transformer efficacement les données.
Méthodes courantes
pythonfruits = ["apple", "banana", "cherry"]
fruits.append("date") # Add element at the end
fruits.insert(1, "blueberry") # Insert at index 1
fruits.remove("banana") # Remove element by value
popped = fruits.pop() # Remove and return last element
print(fruits, popped)
Autres méthodes utiles
pythonnumbers = [3, 1, 4, 2]
numbers.sort() # Sorts in ascending order
numbers.reverse() # Reverses the list
print(numbers)
Fonctions intégrées pour les listes
pythonnums = [1, 2, 3, 4]
print(len(nums)) # Number of elements
print(sum(nums)) # Sum of elements
print(max(nums)) # Maximum value
print(min(nums)) # Minimum value
Travailler avec plusieurs listes
python# enumerate() gives index + value when looping
animals = ["cat", "dog", "mouse"]
for index, animal in enumerate(animals):
print(index, animal)
# zip() pairs elements from multiple lists
names = ["Alice", "Bob", "Charlie"]
scores = [85, 92, 78]
for name, score in zip(names, scores):
print(name, "scored", score)
enumerate() est utile lorsque vous avez besoin à la fois de la position et de la valeur d'un élément de liste.
zip() est utile lors de la combinaison de deux ou plusieurs listes élément par élément.
Pièges courants
- Des méthodes telles que
sort()etreverse()modifient la liste sur place et renvoientAucun. - La suppression d'éléments qui n'existent pas génère
ValueError. - Soyez prudent avec
pop()sur les listes vides ; il génèreIndexError. zip()s'arrête à la longueur de liste la plus courte.
Tuples
Les tuples sont des séquences immuables utilisées pour stocker une collection d'éléments. Ils sont définis entre parenthèses () et sont utiles lorsque vous souhaitez garantir l'intégrité des données.
1. Création d'un tuple
Un simple tuple contenant différents types de données :
pythonmy_tuple = (10, "hello", 3.14)
print(my_tuple)
2. Accès aux éléments de tuple
Accéder aux éléments par leur index, semblable aux listes :
python# Accessing the first element
print(my_tuple[0]) # Outputs: 10
# Slicing the tuple
print(my_tuple[1:]) # Outputs: ('hello', 3.14)
Étant donné que les tuples sont immuables, leurs valeurs ne peuvent pas être modifiées après leur création.
Les Ensembles (Sets) en Python
Un ensemble (set) est une collection non ordonnée d'éléments uniques. Contrairement aux tuples ordonnés qui autorisent les doublons, un set garantit l'unicité et permet des recherches instantanées en temps $O(1)$.
Dictionnaires
Les dictionnaires stockent les données dans des paires clé-valeur, ce qui rend la recherche de données efficace. Ils sont créés à l'aide d'accolades {} et sont accessibles via leurs clés.
1. Création d'un dictionnaire
Un dictionnaire de base cartographiant les fruits selon leurs couleurs :
pythonfruit_colors = {
"apple": "red",
"banana": "yellow",
"cherry": "red"
}
2. Accès et modification des données
Accédez à une valeur à l'aide de sa clé, ajoutez une nouvelle paire clé-valeur ou mettez à jour une paire existante :
python# Accessing a value
print(fruit_colors["apple"]) # Outputs: red
# Adding a new entry
fruit_colors["orange"] = "orange"
# Updating an entry
fruit_colors["banana"] = "green"
Parcourir les clés et les valeurs à l'aide de la méthode items() :
pythonfor fruit, color in fruit_colors.items():
print(f"{fruit} is {color}")
Fonctions du dictionnaire
LesDictionaries (dict) stockent les données sous forme de paires clé-valeur.
Python fournit des méthodes telles que .keys() et .values()
pour accéder aux clés et aux valeurs séparément.
Accès aux clés
pythonperson = {"name": "Alice", "age": 25, "city": "Zurich"}
print(person.keys()) # dict_keys(['name', 'age', 'city'])
# Loop through keys
for key in person.keys():
print("Key:", key)
Accès aux valeurs
pythonprint(person.values()) # dict_values(['Alice', 25, 'Zurich'])
# Loop through values
for value in person.values():
print("Value:", value)
Utiliser ensemble des clés et des valeurs
python# Often combined with a for-loop
for key in person.keys():
print(key, "->", person[key])
Pièges courants
.keys()et.values()renvoient des vues spéciales, pas des listes normales. Si vous avez besoin d'une liste, enveloppez-la aveclist().- Les dictionnaires ne sont pas ordonnés avant Python 3.7. Dans Python moderne, ils conservent l'ordre d'insertion.
Python’s built-in collections module provides specialized dictionary subclasses—defaultdict, Counter, and OrderedDict—that eliminate boilerplate code and optimize performance for complex data aggregation tasks.
The `defaultdict` Advantage
Standard dictionaries raise a KeyError when accessing a missing key, requiring repetitive dict.get() or if key not in dict checks. A defaultdict accepts a callable factory function that initializes missing keys automatically.
pythonfrom collections import defaultdict
# Grouping items by category without manual key existence checks
raw_data = [("fruit", "apple"), ("vegetable", "carrot"), ("fruit", "banana"), ("vegetable", "broccoli")]
# defaultdict(list) initializes missing keys with an empty list
categorized = defaultdict(list)
for category, item in raw_data:
categorized[category].append(item)
print(dict(categorized))
Expected Output
```python {'fruit': ['apple', 'banana'], 'vegetable': ['carrot', 'broccoli']} ```Frequency Counting with `Counter`
Counter is a dictionary subclass designed for counting hashable objects. It replaces manual looping and conditional increment logic with an optimized, highly readable API.
pythonfrom collections import Counter
access_logs = ["IP_1", "IP_2", "IP_1", "IP_3", "IP_2", "IP_1"]
ip_counts = Counter(access_logs)
# Find the 2 most common IP addresses
print(ip_counts.most_common(2))
# Mathematical operations across counters
other_logs = ["IP_1", "IP_4"]
ip_counts.update(other_logs)
print(ip_counts["IP_1"])
Expected Output
```python [('IP_1', 3), ('IP_2', 2)] 4 ```Preserving Insertion Order and Beyond with `OrderedDict`
While standard dictionaries have guaranteed insertion order as of Python 3.7+, OrderedDict remembers the order entries were added and provides specialized methods like move_to_end(), making it ideal for custom LRU (Least Recently Used) caches.
pythonfrom collections import OrderedDict
# Creating an LRU cache tracking mechanism
cache = OrderedDict()
cache["a"] = 1
cache["b"] = 2
# Access or update pushes item to the end
cache.move_to_end("a")
cache["c"] = 3
print(list(cache.keys()))
Expected Output
```python ['b', 'a', 'c'] ```Performance Considerations and Gotchas
- Factory Mutability in
defaultdict: Never pass a mutable object directly (e.g.,defaultdict(list)is correct, butdefaultdict([])shares a single list reference across all missing keys, causing bugs). - Memory Overhead: Specialized mapping types carry minor overhead compared to native dicts due to extra methods and internal tracking structures. Use them only when their specific algorithmic benefits apply.
- Equality Comparisons:
OrderedDictconsiders order when comparing two dictionaries; standarddictequality ignores order.
Key Takeaways
- Use
defaultdictto supply a default factory (likelist,int, orset) and eliminateKeyErrorchecks during aggregation. - Use
Counterfor rapid frequency analysis and multiset mathematical operations. - Use
OrderedDictwhen your algorithm explicitly relies on reordering keys or explicit position manipulation (such as custom caching layers).
Conditions : if, elif et else
Les instructions conditionnelles en Python vous permettent d'exécuter des blocs de code selon qu'une condition est vraie ou fausse. La structure de base utilise if, suivi éventuellement de elif (else if) et else pour la solution de secours.
1. Instruction if de base
Utilisez l'instruction if pour exécuter du code uniquement lorsqu'une condition est remplie :
pythonx = 10
if x > 5:
print("x is greater than 5")
# Outputs: x is greater than 5
2. Déclaration if-else
Inclure un bloc else pour exécuter du code lorsque la condition n'est pas remplie :
pythonx = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
# Outputs: x is not greater than 5
3. if-elif-else Chaîne
Pour plusieurs conditions, utilisez elif pour vérifier des conditions supplémentaires :
pythonx = 5
if x > 5:
print("x is greater than 5")
elif x == 5:
print("x is exactly 5")
else:
print("x is less than 5")
# Outputs: x is exactly 5
Ces constructions vous permettent de créer des structures de prise de décision robustes dans vos programmes Python.
for-loop (Bases)
Une boucle for en Python répète le code pour chaque élément d'une séquence (comme une liste, une chaîne ou une plage de nombres).
Contrairement à while, le nombre de répétitions est généralement connu à l'avance.
Comptage avec range()
pythonfor i in range(5):
print("Number:", i)
# Prints 0, 1, 2, 3, 4
range(5) génère des nombres de 0 à (mais non compris) 5.
Parcourir une liste
pythonfruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)
La boucle visite chaque élément de la liste un par un.
Faire une boucle dans une chaîne
pythonword = "hi!"
for char in word:
print(char)
# Prints h, i, !
Utilisation de break et continue
pythonfor num in range(1, 6):
if num == 3:
continue # skip number 3
if num == 5:
break # stop the loop completely
print(num)
# Prints 1, 2, 4
Pièges courants
- Erreurs ponctuelles : N'oubliez pas que
range(n)s'arrête avantn. - Oublier que
invérifie les éléments :pour x dans la listedonne des éléments, pas des index. - Mélange
breaketcontinue:breaktermine la boucle,continuesaute uniquement l'étape en cours.
while-loop (Bases)
Une boucle while répète un bloc de code tant que sa condition est True.
Contrairement aux boucles for, le nombre de répétitions n'est pas fixé à l'avance.
La condition est vérifiée avant chaque répétition.
Important : Soyez prudent avec l'état. S'il ne devient jamais False,
la boucle s'exécutera pour toujours (une boucle infinie).
Exemple de comptage simple
pythonx = 0
while x < 5:
print("Counted to:", x)
x += 1 # Important: update the counter!
Cette boucle commence à x = 0 et s'arrête une fois que x n'est plus inférieur à 5.
Arrêter tôt avec break
pythonx = 10
while True: # runs "forever" unless stopped
if x % 7 == 0:
print("Found a multiple of 7:", x)
break # exit the loop
x += 1
Ici, nous utilisons while True mais nous nous échappons avec break une fois qu'une condition est remplie.
Saut d'itérations avec continue
pythonx = -3
while x <= 3:
x += 1
if x == 0: # skip division by zero
continue
print("1/", x, "=", 1/x)
L'instruction continue ignore l'étape de boucle actuelle et passe à la suivante.
Pièges de base
- Oubli de mettre à jour la variable :
Si
x += 1est manquant, la condition ne change jamais, et la boucle s'exécute pour toujours. - Conditions trop générales :
while Truen'est sûr que si vous incluez unbreak. approprié
Instructions de contrôle de boucle : break, continue et pass
Python fournit des instructions spéciales qui modifient le flux normal des boucles. Ils sont utiles pour un contrôle précis des itérations, pour gérer les cas exceptionnels et pour rendre le code plus expressif.
break — Sortie d'une boucle
break termine immédiatement la boucle englobante la plus proche, quelle que soit l'état de la boucle. Il est couramment utilisé lorsqu'une condition cible est remplie et qu'aucune autre itération n'est nécessaire.
pythonnums = [1, 4, 7, 10]
for n in nums:
if n > 5:
print(f"Found {n}, stopping loop.")
break
# Only iterates until 7, then exits
continue — Sauter une itération
continue ignore le reste de l'itération en cours et passe directement à la suivante. Il est souvent utilisé pour filtrer les cas indésirables.
pythonfor n in range(5):
if n % 2 == 0:
continue
print(f"Odd: {n}")
# Prints Odd: 1, 3
pass — Déclaration d'espace réservé
pass ne fait rien et agit comme un espace réservé syntaxique. Ceci est utile lorsqu'un bloc de code est requis syntaxiquement mais qu'aucune action ne doit encore être entreprise (par exemple, pendant le développement ou dans les méthodes de classe abstraite).
pythonfor n in range(3):
if n == 1:
pass # Placeholder for future logic
else:
print(n)
# Prints 0 and 2, does nothing on 1
```<h2 class="error">Pièges courants</h2>
<ul>
<li><strong>Confondre <code>break</code> avec <code>return</code>:</strong> <code>break</code> quitte uniquement la boucle, pas la fonction. Utilisez <code>return</code> pour quitter complètement une fonction.</li>
<li><strong>Boucles infinies avec <code>continue</code>:</strong> Dans les boucles <code>while</code>, placer <code>continue</code> avant de mettre à jour les variables de boucle peut empêcher la condition de se produire. changer.</li>
<li><strong>Une utilisation abusive de <code>pass</code>:</strong> Étant donné que <code>pass</code> ne fait rien, le laisser involontairement dans le code de production peut masquer une logique manquante ou des bogues.</li>
</ul>
<h2>Comparaison rapide</h2>
<ul>
<li><code>break</code> : quittez complètement la boucle.</li>
<li><code>continue</code> : passer à l'itération suivante.</li>
<li><code>pass</code> : ne rien faire, espace réservé uniquement.</li>
</ul>
Boucles imbriquées
Les boucles imbriquées sont des boucles à l'intérieur des boucles. La boucle externe s'exécute une fois pour chaque itération de la boucle interne, multipliant le nombre total d'itérations. Ils sont essentiels pour travailler avec des données multidimensionnelles, des problèmes combinatoires et algorithmiques.
Produit cartésien
pythoncolors = ["red", "blue"]
sizes = ["S", "M", "L"]
for color in colors:
for size in sizes:
print(color, size)
Imbriqué while
pythoni = 1
while i <= 3:
j = 1
while j <= 2:
print(i, j)
j += 1
i += 1
Pièges
Explosion de complexité : Deux boucles imbriquées sur n éléments entraînent chacune une complexité O(n²). L'ajout de niveaux supplémentaires augmente considérablement la durée d'exécution.
Observation de variables : La réutilisation accidentelle des noms de variables dans les boucles internes et externes peut remplacer les valeurs de manière inattendue.
Comprehensions and generator expressions provide a declarative, highly optimized syntax in Python to construct collections and stream data without verbose boilerplate loops.
Comprehensions: Lists, Dictionaries, and Sets
Traditional for loops require manual initialization and mutation of collections. Comprehensions execute this logic in C under the hood, yielding faster execution and cleaner readability.
python# Traditional approach
squares_traditional = []
for x in range(5):
if x % 2 == 0:
squares_traditional.append(x**2)
# List Comprehension (Expression, Iteration, Optional Condition)
squares = [x**2 for x in range(5) if x % 2 == 0]
# Dictionary Comprehension
square_map = {x: x**2 for x in range(5)}
# Set Comprehension (drops duplicates)
unique_lengths = {len(word) for word in ["apple", "bat", "apple", "car"]}
print(squares) # [0, 4, 16]
print(square_map) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
print(unique_lengths) # {3, 5}
Conditional Logic Placement
The placement of the if statement changes based on whether you are filtering items or transforming values conditionally.
python# Filtering (goes at the END)
evens = [x for x in range(10) if x % 2 == 0]
# Conditional Transformation (ternary goes BEFORE the loop)
labeled = ["even" if x % 2 == 0 else "odd" for x in range(5)]
Generator Expressions for Memory Efficiency
List comprehensions compute and store every element in memory simultaneously. If you only need to iterate over a sequence once, use a generator expression (using parentheses ()) to evaluate items lazily on demand.
import
# List comprehension: Allocates entire list in RAM
list_comp = [x**2 for x in range(1000000)]
# Generator expression: Allocates an iterator footprint only
gen_expr = (x**2 for x in range(1000000))
print(f"List size: {sys.getsizeof(list_comp)} bytes")
print(f"Gen size: {sys.getsizeof(gen_expr)} bytes")
# Consuming the generator lazily
print(next(gen_expr)) # 0
print(next(gen_expr)) # 1
Expected Output:
textList size: 8448728 bytes
Gen size: 200 bytes
0
1
Performance & Readability Edge Cases
- Readability Limit: Avoid multi-nested comprehensions (e.g., matrix flattening with two loops and conditions). If it spans more than two lines or requires deep nesting, fall back to a readable
forloop. - Variable Leakage: Unlike Python 2, Python 3 list comprehensions have their own local scope, preventing loop variables from leaking into the surrounding namespace. However, generator expressions handle scoping slightly differently regarding late-binding closures.
Key Takeaways
- Comprehensions streamline list, dict, and set creation with C-optimized performance.
- Filters (`if`) go at the end of a comprehension, while conditional expressions (`X if cond else Y`) go before the `for` keyword.
- Generator expressions replace square brackets with parentheses to process large datasets lazily with minimal memory overhead.
- Prioritize readability: if a comprehension becomes excessively complex, refactor it into a standard loop or helper function.
Fonctions et expressions Lambda
Les fonctions en Python sont définies à l'aide du mot-clé def et vous permettent d'encapsuler du code pour le réutiliser. De plus, les expressions lambda fournissent un raccourci pour créer de petites fonctions anonymes.
1. Définir des fonctions
Utilisez def pour définir une fonction, éventuellement avec des paramètres :
pythondef greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
# Outputs: Hello, Alice!
2. Fonctions Lambda
Les expressions Lambda créent de petites fonctions anonymes. Ils sont utiles pour les fonctions courtes et simples :
python# A lambda that adds two numbers
add = lambda a, b: a + b
print(add(3, 4)) # Outputs: 7
Les fonctions régulières et les expressions lambda sont des outils essentiels pour organiser et simplifier votre code.
Function decorators leverage Python’s first-class functions to transparently modify or enhance the behavior of existing functions or methods without permanently changing their source code.
First-Class Functions and Closures
In Python, functions are first-class citizens. They can be assigned to variables, stored in data structures, passed as arguments, and returned from other functions. A decorator is fundamentally a callable that accepts a function as input, creates a new inner wrapper function that executes additional logic, and returns that wrapper.
pythonfrom typing import Callable, Any
def logger(func: Callable[..., Any]) -> Callable[..., Any]:
def wrapper(*args: Any, **kwargs: Any) -> Any:
print(f"Calling '{func.__name__}' with args: {args}, kwargs: {kwargs}")
result = func(*args, **kwargs)
print(f"'{func.__name__}' returned: {result}")
return result
return wrapper
@logger
def add(a: int, b: int) -> int:
return a + b
# Equivalent to: add = logger(add)
The @logger syntactic sugar is merely application-time shorthand for reassigning the function name to the output of the decorator callable.
Preserving Metadata with functools.wraps
When a function is wrapped, it loses its original identity, docstring, and module name because introspection tools (__name__, __doc__) inspect the wrapper function instead. Always use functools.wraps to copy these attributes from the original function to the wrapper.
pythonfrom functools import wraps
from typing import Callable, Any
def strict_types(func: Callable[..., Any]) -> Callable[..., Any]:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
# Pre-execution validation logic could live here
return func(*args, **kwargs)
return wrapper
@strict_types
def multiply(x: int, y: int) -> int:
"""Multiplies two integers together."""
return x * y
print(multiply.__name__) # Output: multiply
print(multiply.__doc__) # Output: Multiplies two integers together.
Omitting functools.wraps breaks documentation generators, dependency injection containers, and routing frameworks that rely strictly on function metadata.
Decorators That Take Arguments
To pass arguments to a decorator, you must write a decorator factory—an outer function that accepts your configuration parameters and returns the actual decorator, requiring a three-tier nested function structure.
pythonfrom functools import wraps
import time
from typing import Callable, Any
def repeat(num_times: int) -> Callable[[Callable[..., Any]], Callable[..., Any]]:
def decorator_repeat(func: Callable[..., Any]) -> Callable[..., Any]:
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
for _ in range(num_times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator_repeat
@repeat(num_times=3)
def greet(name: str) -> None:
print(f"Hello, {name}!")
greet("Alice")
Expected Output
textHello, Alice!
Hello, Alice!
Hello, Alice!
Common Gotchas and Edge Cases
- Signature Alteration: Simple wrappers accept
*argsand**kwargs, which can mask type hints from static analyzers like Mypy. UseParamSpecandTypeVarfrom thetypingmodule for advanced, type-safe decorators. - Execution Order: When stacking multiple decorators, they execute from bottom to top (closest to the function definition first), but the wrapping occurs from top to bottom.
@dec1over@dec2meansdec1(dec2(func)).
Key Takeaways
- Functions are first-class objects in Python, making them valid inputs and outputs for other functions.
- Always apply
@functools.wraps(func)to inner wrapper functions to preserve function metadata and docstrings. - Decorators that accept arguments require a factory function enclosing the actual decorator and wrapper.
- Stacked decorators execute bottom-up relative to their visual position on the target function.
Python’s functools module provides high-order functions and operations on callable objects, bridging imperative logic with functional paradigms. Mastering partial, singledispatch, and lru_cache allows you to write cleaner, faster, and more modular code without boilerplates.
Partial Application with `functools.partial`
Partial application freezes a portion of a function’s arguments, creating a new callable with fewer parameters. This is especially useful for configuration injection, callback handlers, and functional pipelines.
pythonfrom functools import partial
def api_request(method: str, timeout: int, retries: int, endpoint: str) -> str:
return f"[{method}] {endpoint} (timeout={timeout}s, retries={retries})"
# Freeze configuration parameters
get_user_request = partial(api_request, "GET", timeout=5, retries=3)
# Later in the codebase, supply only the remaining parameter
print(get_user_request("/users/42"))
Expected Output
```text [GET] /users/42 (timeout=5s, retries=3) ```partial constructs a new object retaining attributes of the original function. However, note that partial objects do not support assignment of arbitrary attributes, and arguments are bound positionally or by keyword at call time, overriding defaults where necessary.
Polymorphism via `functools.singledispatch`
Python lacks built-in method overloading based on argument types. singledispatch transforms a regular function into a generic function, dispatching implementation behavior dynamically based on the type of its first argument.
pythonfrom functools import singledispatch
@singledispatch
def serialize(data) -> str:
raise TypeError(f"Cannot serialize type {type(data)}")
@serialize.register
def _(data: int) -> str:
return f"<integer>{data}</integer>"
@serialize.register
def _(data: list) -> str:
items = "".join(serialize(item) for item in data)
return f"<list>{items}</list>"
print(serialize(100))
print(serialize([10, 20]))
Expected Output
```textTo dispatch on types other than the first argument or multiple arguments, look toward third-party libraries like multipledispatch, but singledispatch handles standard single-argument polymorphism efficiently out of the box.
Performance Optimization with `functools.lru_cache`
Pure functions with deterministic outputs benefit from memoization. The @lru_cache decorator wraps a function with a memoizing callable that saves up to maxsize recent calls, trading memory for execution speed.
pythonfrom functools import lru_cache
import time
@lru_cache(maxsize=128)
def expensive_computation(n: int) -> int:
# Simulate heavy workload
if n < 2:
return n
return expensive_computation(n - 1) + expensive_computation(n - 2)
start = time.perf_counter()
print(expensive_computation(35))
print(f"Time taken: {time.perf_counter() - start:.6f}s")
# Check cache metrics
print(expensive_computation.cache_info())
Expected Output
```text 9227465 Time taken: 0.000042s CacheInfo(hits=33, misses=36, maxsize=128, currsize=36) ```Gotchas and Best Practices
- Hashability: Arguments passed to an `lru_cache` decorated function must be hashable. Passing lists or dicts will raise a `TypeError`. Use tuples instead of lists for cacheable inputs.
- Memory Leaks: If applied to methods on long-lived objects, `lru_cache` stores strong references to `self`, preventing garbage collection of the instance unless managed carefully.
Key Takeaways
- Use `functools.partial` to reduce repetitive argument passing and adapt functions for callback APIs.
- Leverage `functools.singledispatch` for clean, extensible type-based polymorphism without bloated `isinstance` type-checking chains.
- Apply `functools.lru_cache` on pure, deterministic functions to accelerate compute-heavy operations, ensuring all parameters are hashable.
Python data classes reduce boilerplate by automatically generating special methods like __init__, __repr__, and __eq__ based on typed attributes.
The Anatomy of @dataclass
The @dataclass decorator inspects type annotations to synthesize boilerplate methods, transforming plain classes into efficient data containers.
pythonfrom dataclasses import dataclass
@dataclass
class ServerNode:
host: str
port: int
active: bool = True
# Automatic __init__, __repr__, and __eq__ are generated
node1 = ServerNode("127.0.0.1", 8080)
node2 = ServerNode(host="127.0.0.1", port=8080, active=True)
print(node1)
print(node1 == node2)
Expected Output:
textServerNode(host='127.0.0.1', port=8080, active=True)
True
Handling Mutable Defaults with field()
Never use mutable defaults like lists or dicts directly in data classes, as they share references across all instances. Use field(default_factory=...) instead.
pythonfrom dataclasses import dataclass, field
@dataclass
class Cluster:
name: str
# Incorrect: nodes: list[str] = [] (Shares list across instances!)
nodes: list[str] = field(default_factory=list)
c1 = Cluster("prod")
c1.nodes.append("node-1")
c2 = Cluster("staging")
print(c2.nodes) # Safely empty, not contaminated by c1
Expected Output:
text[]
Enforcing Immutability and Performance
Pass frozen=True to the decorator to make instances immutable and hashable, allowing them to be used as dictionary keys or set elements.
pythonfrom dataclasses import dataclass
@dataclass(frozen=True)
class Coordinate:
x: float
y: float
coord = Coordinate(10.5, 20.1)
try:
coord.x = 15.0
except AttributeError as e:
print(f"Caught error: {e}")
Expected Output:
textCaught error: cannot assign to field 'x'
Gotchas & Edge Cases
- Field Ordering: Non-default fields cannot follow default fields. If
port: int = 80comes beforehost: str, Python raises aTypeError. - Type Checking vs Runtime: Type annotations on data classes are not strictly enforced at runtime by default; they serve as metadata. Use runtime validation tools like
pydanticif strict validation is required. __post_init__: Use the__post_init__method for validation or derived fields that depend on initialized attributes.
python@dataclass
class Rectangle:
width: float
height: float
area: float = field(init=False)
def __post_init__(self):
# Calculate derived field after __init__ runs
object.__setattr__(self, 'area', self.width * self.height)
Key Takeaways
- Use
@dataclassto eliminate manual__init__,__repr__, and comparison boilerplate. - Always use
field(default_factory=...)for mutable types like lists and dictionaries. - Set
frozen=Truefor immutable, hashable data structures that double as dictionary keys. - Use
__post_init__for cross-field validation or computing derived attributes.
Metaclasses are the “classes of classes,” enabling you to intercept and programmatically modify class creation before they are instantiated in memory.
Understanding the Object Model
In Python, everything is an object, including classes themselves. An ordinary instance is created by a class; similarly, a class instance is created by a metaclass. By default, the metaclass for all standard classes is type.
When the Python interpreter reads a class statement, it executes the body in a local namespace and then calls the metaclass with three arguments: name, bases, and namespace.
pythonclass Meta(type):
def __new__(mcs, name, bases, namespace):
print(f"Creating class: {name}")
# Intercept and modify the class namespace
namespace["enforced_attribute"] = 42
return super().__new__(mcs, name, bases, namespace)
class MyClass(metaclass=Meta):
pass
print(MyClass.enforced_attribute)
Expected Output
```text Creating class: MyClass 42 ```Practical Application: API Registration and Validation
Metaclasses are rarely needed for standard business logic, but they are immensely powerful for framework design, such as automatic plugin registration or enforcing architectural constraints.
pythonclass RegistryMeta(type):
registry = {}
def __new__(mcs, name, bases, namespace):
# Prevent registration of the base plugin class itself
if name != "Plugin":
if "run" not in namespace:
raise TypeError(f"Plugin {name} must implement a 'run' method.")
mcs.registry[name] = namespace
return super().__new__(mcs, name, bases, namespace)
class Plugin(metaclass=RegistryMeta):
pass
class AudioPlugin(Plugin):
def run(self):
return "Playing audio..."
try:
class BrokenPlugin(Plugin):
pass
except TypeError as e:
print(e)
print("Registered plugins:", list(RegistryMeta.registry.keys()))
Expected Output
```text Plugin BrokenPlugin must implement a 'run' method. Registered plugins: ['AudioPlugin'] ```Metaclasses vs. Class Decorators
Before reaching for a metaclass, consider whether a class decorator can solve your problem. Class decorators are easier to read and maintain for simple modifications.
- Use Class Decorators when you only need to modify or augment an existing class after it has been created.
- Use Metaclasses when you need to control class creation downstream (such as ensuring subclasses inherit behavior, modifying the class dictionary before creation, or enforcing strict base-class structures across large hierarchies).
Edge Cases and Performance Considerations
- Inheritance Rules: If a class specifies a metaclass, all its subclasses will inherit that metaclass. If multiple base classes are used, Python resolves the metaclass via Metaclass Conflict resolution (the metaclass must be a strict subclass of all its bases’ metaclasses).
- Performance: Metaclass hooks (
__new__and__init__) run exactly once per class definition at import/load time, not during instantiation. Therefore, they impose zero runtime overhead on standard object instantiation.
Key Takeaways
- Metaclasses are instantiated by subclassing
typeand overriding__new__or__init__. - Python invokes the metaclass during class definition time, passing
name,bases, andnamespace. - Use metaclasses for validation, automatic registration, and architectural enforcement across class hierarchies.
- Prefer class decorators for lightweight, isolated class modifications.
The descriptor protocol (__get__, __set__, and __delete__) is the underlying mechanism that powers Python properties, methods, static methods, and class methods, allowing you to intercept and customize low-level attribute access. By implementing these methods, you gain precise control over validation, state mutation, and lazy evaluation at the class level rather than the instance level.
Implementing the Descriptor Protocol
A descriptor is any object that defines at least one of the descriptor methods. When an attribute is accessed on an instance, Python’s attribute lookup checks the class of the object for a descriptor before falling back to the instance dictionary (__dict__).
pythonclass ValidatedString:
def __init__(self, min_length: int = 0):
self.min_length = min_length
self._name = ""
def __set_name__(self, owner, name):
# Automatically capture the attribute name assigned in the owner class
self._name = name
def __get__(self, instance, owner):
if instance is None:
return self # Accessed via the class, return the descriptor itself
return instance.__dict__.get(self._name, None)
def __set__(self, instance, value):
if not isinstance(value, str):
raise TypeError(f"'{self._name}' must be a string")
if len(value) < self.min_length:
raise ValueError(f"'{self._name}' must be at least {self.min_length} chars")
instance.__dict__[self._name] = value
class UserProfile:
username = ValidatedString(min_length=3)
email = ValidatedString(min_length=5)
def __init__(self, username: str, email: str):
self.username = username
self.email = email
Data descriptors (those implementing both __get__ and __set__) take precedence over instance dictionary entries. Non-data descriptors (implementing only __get__, such as functions) can be shadowed by instance dictionary keys.
Lazy Evaluation with Descriptors
You can use non-data or data descriptors to implement lazy evaluation, computing a resource-heavy attribute only once and caching it directly on the instance dictionary to bypass subsequent descriptor lookups.
pythonclass CachedProperty:
def __init__(self, compute_func):
self.compute_func = compute_func
self.__doc__ = compute_func.__doc__
self._name = ""
def __set_name__(self, owner, name):
self._name = name
def __get__(self, instance, owner):
if instance is None:
return self
# Compute value
value = self.compute_func(instance)
# Cache the value on the instance dictionary using the same attribute name.
# Because instance dictionaries override non-data descriptors, subsequent
# lookups will hit instance.__dict__[self._name] directly, bypassing __get__.
instance.__dict__[self._name] = value
return value
class DataModel:
@CachedProperty
def heavy_computation(self):
print("Executing expensive calculation...")
return sum(i**2 for i in range(1_000_000))
Expected Output and Execution
python# Validation behavior
user = UserProfile("alice", "alice@example.com")
print(user.username) # alice
try:
user.username = "al" # Too short
except ValueError as e:
print(e) # 'username' must be at least 3 chars
# Lazy evaluation behavior
model = DataModel()
print(model.__dict__) # {} (not computed yet)
print(model.heavy_computation) # Executes expensive calculation... -> 333332833333500000
print(model.heavy_computation) # Fetches directly from __dict__ without printing message
Gotchas and Performance Considerations
- Instance vs. Class Access: Always handle
instance is Nonein__get__. When an attribute is accessed on the class (e.g.,UserProfile.username),instanceis passed asNone. - Memory Leaks: Storing state inside the descriptor instance itself (e.g.,
self._value = valueinside__set__) shares that state across all instances of the owner class, leading to bugs. Always store instance-specific state within theinstance.__dict__or passinstancereferences carefully using aWeakKeyDictionary. __set_name__Availability: Introduced in Python 3.6,__set_name__eliminates the boilerplate of manually passing string names into descriptor initializers. Always use it to capture the attribute name.
Key Takeaways
- Descriptors intercept attribute access (
__get__,__set__,__delete__) at the class level, providing the foundation for properties and validation frameworks. - Data descriptors (defining
__set__) override instance dictionary entries, whereas non-data descriptors (defining only__get__) can be shadowed by instance attributes. - Caching values in
instance.__dict__via non-data descriptors is the standard idiom for implementing efficient lazy evaluation. - Use
__set_name__to automatically register field names without manual string duplication.
Robust applications anticipate runtime failures by gracefully intercepting exceptions, maintaining clean resource states, and bubbling up domain-specific errors when assumptions break.
Catching Specific Exceptions and Using Else
Never use bare except: clauses; they catch system exits, keyboard interrupts, and memory errors, masking bugs. Always target specific exception classes. The else block executes only if the try block completes with zero exceptions, separating core logic from error handlers.
pythondef parse_temperature(data: dict, key: str) -> float:
try:
raw_value = data[key]
celsius = float(raw_value)
except KeyError:
print(f"Error: Missing key '{key}' in data payload.")
raise
except ValueError:
print(f"Error: Value '{data[key]}' cannot be parsed as a float.")
return 0.0
else:
# Executes only if try succeeds entirely
return (celsius * 9/5) + 32
# Try It Yourself
print(parse_temperature({"temp": "25.5"}, "temp"))
print(parse_temperature({"temp": "invalid"}, "temp"))
Expected Output
```text 77.3 Error: Value 'invalid' cannot be parsed as a float. 0.0 ```The Guarantee of Finally and Custom Exceptions
The finally block guarantees execution regardless of whether an exception occurred, was caught, or if a return statement was hit early. This makes it ideal for cleanup tasks like closing sockets or file handles. Furthermore, custom exceptions should inherit from Python’s built-in Exception (or a base domain exception) to provide precise error context.
pythonclass InsufficientFundsError(Exception):
"""Raised when an account balance cannot cover the withdrawal."""
def __init__(self, balance: float, amount: float):
super().__init__(f"Attempted to withdraw {amount}, but balance is only {balance}")
self.balance = balance
self.amount = amount
class BankAccount:
def __init__(self, balance: float):
self._balance = balance
def withdraw(self, amount: float) -> None:
print("Transaction processing initiated...")
try:
if amount > self._balance:
raise InsufficientFundsError(self._balance, amount)
self._balance -= amount
print(f"Successfully withdrew {amount}. New balance: {self._balance}")
finally:
print("Transaction audit log: Closed.\n")
# Try It Yourself
account = BankAccount(100.0)
try:
account.withdraw(150.0)
except InsufficientFundsError as e:
print(f"Caught custom exception: {e}")
Expected Output
```text Transaction processing initiated... Transaction audit log: Closed.Caught custom exception: Attempted to withdraw 150.0, but balance is only 100.0
<h2>Resource Management via Context Managers</h2>
Instead of manually managing `try...finally` blocks to close resources, use context managers via the `with` statement. They implement the Context Manager protocol (`__enter__` and `__exit__`), ensuring cleanup occurs even if exceptions crash the block.
```python
from contextlib import contextmanager
import sqlite3
# Custom context manager using generator syntax
@contextmanager
def managed_cursor(connection: sqlite3.Connection):
cursor = connection.cursor()
try:
yield cursor
connection.commit()
except Exception:
connection.rollback()
raise
finally:
cursor.close()
# Usage with an in-memory SQLite database
conn = sqlite3.connect(":memory:")
try:
with managed_cursor(conn) as cur:
cur.execute("CREATE TABLE users (name TEXT)")
cur.execute("INSERT INTO users VALUES ('Alice')")
# Uncommenting below line triggers automatic rollback
# raise RuntimeError("Database corruption detected!")
print("Transaction committed successfully.")
except RuntimeError as err:
print(f"Caught: {err}")
finally:
conn.close()
Key Takeaways
- Be Specific: Catch precise exceptions (e.g., `KeyError`, `ValueError`) rather than using bare `except:` statements.
- Isolate Logic: Use the `else` block for code that should run only if the `try` block succeeds, keeping handlers lean.
- Guaranteed Cleanup: Rely on `finally` blocks or context managers (`with` statement) to clean up external resources safely.
- Domain-Driven Errors: Subclass `Exception` to create expressive, custom exception types that carry contextual error metrics.
Méthodes de fichiers de base
La fonction intégrée open() renvoie un objet fichier que vous pouvez utiliser pour lire ou écrire dans des fichiers sur le disque.
Le mode détermine les actions autorisées : 'r' (lecture, par défaut), 'w' (écriture, écrasement), 'a' (ajouter).
L'ouverture d'un fichier ne lit ni n'écrit les données en soi - vous devez appeler les méthodes de fichier indiquées ci-dessous. Fermez toujours les fichiers lorsque vous avez terminé (ou, de préférence, utilisez un gestionnaire de contexte).
Modes — exemples rapides
python# implicit read mode (same as 'r')
f = open("example.txt")
f.close()
# explicit read
f = open("example.txt", "r")
f.close()
# open for writing (will overwrite)
f = open("output.txt", "w")
f.write("line 1\n")
f.close()
# open for appending (adds to end)
f = open("output.txt", "a")
f.write("another line\n")
f.close()
.read() — lire l'intégralité du contenu
read() renvoie le reste du fichier sous la forme d'une seule chaîne. S'il est appelé à nouveau alors qu'il est déjà à la fin, il renvoie une chaîne vide.
pythonf = open("notes.txt", "r", encoding="utf-8")
all_text = f.read()
print(len(all_text)) # number of characters read
more = f.read() # already at EOF → returns ''
print(repr(more)) # shows ''
f.close()
.readline() — lire la ligne suivante
readline() renvoie la ligne suivante (y compris la nouvelle ligne de fin si elle est présente).
L'appeler à plusieurs reprises avance dans le fichier. Un argument size (par exemple, readline(50)) limite le nombre de caractères renvoyés — il ne pas sélectionne la « nième ligne ».
pythonf = open("notes.txt", "r", encoding="utf-8")
first = f.readline()
second = f.readline()
print("First:", first)
print("Second:", second)
# to get the 3rd line specifically, iterate 3 times or use itertools.islice
f.close()
```<h2><span style="font-family: Roboto;">.readlines() — récupère toutes les lignes sous forme de liste</span></h2>
<p><span style="font-family: Roboto;">
<code>readlines()</code> renvoie une liste où chaque élément correspond à une ligne du fichier (y compris les caractères de nouvelle ligne). À utiliser avec précaution sur des fichiers très volumineux.
</span></p>
```python
f = open("notes.txt", "r", encoding="utf-8")
lines = f.readlines()
print("Number of lines:", len(lines))
print("Line 0:", lines[0])
f.close()
.write() — écrit des chaînes dans un fichier
write() nécessite une chaîne. Convertissez d'autres types avec str(). Le comportement (écraser ou ajouter) dépend du mode utilisé lors de l'ouverture du fichier.
python# overwrite file
f = open("results.txt", "w", encoding="utf-8")
f.write("score: " + str(42) + "\n")
f.close()
# append
f = open("results.txt", "a", encoding="utf-8")
f.write("score: " + str(100) + "\n")
f.close()
.close() et bonnes pratiques
close() libère le descripteur de fichier et garantit que les données mises en mémoire tampon sont vidées sur le disque. Oublier de fermer peut bloquer d'autres programmes ou perdre des données. Le modèle recommandé est le gestionnaire de contexte qui se ferme automatiquement.
python# manual close (works but easy to forget on errors)
f = open("data.txt", "r", encoding="utf-8")
try:
content = f.read()
finally:
f.close()
# preferred: context manager (automatic close)
with open("data.txt", "r", encoding="utf-8") as f:
for line in f:
process(line.rstrip("\n"))
# file is closed here automatically
Petits exemples pratiques
python# Example: copy a file line-by-line (memory-friendly)
with open("source.txt", "r", encoding="utf-8") as src, \
open("copy.txt", "w", encoding="utf-8") as dst:
for line in src:
dst.write(line)
# Example: read the 3rd line safely
from itertools import islice
with open("notes.txt", "r", encoding="utf-8") as f:
third_line = next(islice(f, 2, 3), "") # returns "" if missing
```<h2><span style="font-family: Roboto;">Erreurs courantes et solutions rapides</span></h2>
<ul>
<li><span style="font-family: Roboto;"><strong>FileNotFoundError</strong> : vérifiez le chemin ou utilisez un chemin absolu.</span></li>
<li><span style="font-family: Roboto;"><strong>PermissionError</strong> : assurez-vous que vous disposez des autorisations d'écriture/lecture pour le dossier cible.</span></li>
<li><span style="font-family: Roboto;"><strong>UnicodeDecodeError</strong> : spécifiez le <code>encoding</code> correct (par exemple, <code>"utf-8"</code>, <code>"latin-1"</code>) ou ouvrir en mode binaire <code>"rb"</code> pour les octets bruts.</span></li>
</ul>
Standard thread-local storage fails in asynchronous applications because multiple coroutines share a single thread. Python’s contextvars module provides asynchronous task-local state, which can be cleanly managed using custom context managers built with contextlib.asynccontextmanager.
The Problem with Thread-Local State in AsyncIO
When using threading.local(), state is bound to the operating system thread. In an asyncio event loop, hundreds of concurrent tasks can run on a single thread. If Task A and Task B modify a thread-local variable, they will overwrite each other’s data.
contextvars.ContextVar solves this by binding state to the execution context of the current logical task rather than the physical thread.
Implementing Async Task-Local State
The following example demonstrates how to encapsulate a ContextVar within an asynchronous context manager to manage request IDs safely across concurrent tasks without explicit parameter passing.
pythonimport asyncio
from contextvars import ContextVar
from contextlib import asynccontextmanager
# Define a context variable with a default value
request_id_var: ContextVar[str] = ContextVar("request_id", default="<no-request>")
@asynccontextmanager
async def set_request_context(request_id: str):
# Set the token to allow resetting the context upon exit
token = request_id_var.set(request_id)
try:
yield
finally:
# Restore the previous context state
request_id_var.reset(token)
async def handle_request(name: str, delay: float):
async with set_request_context(f"req-{name}"):
print(f"[{request_id_var.get()}] Started processing")
await asyncio.sleep(delay)
print(f"[{request_id_var.get()}] Finished processing")
async def main():
# Run concurrent tasks sharing the same thread but isolated contexts
await asyncio.gather(
handle_request("A", 0.2),
handle_request("B", 0.1),
)
if __name__ == "__main__":
asyncio.run(main())
Expected Output
text[req-A] Started processing
[req-B] Started processing
[req-B] Finished processing
[req-A] Finished processing
Notice how req-A and req-B maintain their distinct values throughout their respective lifecycles, even though their execution overlaps on the same thread.
Gotchas and Edge Cases
- Task Forking: When using
asyncio.create_task(), the child task automatically shallow-copies the current context. Mutations inside the child task do not affect the parent task. However, shared mutable objects (like adictorlist) stored inside aContextVarare still shared references. Always store immutable data or create defensive copies. - Synchronous Callbacks: If an async function calls synchronous code via
loop.run_in_executor(), the context is not automatically propagated to thread pools unless explicitly copied usingcontextvars.copy_context().
Key Takeaways
- Use
contextvars.ContextVarinstead ofthreading.local()for asynchronous concurrency to prevent race conditions between tasks. - Leverage
contextlib.asynccontextmanagerto safely set and reset context variables using standardasync withsyntax. - Always capture and reset tokens using
ContextVar.set()andContextVar.reset()to avoid leaking state across execution contexts. - Remember that context variables isolate references; mutable objects assigned to a context variable remain mutable across spawned tasks.
Importation de modules en Python
Python vous permet d'étendre les fonctionnalités en important des modules (fichiers contenant du code, des fonctions et des classes Python). Les modules peuvent être intégrés, personnalisés ou installés à partir de sources externes (comme PyPI).
1. Syntaxe d'importation de base
Utilisez l'instruction import pour introduire un module dans votre programme.
pythonimport math
print(math.sqrt(16)) # Outputs: 4.0
2. Importation de fonctions ou d'alias spécifiques
Vous pouvez importer des fonctions spécifiques ou renommer des modules pour plus de commodité.
pythonfrom math import pi, sin
print(pi) # Outputs: 3.141592653589793
print(sin(90)) # Uses radians by default
import numpy as np
arr = np.array([1, 2, 3])
print(arr)
```<h2><span style="font-family: Roboto;">3. Modules intégrés couramment utilisés</span></h2>
<p><span style="font-family: Roboto;">Certains des modules intégrés les plus utiles incluent :</span></p>
<ul>
<li><span style="font-family: Roboto;"><code>math</code> → Fonctions mathématiques (sqrt, pi, sin, cos...)</span></li>
<li><span style="font-family: Roboto;"><code>aléatoire</code> → Nombres aléatoires, brassage, choix</span></li>
<li><span style="font-family: Roboto;"><code>datetime</code> → Dates et heures</span></li>
<li><span style="font-family: Roboto;"><code>os</code> → Interactions avec le système d'exploitation (fichiers, répertoires)</span></li>
<li><span style="font-family: Roboto;"><code>sys</code> → Paramètres et fonctions spécifiques au système</span></li>
<li><span style="font-family: Roboto;"><code>json</code> → Travailler avec des données JSON</span></li>
</ul>
<h2><span style="font-family: Roboto;">4. Installation de modules externes</span></h2>
<p><span style="font-family: Roboto;">
De nombreux modules populaires ne sont pas intégrés et doivent être installés via <code>pip</code> (le gestionnaire de packages de Python).
</span></p>
```bash
pip install numpy
pip install requests
pythonimport requests
response = requests.get("https://api.github.com")
print(response.status_code)
```<h2><span style="font-family: Roboto;">5. Résolution des erreurs d'importation</span></h2>
<p><span style="font-family: Roboto;">
Problèmes courants lors de l'importation de modules :
</span></p>
<ul>
<li><span style="font-family: Roboto;"><strong>ModuleNotFoundError</strong> : Le module n'est pas installé.
➝ Correctif : exécutez <code>pip install modulename</code>.</span></li>
<li><span style="font-family: Roboto;"><strong>ImportError</strong> : Une fonction/classe spécifique ne peut pas être importée.
➝ Correctif : consultez la documentation du module pour connaître les noms de fonctions corrects.</span></li>
<li><span style="font-family: Roboto;"><strong>Conflits de versions</strong> : une version de module peut ne pas prendre en charge votre version de Python.
➝ Correction : mise à niveau avec <code>pip install --upgrade modulename</code>.</span></li>
<li><span style="font-family: Roboto;"><strong>Problèmes d'environnement virtuel</strong> : Le module est installé dans un environnement différent.
➝ Correctif : activez le bon environnement avant d'exécuter le script.</span></li>
</ul>
<h2><span style="font-family: Roboto;">6. Vérification des modules installés</span></h2>
```bash
pip list # Shows installed modules
pip show numpy # Details about a specific module
Savoir comment importer et gérer des modules vous permet d'étendre les fonctionnalités de Python bien au-delà de ses fonctionnalités principales.
Modern Python packaging relies on the standardized pyproject.toml configuration file (PEP 621) and build backends like setuptools to replace legacy setup.py scripts. This decoupling ensures consistent, isolated builds and a declarative manifest for project metadata and dependencies.
Project Directory Structure
A robust, modern Python package requires a clear separation between source code, tests, and configuration files. Place your source files inside a src/ directory to prevent accidental imports of local modules during testing.
textmy_awesome_package/
├── .gitignore
├── README.md
├── pyproject.toml
├── src/
│ └── awesome_pkg/
│ ├── __init__.py
│ └── core.py
└── tests/
└── test_core.py
Configuring pyproject.toml
The pyproject.toml file declares the build system requirements and project metadata. Below is a production-ready configuration using setuptools as the build backend.
toml[build-system]
requires = ["setuptools>=68.0.0", "wheel"]
build-backend = "setuptools.build_meta"
[project]
name = "awesome-pkg"
version = "0.1.0"
description = "A high-performance utility package for modern Python."
readme = "README.md"
authors = [
{ name = "Alex Developer", email = "alex@oldlane17.com" }
]
license = { text = "MIT" }
classifiers = [
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.12",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]
requires-python = ">=3.12"
dependencies = [
"requests>=2.31.0",
"pydantic>=2.6.0"
]
[project.optional-dependencies]
dev = [
"pytest>=8.0.0",
"ruff>=0.2.0"
]
[tool.setuptools.packages.find]
where = ["src"]
include = ["awesome_pkg*"]
Writing Package Code
Inside your source layout, implement clean, documented code. Use explicit namespace exports in __init__.py to control the public API surface.
python# src/awesome_pkg/core.py
from pydantic import BaseModel
class ConfigModel(BaseModel):
endpoint: str
timeout: int = 30
def process_payload(data: dict, config: ConfigModel) -> str:
"""Processes incoming payload against a validated configuration."""
return f"Processed for {config.endpoint} with timeout {config.timeout}"
python# src/awesome_pkg/__init__.py
from .core import ConfigModel, process_payload
__all__ = ["ConfigModel", "process_payload"]
__version__ = "0.1.0"
Building and Installing Locally
To build distributions and install your package in editable mode for local development, use the modern build and pip CLI tools. Never invoke python setup.py directly.
bash# Install build isolation tools
python -m pip install --upgrade build twine
# Build source distribution and wheel
python -m build
# Install the package in editable mode with development dependencies
python -m pip install -e ".[dev]"
Expected output after running python -m build:
text* Creating venv isolated environment...
* Installing packages in isolated environment... (setuptools>=68.0.0, wheel)
* Getting dependencies for sdist...
* Building sdist...
* Built dist/awesome_pkg-0.1.0.tar.gz
* Building wheel...
* Built dist/awesome_pkg-0.1.0.whl
Successfully built awesome_pkg-0.1.0.tar.gz and awesome_pkg-0.1.0.whl
Common Gotchas & Edge Cases
- Missing
__init__.py: In namespace packages or modern layouts, omitting__init__.pycan cause discovery failures depending on the setuptools version. Always include it unless creating explicit implicit namespace packages. - Package Discovery Mismatches: If your build succeeds but
import awesome_pkgfails withModuleNotFoundError, your[tool.setuptools.packages.find]configuration likely does not match your directory layout (where = ["src"]is mandatory for src-layouts). - Hardcoding Dependencies: Keep runtime dependencies in
project.dependenciesminimal. Heavy testing or linting tools belong exclusively inproject.optional-dependencies.
Key Takeaways
- Use
pyproject.tomlas the single source of truth for project metadata, dependencies, and build system configuration. - Adopt the
src/layout to enforce clean separation between code under test and local execution directories. - Rely on the standard
buildfrontend andsetuptools.build_metabackend instead of legacysetup.pyscripts. - Use
pip install -e .for rapid local iteration during the development cycle.
Python’s import system is extensible through PEP 302/451 protocols, allowing you to intercept import requests and load code from unconventional sources like databases, encrypted files, or network streams by implementing custom meta-path finders and loaders.
The Import Architecture
When import module_name is executed, Python consults sys.meta_path, a list of finder objects. Each finder must implement a find_spec(fullname, path, target=None) method. If it recognizes the module, it returns a ModuleSpec object containing a loader; otherwise, it returns None.
pythonimport sys
import importlib.machinery
import importlib.abc
class DatabaseFinder(importlib.abc.MetaPathFinder):
def __init__(self, storage):
# Simulated database containing module source code
self.storage = storage
def find_spec(self, fullname, path, target=None):
if fullname in self.storage:
# Create a ModuleSpec pointing to our loader
return importlib.machinery.ModuleSpec(
name=fullname,
loader=DatabaseLoader(self.storage[fullname]),
origin="database"
)
return None
Implementing the Loader
Once a finder returns a spec, Python invokes the loader’s create_module(spec) and exec_module(module) methods. For most pure Python modules, inheriting from importlib.abc.Loader and implementing exec_module is sufficient.
pythonclass DatabaseLoader(importlib.abc.Loader):
def __init__(self, source_code):
self.source_code = source_code
def create_module(self, spec):
# Returning None delegates default module creation to Python
return None
def exec_module(self, module):
# Execute the source code within the module's own namespace dict
exec(self.source_code, module.__dict__)
Wiring It Up
To make Python use your custom finder, prepend it to sys.meta_path.
python# Setup mock database storage
virtual_db = {
"secret_ops": "ACCESS_KEY = 'super-secret-123'\ndef run(): return 'Executing secure operation'"
}
# Register the meta-path finder
sys.meta_path.insert(0, DatabaseFinder(virtual_db))
# Import the module as if it exists on disk
import secret_ops
print(secret_ops.ACCESS_KEY)
print(secret_ops.run())
Expected Output:
textsuper-secret-123
Executing secure operation
Edge Cases and Gotchas
- Caching (`sys.modules`): Python caches imported modules in `sys.modules`. If you mutate code in your backing store, `import` statements will hit the cache unless you explicitly delete `sys.modules[fullname]`.
- Loader State: Loaders should avoid storing module-specific state directly on the loader instance if the loader is reused across multiple module instances.
- Package Support: If your custom loader handles packages (modules with submodules), you must set `spec.submodule_search_locations = []` in your finder.
Key Takeaways
- Custom import pipelines require implementing a MetaPathFinder (returns a `ModuleSpec`) and a Loader (executes the source code).
- Register custom finders by placing them onto `sys.meta_path`.
- Use `exec(code, module.__dict__)` inside `exec_module` to properly populate the module's namespace.
- Always clean up `sys.modules` if you need hot-reloading or dynamic updates from your data source.
Robust, scalable testing is the backbone of reliable software engineering, and pytest has become the undisputed industry standard for Python testing due to its powerful fixture system and readable assertions. This chapter covers writing scalable unit tests, leveraging dependency injection via fixtures, and practicing Test-Driven Development (TDD).
Anatomy of a Pytest Unit Test
Pytest discovers tests automatically by scanning files prefixed or suffixed with test_ (e.g., test_auth.py). Unlike unittest, pytest uses plain Python assert statements and automatically introspects intermediate values on failure to provide detailed diagnostic diffs.
python# math_utils.py
def calculate_discount(price: float, discount_percent: float) -> float:
if not (0 <= discount_percent <= 100):
raise ValueError("Discount must be between 0 and 100")
if price < 0:
raise ValueError("Price cannot be negative")
return round(price * (1 - discount_percent / 100), 2)
python# test_math_utils.py
import pytest
from math_utils import calculate_discount
def test_calculate_discount_standard():
assert calculate_discount(100.0, 20.0) == 80.0
def test_calculate_discount_boundary():
assert calculate_discount(50.0, 0.0) == 50.0
assert calculate_discount(200.0, 100.0) == 0.0
@pytest.mark.parametrize(
"price, discount, expected",
[
(99.99, 10.0, 89.99),
(50.0, 50.0, 25.0),
]
)
def test_calculate_discount_parametrized(price, discount, expected):
assert calculate_discount(price, discount) == expected
def test_calculate_discount_invalid_price():
with pytest.raises(ValueError, match="Price cannot be negative"):
calculate_discount(-10.0, 15.0)
Scalable State Management with Fixtures
Fixtures replace traditional setup and teardown methods with a modular, dependency-injection approach. Fixtures can request other fixtures and manage resources (like databases or temporary files) deterministically using yield.
python# conftest.py or test file
import pytest
@pytest.fixture
def sample_user_payload():
# Setup phase: Prepare test data
payload = {"username": "dev_guru", "role": "admin", "active": True}
yield payload
# Teardown phase (if needed, e.g., cleaning up state):
payload.clear()
def test_user_is_admin(sample_user_payload):
assert sample_user_payload["role"] == "admin"
To prevent tight coupling and unexpected test pollution, pytest fixtures default to function scope. Use scope="session", scope="module", or scope="class" explicitly when sharing expensive resources like database connections.
Test-Driven Development (TDD) Workflow
TDD follows a strict Red-Green-Refactor loop:
- Red: Write a failing test for a feature that doesn’t exist yet.
- Green: Write the minimum amount of production code to make the test pass.
- Refactor: Clean up the code while keeping tests green.
python# Step 1 (Red): Write the test first
# test_cart.py
def test_shopping_cart_total():
cart = ShoppingCart()
cart.add_item("Laptop", 1000.0)
cart.add_item("Mouse", 50.0)
assert cart.get_total() == 1050.0
python# Step 2 (Green): Implement minimal code to pass
# cart.py
class ShoppingCart:
def __init__(self):
self.items = []
def add_item(self, name: str, price: float):
self.items.append({"name": name, "price": price})
def get_total(self) -> float:
return sum(item["price"] for item in self.items)
Try It Yourself
Execute your tests from the terminal using the pytest command. For verbose output and running specific tests matching a keyword:
bashpytest -v -k "discount"
Expected Output:
text============================= test session starts ==============================
platform linux -- Python 3.12.x, pytest-8.x.x, pluggy-1.x.x
cachedir: .pytest_cache
rootdir: /path/to/project
collected 6 items
test_math_utils.py::test_calculate_discount_standard PASSED [ 16%]
test_math_utils.py::test_calculate_discount_boundary PASSED [ 33%]
test_math_utils.py::test_calculate_discount_parametrized[99.99-10.0-89.99] PASSED [ 50%]
test_math_utils.py::test_calculate_discount_parametrized[50.0-50.0-25.0] PASSED [ 66%]
test_math_utils.py::test_calculate_discount_invalid_price PASSED [ 83%]
test_cart.py::test_shopping_cart_total PASSED [100%]
============================== 6 passed in 0.04s ===============================
Key Takeaways
- Use native Python
assertstatements; pytest introspects expressions automatically to show detailed error diffs. - Avoid test duplication by utilizing
@pytest.mark.parametrizefor data-driven testing scenarios. - Leverage fixtures with
yieldfor clean, modular setup and deterministic resource teardown. - Always test exception handling explicitly using
with pytest.raises(ExceptionType, match="regex"):. - Stick to the TDD Red-Green-Refactor cycle to ensure every line of code is intentional and tested.
Python’s re module brings regular expression matching operations to string processing, enabling precise pattern validation, searching, and extraction.
Compilation and Performance
Regular expressions must be compiled into pattern objects before execution to optimize performance in loops or repetitive lookups.
pythonimport re
# Compile once for efficiency
log_pattern = re.compile(
r'^(?P<ip>\d{1,3}(?:\.\d{1,3}){3}) - - \[(?P<timestamp>[^\]]+)\] "(?P<method>[A-Z]+) (?P<url>[^\s]+)[^"]*" (?P<status>\d{3}){{content}}#x27;
)
sample_log = '192.168.1.50 - - [14/Oct/2023:10:15:32 +0000] "GET /api/v1/users HTTP/1.1" 200'
match = log_pattern.match(sample_log)
if match:
# Extract data using named capture groups
print(match.groupdict())
Expected Output
python{'ip': '192.168.1.50', 'timestamp': '14/Oct/2023:10:15:32 +0000', 'method': 'GET', 'url': '/api/v1/users', 'status': '200'}
Advanced Extraction and Replacement
Beyond basic searching, re.sub accepts a callable to dynamically transform matches using match object properties.
pythonimport re
text = "Items cost $45.50, €12.00, and $100."
# Find currency symbols and numeric values, apply dynamic exchange rate replacement
converted = re.sub(r'([$€])(\d+(?:\.\d{2})?)', lambda m: f"USD {float(m.group(2)) * (1.1 if m.group(1) == '€' else 1.0):.2f}", text)
print(converted)
Expected Output
textItems cost USD 45.50, USD 13.20, and USD 100.00.
Common Gotchas and Performance Considerations
- Greedy Quantifiers: By default, quantifiers like
.*are greedy and consume as much text as possible. Append a?(e.g.,.*?) for lazy matching, but prefer character classes like[^"]*when parsing structural formats to avoid catastrophic backtracking. - Raw Strings: Always use raw string literals (
r"...") for regular expression patterns to prevent unintended backslash escapes.
Key Takeaways
- Compile patterns using
re.compile()if they are executed multiple times to bypass runtime parsing overhead. - Leverage named capture groups (
(?P<name>...)) to make extraction code maintainable and self-documenting. - Use explicit character classes (
[^\s]+) instead of greedy wildcards to ensure predictable performance and prevent backtracking vulnerabilities.
The concurrent.futures module provides a high-level asynchronous interface for executing callables using pooled threads or processes, abstracting away low-level synchronization mechanics.
Choosing the Right Pool: Threads vs. Processes
Python’s Global Interpreter Lock (GIL) permits only one thread to execute Python bytecode at a time, rendering ThreadPoolExecutor inefficient for CPU-bound tasks. However, I/O-bound tasks—such as network requests or disk reads—spend most of their time waiting, making threads ideal. Conversely, ProcessPoolExecutor bypasses the GIL by spawning separate interpreter processes, making it essential for CPU-bound numerical or algorithmic processing.
pythonimport time
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
def cpu_bound_task(n: int) -> int:
"""Simulates a heavy computational workload."""
return sum(i * i for i in range(n))
def io_bound_task(url: str) -> str:
"""Simulates an I/O network delay."""
time.sleep(0.5)
return f"Loaded: {url}"
# CPU-bound: Use ProcessPoolExecutor
if __name__ == "__main__":
with ProcessPoolExecutor() as executor:
numbers = [10_000_000, 15_000_000, 20_000_000]
results = list(executor.map(cpu_bound_task, numbers))
print("CPU Results:", results)
# I/O-bound: Use ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=4) as executor:
urls = ["api.v1/data", "api.v2/data", "api.v3/data"]
results = list(executor.map(io_bound_task, urls))
print("I/O Results:", results)
Asynchronous Execution with `as_completed`
While executor.map() preserves the input order, it blocks until each task finishes sequentially in the iterator. For workloads where tasks finish at unpredictable times, as_completed() yields futures as they resolve, enabling real-time processing.
pythonfrom concurrent.futures import ThreadPoolExecutor, as_completed
import random
import time
def fetch_data(task_id: int) -> str:
delay = random.uniform(0.1, 1.0)
time.sleep(delay)
return f"Task {task_id} completed in {delay:.2f}s"
with ThreadPoolExecutor(max_workers=3) as executor:
# Submit tasks and map futures to identifiers
future_to_id = {executor.submit(fetch_data, i): i for i in range(5)}
for future in as_completed(future_to_id):
try:
data = future.result()
print(data)
except Exception as exc:
print(f"Task generated an exception: {exc}")
Expected Output
```text CPU Results: [33333328333333500000, 112499962500003750000, 266666640000001000000] I/O Results: ['Loaded: api.v1/data', 'Loaded: api.v2/data', 'Loaded: api.v3/data'] Task 0 completed in 0.15s Task 2 completed in 0.31s Task 1 completed in 0.54s Task 4 completed in 0.82s Task 3 completed in 0.95s ```Edge Cases and Performance Gotchas
- Serialization Overhead:
ProcessPoolExecutorrequires arguments and return values to be pickled (serialized). Passing large objects or non-picklable items (like open database connections or locks) will raise aPicklingError. - Context Protection: Always protect process pool execution blocks with
if __name__ == '__main__':on platforms like Windows and macOS that use thespawnstart method, preventing recursive process initialization loops. - Deadlocks in Pools: Avoid calling
future.result()inside a task submitted to the same pool if the pool’s maximum workers are exhausted, as this will lead to a permanent deadlock.
Key Takeaways
- Use
ThreadPoolExecutorfor I/O-bound workloads to overlap waiting periods efficiently. - Use
ProcessPoolExecutorfor CPU-bound tasks to scale across multiple CPU cores by escaping the GIL. - Use
executor.map()for simple ordered collections, andas_completed()when you need to handle task results dynamically as soon as they finish. - Ensure all task arguments and outputs passed to a
ProcessPoolExecutorare safely picklable.
Python’s asyncio library enables concurrent execution using the async and await syntax, allowing single-threaded cooperative multitasking for I/O-bound operations.
Core Concepts: Coroutines and Event Loops
An asynchronous function is defined using async def, creating a coroutine object when called. Coroutines do not run when invoked; they must be scheduled onto the event loop using mechanisms like asyncio.run() or await.
pythonimport asyncio
async def fetch_data(delay: int, id: int) -> str:
print(f"Task {id}: Starting download...")
await asyncio.sleep(delay) # Non-blocking pause
print(f"Task {id}: Complete!")
return f"Data {id}"
async def main():
# Sequential execution (takes delay1 + delay2 time)
result = await fetch_data(1, 1)
print(result)
asyncio.run(main())
Concurrent Execution with `asyncio.gather`
To execute multiple coroutines concurrently rather than sequentially, wrap them in asyncio.gather(). This pools independent operations so they run during each other’s I/O wait times.
pythonimport asyncio
import time
async def simulate_api_call(endpoint: str, delay: float) -> str:
print(f"Fetching {endpoint}...")
await asyncio.sleep(delay)
return f"Response from {endpoint}"
async def main():
start_time = time.perf_counter()
# Run three API calls concurrently
results = await asyncio.gather(
simulate_api_call("/users", 1.5),
simulate_api_call("/posts", 1.0),
simulate_api_call("/settings", 0.5)
)
end_time = time.perf_counter()
print(f"All requests finished in {end_time - start_time:.2f} seconds.")
print("Results:", results)
asyncio.run(main())
Expected Output
```text Fetching /users... Fetching /posts... Fetching /settings... All requests finished in 1.50 seconds. Results: ['Response from /users', 'Response from /posts', 'Response from /settings'] ```Gotchas and Performance Considerations
- Blocking Code: Calling synchronous, blocking libraries (like standard
time.sleep()or standardrequests) inside anasyncfunction freezes the entire event loop. Always use async-native equivalents (e.g.,asyncio.sleep()orhttpxinstead ofrequests). - CPU-Bound Tasks:
asynciodoes not speed up CPU-bound tasks (like heavy computation or image processing). It only optimizes waiting periods for I/O. For CPU-bound concurrency, useconcurrent.futures.ProcessPoolExecutor. - Unhandled Exceptions: If a task scheduled via
asyncio.gatherfails, it raises the exception immediately. Usereturn_exceptions=Trueingatherif you need to capture failures independently.
Key Takeaways
* Use `async def` to define coroutines and `await` to yield control back to the event loop during I/O operations. * `asyncio.run()` is the standard entry point for launching the top-level event loop. * Combine independent coroutines with `asyncio.gather()` to achieve non-blocking concurrent execution. * Avoid blocking the event loop with synchronous operations or CPU-intensive algorithms.Building robust, enterprise-grade asynchronous systems requires moving beyond basic async/await syntax to master low-level synchronization primitives, custom task instrumentation, and event loop policies.
Low-Level Synchronization Primitives
While asyncio.Lock handles standard mutual exclusion, complex architectures often require primitives like asyncio.Condition, asyncio.Event, and asyncio.Semaphore to manage fine-grained producer-consumer boundaries without deadlocks.
pythonimport asyncio
async def worker(id: int, semaphore: asyncio.Semaphore, condition: asyncio.Condition, state: dict):
async with semaphore:
print(f"Worker {id} acquired semaphore.")
await asyncio.sleep(0.1)
async with condition:
state["ready_count"] += 1
if state["ready_count"] == 3:
print("All workers ready. Notifying coordinator...")
condition.notify_all()
else:
await condition.wait()
print(f"Worker {id} finished execution.")
async def main():
semaphore = asyncio.Semaphore(2)
condition = asyncio.Condition()
state = {"ready_count": 0}
tasks = [asyncio.create_task(worker(i, semaphore, condition, state)) for i in range(3)]
await asyncio.gather(*tasks)
if __name__ == "__main__":
asyncio.run(main())
Custom Task Factories and Instrumentation
Default asyncio.Task instances provide basic lifecycle tracking. By implementing a custom task factory via loop.set_task_factory(), you can inject tracing, automatic context propagation, or deep execution metrics into every spawned coroutine.
pythonimport asyncio
import time
class InstrumentedTask(asyncio.Task):
def __init__(self, coro, *, context=None, name=None):
super().__init__(coro, context=context, name=name)
self.created_at = time.perf_counter()
self.add_done_callback(self._log_completion)
def _log_completion(self, task):
duration = time.perf_counter() - self.created_at
print
The Python itertools module provides fast, memory-efficient tooling to build complex iterator pipelines and combinatorial streams without materializing intermediate data structures in RAM.
Infinite Iterators and Memory Efficiency
Standard collections like lists or tuples load all elements into memory immediately. In contrast, itertools.count, cycle, and repeat generate values lazily on demand. This pattern prevents memory exhaustion when processing infinite streams or unbounded mathematical sequences.
pythonfrom itertools import count, islice
# Create an infinite sequence starting at 10, stepping by 3
infinite_sequence = count(start=10, step=3)
# Safely consume the first 5 elements using islice
first_five = list(islice(infinite_sequence, 5))
print(first_five)
Expected Output:
text[10, 13, 16, 19, 22]
Gotcha: Never pass an infinite iterator directly to a consumer like list() or sum() without a bound (such as islice or takewhile), or your program will hang indefinitely attempting to exhaust memory.
Terminating and Grouping Iterators
Processing sorted or grouped data often requires conditional slicing or aggregation. Tools like groupby, dropwhile, and takewhile evaluate predicates on-the-fly.
pythonfrom itertools import groupby
data = [('A', 1), ('A', 2), ('B', 3), ('B', 4), ('A', 5)]
# groupby requires data to be sorted by the grouping key first
sorted_data = sorted(data, key=lambda x: x[0])
for key, group in groupby(sorted_data, key=lambda x: x[0]):
print(f"Key: {key}, Values: {list(group)}")
Expected Output:
textKey: A, Values: [('A', 1), ('A', 2), ('A', 5)]
Key: B, Values: [('B', 3), ('B', 4)]
Performance Tip: itertools.groupby looks only at adjacent elements. If your data is unsorted, groupby will split identical keys that are separated by other values. Always sort your dataset by the grouping key before calling groupby.
Combinatorial Generators
Calculating permutations, combinations, and Cartesian products using nested loops degrades time complexity quickly. itertools implements these in optimized C under the hood.
pythonfrom itertools import combinations, permutations
items = ['CPU', 'RAM', 'GPU']
# Order matters: permutations
print("Permutations:", list(permutations(items, 2)))
# Order does not matter: combinations
print("Combinations:", list(combinations(items, 2)))
Expected Output:
textPermutations: [('CPU', 'RAM'), ('CPU', 'GPU'), ('RAM', 'CPU'), ('RAM', 'GPU'), ('GPU', 'CPU'), ('GPU', 'RAM')]
Combinations: [('CPU', 'RAM'), ('CPU', 'GPU'), ('RAM', 'GPU')]
Key Takeaways
- Use
itertoolsto process large or infinite datasets lazily, avoiding memory bloat from intermediate lists. - Always bound infinite iterators (
count,cycle,repeat) using tools likeisliceortakewhile. - Ensure datasets are sorted by the target key before passing them to
itertools.groupby. - Leverage C-optimized combinatorial generators (
permutations,combinations,product) instead of writing custom nested loops for data analysis tasks.
Memory-efficient data processing in Python relies on lazy evaluation via custom iterators and generator pipelines, allowing unbounded streams to be processed with $O(1)$ spatial complexity using the yield from delegation pattern.
Building Stateful Custom Iterators
To implement a custom iterator from scratch, an object must implement the iterator protocol: the __iter__() method (returning self) and the __next__() method (raising StopIteration when exhausted).
pythonclass WindowedIterator:
"""Yields a sliding window of size `k` over an iterable."""
def __init__(self, iterable, k: int):
if k <= 0:
raise ValueError("Window size must be greater than 0")
self.iterator = iter(iterable)
self.k = k
self.window = []
# Prime the window
try:
for _ in range(k):
self.window.append(next(self.iterator))
except StopIteration:
pass
def __iter__(self):
return self
def __next__(self):
if len(self.window) < self.k:
raise StopIteration
current_window = tuple(self.window)
try:
next_item = next(self.iterator)
self.window.pop(0)
self.window.append(next_item)
except StopIteration:
# Clear window so subsequent calls immediately raise StopIteration
self.window = []
return current_window
# Usage
stream = [1, 2, 3, 4, 5]
for window in WindowedIterator(stream, 3):
print(window)
Expected Output:
text(1, 2, 3)
(2, 3, 4)
(3, 4, 5)
Composing Pipelines with Generators and yield from
Generators simplify iterator creation, while the yield from expression delegates control to a sub-generator or any iterable. This establishes transparent bidirectional channels for values, exceptions, and return values without boilerplate loops.
pythonfrom typing import Generator, Iterable, Any
def reader(filename: str) -> Generator[str, None, None]:
# Simulating a file stream
lines = [" DATA: 10 ", "SKIPPED", " DATA: 20 ", " DATA: 30 "]
for line in lines:
yield line
def cleaner(source: Iterable[str]) -> Generator[str, None, None]:
for line in source:
stripped = line.strip()
if stripped.startswith("DATA:"):
# yield from delegates iteration directly to the string's characters
# or sub-processing logic; here we yield the processed chunk.
yield stripped
def parser(source: Iterable[str]) -> Generator[int, None, None]:
for item in source:
val = item.split(":")[1]
yield int(val)
def pipeline(filename: str) -> Generator[int, None, None]:
"""Composes sub-generators seamlessly using yield from."""
raw = reader(filename)
cleaned = cleaner(raw)
# Delegate entirely to the parser sub-generator
yield from parser(cleaned)
# Execute pipeline
for val in pipeline("simulated_file.txt"):
print(val, type(val))
Expected Output:
text10 <class 'int'>
20 <class 'int'>
30 <class 'int'>
Advanced Generator Features: send(), throw(), and close()
Generators are coroutines. The yield from expression automatically wires up communication channels, allowing values to be sent into sub-generators and exceptions to propagate correctly down the delegation chain.
pythondef accumulator() -> Generator[int, int, float]:
total = 0
count = 0
try:
while True:
# Value is received via .send()
value = yield total
if value is None:
break
total += value
count += 1
finally:
return total / count if count > 0 else 0.0
def delegator() -> Generator[Any, Any, float]:
print("Delegator starting...")
# yield from establishes a transparent pipe for send() and return values
avg = yield from accumulator()
print(f"Sub-generator finished. Final average: {avg}")
return avg
# Driving the coroutine pipeline
gen = delegator()
print(next(gen)) # Prime the generator (runs until first yield)
print(gen.send(10)) # Sends 10 into accumulator
print(gen.send(20)) # Sends 20 into accumulator
try:
gen.send(None) # Triggers break, returns final average via StopIteration
except StopIteration as e:
print(f"Pipeline returned: {e.value}")
Expected Output:
textDelegator starting...
0
10
30
Sub-generator finished. Final average: 15.0
Pipeline returned: 15.0
Performance Considerations and Gotchas
- Memory O(1) Guarantee: Generator pipelines execute lazily. Intermediate transformations do not allocate lists in memory, making them ideal for processing datasets larger than RAM.
- Single-Pass Iteration: Iterators and generators can only be consumed once. Attempting to iterate a consumed generator twice silently yields nothing.
- State Leakage in Custom Iterators: Ensure state variables (like
self.windowor underlyingiter(iterable)) are properly reset whenStopIterationis reached to prevent undefined behavior on reuse.
Key Takeaways
- Implement custom iterators via
__iter__and__next__, raisingStopIterationexplicitly when complete. - Use
yield fromto cleanly delegate execution to sub-generators, establishing automatic pipelines for values, exceptions, and return values. - Generators function as lightweight coroutines capable of receiving external input via
.send()while maintaining strict $O(1)$ memory overhead.
NumPy — Installer et importer
NumPy est le package de base pour le calcul numérique en Python (tableaux, mathématiques rapides, algèbre linéaire).
Installez-le avec pip ou votre gestionnaire de packages, puis importez-le (classiquement sous np).
Installer
shell# with pip
pip install numpy
# or with conda
conda install numpy
Importer
pythonimport numpy as np
# now use np.array, np.linspace, np.zeros, ...
Pièges courants
- Assurez-vous d'installer dans le même environnement Python que celui que vous exécutez (problèmes d'environnement virtualenv/conda).
- L'importation sous un autre format que
npest autorisée mais peu courante – d'autres personnes s'attendent ànp.
Tableaux NumPy - Créer, indexer, découper
Les tableauxNumPy sont comme des listes mais avec des types numériques fixes et des opérations vectorisées rapides. Vous pouvez convertir des listes, créer des tableaux imbriqués (2D) et les indexer/découper.
Créer à partir de listes
pythonimport numpy as np
a = np.array([1, 2, 3, 4]) # 1D array
b = np.array([[1, 2, 3], [4, 5, 6]]) # 2D array
print(a.shape) # (4,)
print(b.shape) # (2, 3)
Indexation (1D et 2D)
pythonprint(a[0]) # first element -> 1
print(b[1, 2]) # second row, third column -> 6
print(b[0][1]) # alternative syntax -> 2
Découpage
pythonc = np.arange(10) # array([0,1,2,...,9])
print(c[1:5]) # [1 2 3 4]
print(b[0:2, 1:3]) # rows 0..1 and cols 1..2 (2x2 subarray)
Pièges courants
-
Les tableaux
- NumPy nécessitent un type uniforme : les objets Python mixtes conduisent à
dtype=object. - Les tranches sont des **vues**, pas des copies : la modification d'une tranche peut modifier le tableau d'origine.
Forme du tableau et propriété .shape
.shape renvoie un tuple avec la taille de chaque dimension. C'est une propriété (pas de parenthèses).
Exemples
pythonimport numpy as np
a = np.array([1, 2, 3, 4])
b = np.array([[1,2,3],[4,5,6]])
print(a.shape) # (4,)
print(b.shape) # (2, 3)
# reshape if needed
c = a.reshape((2,2))
print(c.shape) # (2, 2)
Pièges courants
- Appeler
.shape()avec des parenthèses est incorrect : c'est une propriété, pas une fonction. reshapenécessite des tailles qui se multiplient par le même nombre d'éléments (ou utilisez-1pour l'inférence automatique).
NumPy — Fonctions de base (linspace, zéros, aléatoire, ...)
NumPy propose des constructeurs et des assistants pratiques pour les tableaux et séquences couramment utilisés.
Constructeurs communs
pythonimport numpy as np
# even spacing: start, stop, num-values
x = np.linspace(0, 1, num=5) # [0. 0.25 0.5 0.75 1. ]
# zeros with shape / dtype
Z = np.zeros((2,3), dtype=float) # 2x3 array of zeros
# arange like Python range -> integers
r = np.arange(0, 10, 2) # [0 2 4 6 8]
Numéros aléatoires
python# modern usage (numpy >= 1.17) prefers Generator, but simple forms below:
rand = np.random.rand(3) # 3 uniform floats in [0,1)
rnorm = np.random.randn(3) # 3 standard normal samples
rint = np.random.randint(0, 10, size=4) # 4 ints in [0,10)
Comportement du type de données
pythona = np.array([1, 2, 3], dtype=int)
a[0] += 0.2
print(a) # still integer array; fractional part lost (a[0] remains 1)
- Si un tableau a un type entier, les opérations sur place seront converties en ce type (troncation possible).
- Pour autoriser les flottants, créez le tableau avec
dtype=floatou lancez avec.astype().
Matplotlib — Installer et importer
Matplotlib est la bibliothèque de traçage standard pour Python. Installez-le avec votre gestionnaire de packages et importez le module pyplot (généralement sous le nom plt).
Installer
shell# with pip
pip install matplotlib
# or with conda
conda install matplotlib
Importer
pythonimport matplotlib.pyplot as plt
# optionally import numpy for data
import numpy as np
Pièges courants
- Installer dans l'environnement actif (virtualenv/conda) utilisé par votre script ou notebook.
- Dans certains environnements (par exemple, les serveurs sans tête), vous aurez peut-être besoin d'un backend non interactif pour enregistrer les chiffres.
Matplotlib — Utilisation de base (plt.plot, plt.show, save)
Flux de travail de traçage simple : créez des données, appelez des fonctions de traçage, puis affichez ou enregistrez la figure.
Tracé linéaire simple
pythonimport matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
plt.plot(x, y) # plot the line
plt.show() # display the plot window (or inline in notebooks)
Séries multiples et sauvegarde
pythonplt.plot(x, np.sin(x), label='sin')
plt.plot(x, np.cos(x), label='cos')
plt.legend()
plt.savefig('sincos.png') # save to file
plt.show()
Pièges courants
- Appelez
plt.show()après avoir configuré le tracé — sinon certains backends risquent de ne pas afficher le style complet. - Lorsque vous tracez plusieurs figures, utilisez
plt.figure()oufig, ax = plt.subplots()pour les séparer.
Matplotlib — Modificateurs et style (titre, légende, axes, aspect)
Utilisez des étiquettes, des limites, des légendes et des méthodes d'axe pour ajuster l'apparence et la disposition des tracés.
Étiquettes, titre, légende
pythonplt.plot(x, np.sin(x), label='sin')
plt.plot(x, np.cos(x), label='cos')
plt.xlabel('x (rad)')
plt.ylabel('value')
plt.title('Sine & Cosine')
plt.legend() # show labels in top-right by default
plt.show()
Limites et aspect des axes
pythonplt.plot([0,1,2], [0,1,4])
plt.xlim(0, 2) # set x limits
plt.ylim(0, 5) # set y limits
ax = plt.gca() # get current Axes
ax.set_aspect('equal') # equal scaling for x and y units
plt.show()
Masquer les axes ou les graduations
pythonax = plt.gca()
ax.xaxis.set_visible(False) # hide x-axis
ax.yaxis.set_visible(False) # hide y-axis
Pièges courants
- La modification des propriétés de l'axe nécessite un objet
Axes(depuisplt.gca()ou le retour deplt.subplots()). - De nombreuses options de style sont persistantes pour la figure/les axes actuels : appelez-les dans le bon ordre ou créez une nouvelle figure pour des tracés séparés.
Python’s ast module exposes the compiler’s intermediate representation, allowing developers to inspect, programmatically modify, and safely execute Python source code.
Parsing and Inspecting the AST
Python code is transformed into an Abstract Syntax Tree (AST) before compilation to bytecode. The ast.parse() function takes a source string and returns the root ast.Module node, which contains a sequence of statement nodes.
pythonimport ast
code = """
def calculate(x, y):
return x * y + 2
"""
tree = ast.parse(code)
print(ast.dump(tree, indent=2))
To traverse this tree safely without writing manual recursive visitors, subclass ast.NodeTransformer or ast.NodeVisitor. NodeVisitor reads the tree, while NodeTransformer modifies it in place by returning new nodes or deleting existing ones.
Transforming Code with NodeTransformer
A common pattern for code instrumentation—such as automatic logging or security sandboxing—is intercepting specific node types. The following example intercepts binary multiplication operations (*) and rewrites them into exponentiation (**).
pythonimport ast
class MultiplyToPowerTransformer(ast.NodeTransformer):
def visit_BinOp(self, node: ast.BinOp) -> ast.AST:
# Recursively visit child nodes first
self.generic_visit(node)
# If the operator is multiplication, replace it with power
if isinstance(node.op, ast.Mult):
node.op = ast.Pow()
return node
source = "result = 5 * 3"
tree = ast.parse(source)
transformer = MultiplyToPowerTransformer()
new_tree = transformer.visit(tree)
# Fix missing line numbers and column offsets required for compilation
ast.fix_missing_locations(new_tree)
# Compile and execute the transformed AST
compiled_code = compile(new_tree, filename="<string>", mode="exec")
namespace = {}
exec(compiled_code, namespace)
print(namespace["result"]) # Expected: 125 (5 ** 3)
Expected Output
text125
Edge Cases, Gotchas, and Performance
- Missing Locations: Whenever you construct new AST nodes programmatically, they lack line numbers and column offsets. Always pass your root node through
ast.fix_missing_locations()before callingcompile(), otherwise runtime tracebacks or the compiler itself may raise errors. evalvsexecvscompile: Never pass raw strings directly toeval()orexec()when handling untrusted user input. AST manipulation allows structural whitelisting (e.g., rejectingast.Callnodes entirely), but a robust sandbox requires much deeper isolation than AST rewriting alone.- Performance Overhead: AST transformations occur at parse/load time, not execution time. Therefore, runtime performance of the compiled bytecode remains unaffected. However, parsing large codebases repeatedly can bottleneck application startup. Cache compiled code objects where appropriate.
Key Takeaways
ast.parse()turns source code into a traversable object graph.ast.NodeTransformermutates code structures programmatically by returning modified nodes.- Always call
ast.fix_missing_locations()after altering or constructing nodes manually. - Transformed ASTs must be compiled via
compile()before execution withexec()oreval().
Efficient Python applications demand a solid grasp of reference counting, garbage collection mechanics, and systematic profiling to eliminate memory leaks and execution bottlenecks.
Memory Management & Reference Counting
Python relies primarily on reference counting for memory management. An object’s reference count increases when it is assigned to a new variable or added to a container, and decreases when a reference goes out of scope or is deleted via del.
pythonimport sys
# A new list object is created; reference count is 1
data = [1, 2, 3, 4, 5]
print("Initial ref count:", sys.getrefcount(data) - 1) # Subtract 1 for getrefcount's temporary reference
# Aliasing increases the reference count
alias = data
print("Ref count after alias:", sys.getrefcount(data) - 1)
# Removing references drops the count
del alias
print("Ref count after del:", sys.getrefcount(data) - 1)
Circular References
Reference counting fails when objects reference each other, creating a cycle. Python solves this with a generational garbage collector (gc module) that detects and clears cyclic isolation.
pythonimport gc
class Node:
def __init__(self, name):
self.name = name
self.peer = None
# Disable automatic GC to manually demonstrate collection
gc.disable()
node_a = Node("A")
node_b = Node("B")
# Create a circular reference
node_a.peer = node_b
node_b.peer = node_a
# Delete local references
del node_a
del node_b
# Objects are still in memory due to the cycle. Force a collection sweep.
collected = gc.collect()
print(f"Garbage collector freed {collected} unreachable objects.")
gc.enable()
Diagnosing Memory Leaks with Tracemalloc
The built-in tracemalloc library tracks memory allocations made by Python, letting you pinpoint the exact source of memory growth.
pythonimport tracemalloc
def leak_memory():
# Simulate a memory leak by growing a global-like list indefinitely
leaked_store = []
for i in range(100_000):
leaked_store.append("x" * 100)
return leaked_store
# Start tracing memory allocations
tracemalloc.start()
# Execute leaky operation
store = leak_memory()
# Capture current memory snapshot
snapshot = tracemalloc.take_snapshot()
top_stats = snapshot.statistics("lineno")
print("[ Top 3 Memory Allocations ]")
for stat in top_stats[:3]:
print(stat)
tracemalloc.stop()
Performance Profiling with cProfile
To optimize execution speed, bypass guesswork and profile code execution using cProfile and the built-in pstats module.
pythonimport cProfile
import pstats
from io import StringIO
def heavy_computation():
total = 0
for i in range(1_000_000):
total += i**0.5
return total
def inefficient_lookup():
data = list(range(10_000))
# O(N) lookup inside a loop is an anti-pattern
for i in range(1_000):
_ = i in data
def main():
heavy_computation()
inefficient_lookup()
# Profile the main execution block
profiler = cProfile.Profile()
profiler.enable()
main()
profiler.disable()
# Format and print the top performance bottlenecks
s = StringIO()
sortby = "cumulative"
ps = pstats.Stats(profiler, stream=s).sort_stats(sortby)
ps.print_stats(10) # Print top 10 bottlenecks
print(s.getvalue())
Common Gotchas and Best Practices
- Circular References in Closures/Classes: Circular dependencies prevent immediate deallocation. Use
weakrefproxies when parent-child relationships create reference cycles. __slots__Optimization: Standard Python instances store attributes in a dynamic__dict__, consuming excessive memory for classes instantiated millions of times. Define__slots__to fix attributes and reduce memory footprints significantly.- Profiling Overhead: Running
cProfileslows down application execution. Use it primarily in staging or debugging environments rather than high-throughput production paths.
python# Utilizing __slots__ to save memory
class StandardClass:
def __init__(self, x, y):
self.x = x
self.y = y
class OptimizedClass:
__slots__ = ("x", "y")
def __init__(self, x, y):
self.x = x
self.y = y
Key Takeaways
- Python uses reference counting for instant cleanup and a generational garbage collector to clear complex cyclic references.
sys.getrefcount()helps inspect reference counts, keeping in mind that function arguments create temporary internal references.tracemalloctracks exact line-by-line memory allocations, making memory leak diagnostics deterministic.cProfileexposes execution time bottlenecks, directing optimization efforts toward functions that impact performance most.__slots__reduces the memory overhead of classes by eliminating per-instance dictionaries.
The Python buffer protocol exposes an object’s internal data—such as bytes, bytearrays, or NumPy arrays—directly to other routines like C-extensions or I/O channels without memory duplication. A memoryview exposes this protocol at the Python level, enabling zero-copy slicing and high-performance binary manipulation.
Zero-Copy Slicing Mechanics
Standard Python slicing on bytes or str objects creates a brand new object in memory, copying the underlying byte sequence. For large buffers, this degrades performance and inflates memory footprints. A memoryview references the original memory address space directly.
python# Creating a large bytearray buffer (10 MB)
large_buffer = bytearray(b"A" * (10 * 1024 * 1024))
# Standard slice: Copies 5 MB of memory
standard_slice = large_buffer[5 * 1024 * 1024:]
# Memoryview slice: Zero-copy pointer adjustment
mv = memoryview(large_buffer)
view_slice = mv[5 * 1024 * 1024:]
print(f"Original ID: {id(large_buffer)}")
print(f"View base object: {id(view_slice.obj)}")
print(f"View length: {len(view_slice)}")
Original ID: 140123456789120
View base object: 140123456789120
View length: 5242880
Mutating Underlying Data In-Place
Because memoryview objects wrap mutable buffers (like bytearray), you can modify segments of the buffer in-place. This is crucial for network packet parsing, binary protocol serialization, and image processing.
pythondata = bytearray(b"HEADER:PAYLOAD_DATA")
mv = memoryview(data)
# Mutate the payload section in-place through the view
mv[7:] = b"MODIFIED_DATA"
print(data)
bytearray(b'HEADER:MODIFIED_DATA')
Casting Types and Multidimensional Views
The buffer protocol supports format descriptors. Using memoryview.cast(), you can reinterpret raw bytes as structured types (e.g., arrays of 32-bit integers) without deserializing arrays manually.
pythonimport struct
# 4 integers, 4 bytes each = 16 bytes total
raw_bytes = bytearray(struct.pack("4i", 10, 20, 30, 40))
# Cast the bytearray view to signed 32-bit integers ('i')
int_view = memoryview(raw_bytes).cast("i")
print("Cast view:", int_view.tolist())
# Modify an integer in-place
int_view[2] = 999
print("Updated raw bytes struct:", struct.unpack("4i", raw_bytes))
Cast view: [10, 20, 30, 40]
Updated raw bytes struct: (10, 20, 999, 40)
Common Gotchas and Performance Considerations
- Buffer Export Locks: When a
memoryviewis active on a mutable object like abytearray, operations that resize the underlying object (such asappend,extend, or re-assignment) raise aBufferError. Always release or let yourmemoryviewgo out of scope before mutating container sizes. - Context Management:
memoryviewimplements the context manager protocol. Usewith memoryview(obj) as mv:to explicitly release the underlying buffer lock as soon as the slice operations complete. - Immutable Sources: Slicing an immutable buffer (like
bytes) viamemoryviewis still zero-copy, but casting or mutating it will raise aTypeError.
Key Takeaways
memoryvieweliminates memory duplication by leveraging Python’s underlying buffer protocol for zero-copy slicing.- Slicing a
memoryviewreferences the original memory addresses directly, reducing allocations to $O(1)$ time and space complexity. - The
.cast()method allows reinterpreting raw binary buffers into different numeric data types without data copying. - Active memory views place a lock on mutable buffers; attempting to resize the parent object while a view is active triggers a
BufferError.
Python’s attribute resolution mechanism can be intercepted at multiple levels using __getattribute__, __getattr__, and the descriptor protocol to build powerful, dynamic runtime frameworks.
The Attribute Resolution Order
When an attribute is accessed on an instance (obj.name), Python follows a strict lookup hierarchy known as the Descriptor Protocol and Attribute Resolution Chain:
- Data Descriptors: Instances of classes defining both
__get__and__set__(or__delete__). These take highest precedence over instance dictionary entries. - Instance Dictionary (
__dict__): Normal instance variables. - Non-Data Descriptors: Instances of classes defining only
__get__(e.g., methods). - Class Dictionary: Attributes defined directly on the class.
__getattr__: A fallback hook invoked only if the attribute cannot be found via any of the above mechanisms.
By contrast, __getattribute__ is called unconditionally for every attribute access before looking anywhere else.
Intercepting All Access with __getattribute__
The __getattribute__ method intercepts every read operation on an object.
pythonclass StrictModel:
def __init__(self, data: dict):
# Bypass custom __getattribute__ during initialization to avoid recursion
super().__setattr__('_data', data)
def __getattribute__(self, name):
# Avoid intercepting internal lookups for initialization/methods
if name.startswith('_'):
return super().__getattribute__(name)
data = super().__getattribute__('_data')
if name not in data:
raise AttributeError(f"Field '{name}' is not allowed in StrictModel.")
return data[name]
# Try It Yourself
model = StrictModel({"id": 42, "name": "Old Lane 17"})
print(model.id) # Output: 42
# print(model.invalid) # Raises AttributeError: Field 'invalid' is not allowed in StrictModel.
Gotchas and Infinite Recursion
The single most common bug when implementing `__getattribute__` is triggering infinite recursion. If your implementation executes `self.name` or `self.__dict__['name']`, it invokes `__getattribute__` again. Always delegate to `super().__getattribute__(name)` or access `object.__getattribute__(self, name)`.The Fallback Hook: __getattr__
Unlike __getattribute__, __getattr__ is only triggered when standard lookup mechanisms fail (i.e., raising an AttributeError). This makes it ideal for dynamic proxies, lazy loading, and schema-less data wrappers.
pythonclass LazyConfigProxy:
def __init__(self, loader_func):
super().__setattr__('_loader', loader_func)
super().__setattr__('_loaded', False)
def __getattr__(self, name):
# Load heavy state only on first missing attribute lookup
if not super().__getattribute__('_loaded'):
print("Executing lazy load operation...")
config = super().__getattribute__('_loader')()
super().__setattr__('_config', config)
super().__setattr__('_loaded', True)
config = super().__getattribute__('_config')
if name not in config:
raise AttributeError(f"Configuration key '{name}' does not exist.")
return config[name]
# Try It Yourself
def load_db():
return {"host": "localhost", "port": 5432}
config = LazyConfigProxy(load_db)
print("Proxy created. Accessing port...")
print(config.port)
Expected Output:
textProxy created. Accessing port...
Executing lazy load operation...
5432
The Descriptor Protocol
Descriptors allow you to encapsulate attribute management logic into reusable classes. A descriptor is any object that implements at least one of __get__, __set__, or __delete__.
pythonclass TypeValidated:
def __init__(self, expected_type):
self.expected_type = expected_type
def __set_name__(self, owner, name):
# Automatically captures the attribute name during class creation (Python 3.6+)
self.name = f"_{name}"
def __get__(self, instance, owner):
if instance is None:
return self
return getattr(instance, self.name, None)
def __set__(self, instance, value):
if not isinstance(value, self.expected_type):
raise TypeError(f"Expected {self.expected_type.__name__}, got {type(value).__name__}")
setattr(instance, self.name, value)
class User:
age = TypeValidated(int)
name = TypeValidated(str)
def __init__(self, name: str, age: int):
self.name = name
self.age = age
# Try It Yourself
u = User("Alice", 30)
print(u.name) # Alice
# u.age = "thirty" # Raises TypeError: Expected int, got str
Performance Considerations
Dynamic introspection hooks like __getattribute__ and __getattr__ bypass C-optimized attribute caches in the Python interpreter. Heavy reliance on unconditional attribute interception can degrade performance in tight loops. Use descriptors for localized validation or caching instead of rewriting global lookups via __getattribute__ when possible.
Key Takeaways
__getattribute__runs on every attribute access; always usesuper()to fetch state and prevent infinite recursion.__getattr__acts as a safe fallback executed strictly when normal attribute resolution fails.- Data descriptors (
__get__+__set__) take precedence over instance dictionary attributes. - Use
__set_name__in custom descriptors to automatically capture the attribute’s variable name without duplication.
Bridging Python with native compiled libraries bypasses the Global Interpreter Lock (GIL) and optimizes heavy computational loops via Foreign Function Interfaces (FFI).
The Built-in Approach: Ctypes
ctypes is Python’s built-in foreign function library. It provides C-compatible data types and allows calling functions in DLLs or shared libraries without writing custom C wrapper extensions.
Consider a simple C file, math_ops.c, compiled into a shared library (libmath.so on Linux, libmath.dylib on macOS):
c// math_ops.c
// Compile: gcc -shared -fPIC -O3 math_ops.c -o libmath.so
float compute_heavy(float a, float b, int iterations) {
float result = a;
for (int i = 0; i < iterations; i++) {
result += (a * b) / (i + 1.0f);
}
return result;
}
To load and call this library using ctypes, explicitly declare function argument types (argtypes) and return types (restype) to ensure safe pointer casting and prevent segmentation faults.
pythonimport ctypes
import os
path = os.path.abspath("libmath.so")
lib = ctypes.CDLL(path)
# Define function signature for strict type checking and safety
lib.compute_heavy.argtypes = [ctypes.c_float, ctypes.c_float, ctypes.c_int]
lib.compute_heavy.restype = ctypes.c_float
# Execute the native routine
res = lib.compute_heavy(1.5, 2.5, 1_000_000)
print(f"Ctypes Result: {res:.4f}")
The Advanced Approach: CFFI
While ctypes relies on Python code to map types, cffi (C Foreign Function Interface) parses real C declarations directly. This minimizes boilerplate, improves readability, and handles complex structures or callbacks natively.
Install CFFI via pip install cffi and use its API mode to bind the same shared library:
pythonfrom cffi import FFI
ffi = FFI()
# Declare the C signature directly in C syntax
ffi.cdef("""
float compute_heavy(float a, float b, int iterations);
""")
# Load the shared library
lib = ffi.dlopen("./libmath.so")
# Call natively
res = lib.compute_heavy(1.5, 2.5, 1_000_000)
print(f"CFFI Result: {res:.4f}")
Performance Considerations and Edge Cases
- GIL Release: Neither
ctypesnorcffiautomatically releases the GIL when entering C code. If the native function performs long-running CPU-bound execution, other Python threads remain blocked unless the C code explicitly handles Python thread states (rare with raw FFIs) or you use alternative architectures. - Overhead of Small Calls: FFI calls carry minor Python-to-C transition overhead. Avoid wrapping micro-operations (e.g., calling a C function for every single element in a loop); instead, pass a pointer to a contiguous buffer (like a NumPy array or
ctypesarray) and process the batch in C.
Try It Yourself
Save the C code to math_ops.c, compile it for your platform (gcc -shared -fPIC -O3 math_ops.c -o libmath.so), run either Python snippet, and observe the sub-millisecond execution times for millions of iterations.
Key Takeaways
- Use `ctypes` for zero-dependency native loading using built-in Python modules.
- Use `cffi` when working with complex C header files, structures, and native C syntax declarations.
- Always define explicit `argtypes` and `restype` in `ctypes` to prevent memory corruption and segmentation faults.
- Batch operations into native code rather than making tight, repetitive FFI calls across the Python-C boundary to maximize throughput.
Python relies primarily on reference counting for memory management, supplemented by a generational cyclic garbage collector (gc module) to detect and purge isolated reference loops that reference counting alone cannot reclaim. Understanding how to inspect, tune, and manually trigger this collector is vital for preventing memory leaks in long-running services.
Understanding Reference Cycles
A reference cycle occurs when two or more objects reference each other, ensuring their reference counts never drop to zero even when they are no longer reachable from any namespace or variable.
pythonimport gc
class Node:
def __init__(self, name):
self.name = name
self.parent = None
self.children = []
def add_child(self, child):
child.parent = self
self.children.append(child)
# Create cyclic reference
root = Node("root")
child = Node("child")
root.add_child(child)
# Remove global references
del root
del child
# Cycle remains in memory until generational GC collects it
unreachable = gc.collect()
print(f"Unreachable objects collected: {unreachable}")
Generational Garbage Collection
CPython categorizes objects into three generations (0, 1, and 2) based on survival across collection cycles:
- Generation 0: Youngest objects, checked frequently.
- Generation 1: Objects surviving one collection cycle.
- Generation 2: Long-lived objects, collected least frequently.
pythonimport gc
# Inspect generation thresholds (collections vs allocations)
print("Current thresholds:", gc.get_threshold())
# Temporarily disable automatic collection during high-throughput batches
gc.disable()
try:
# Perform latency-sensitive batch operation
pass
finally:
gc.enable()
gc.collect()
Key Takeaways
- Reference counting handles 99% of deallocations instantaneously upon leaving scope.
- The
gcmodule is specifically designed to identify and collect cyclical references. - Use
weakref.reforweakref.proxyfor parent/observer relationships to prevent cycles from forming.
Python executes source code by first compiling it into low-level instructions (bytecode) for the Python Virtual Machine (PVM). By utilizing the built-in dis module, developers can inspect these instructions to uncover performance bottlenecks, hidden overhead, and optimization opportunities in critical code paths.
Inspecting Bytecode with the dis Module
The dis module (disassembler) translates raw Python bytecode objects into human-readable instruction sequences. Every function in Python possesses a __code__ attribute containing a co_code bytecode string alongside metadata like constants and variable names.
pythonimport dis
def calculate_total(price, tax_rate):
return price * (1 + tax_rate)
dis.dis(calculate_total)
Expected Output
text 4 0 RESUME 여자 0
5 2 LOAD_FAST 0 (price)
4 LOAD_FAST 1 (tax_rate)
6 LOAD_CONST 1 (1)
8 BINARY_OP 0 (+)
10 BINARY_OP ( * )
14 RETURN_VALUE
Each row corresponds to a PVM opcode:
- Line Number: The source code line (
4,5). - Offset: The bytecode instruction offset in bytes (
0,2,4…). - Opcode Name: Low-level instruction (
LOAD_FAST,BINARY_OP,RETURN_VALUE). - Oparg & Value: Numerical operand argument and human-readable resolution (
price,1).
Comparing Implementation Performance via Bytecode
Bytecode analysis reveals why certain idioms execute significantly faster in Python. For instance, comparing list instantiation:
pythonimport dis
print("--- [] Literal ---")
dis.dis("[]")
print("\n--- list() Constructor ---")
dis.dis("list()")
text--- [] Literal ---
1 0 BUILD_LIST 0
2 RETURN_VALUE
--- list() Constructor ---
1 0 PUSH_NULL
2 LOAD_NAME 0 (list)
4 CALL 0
6 RETURN_VALUE
The literal [] issues a single dedicated opcode BUILD_LIST, while list() involves global namespace lookup (LOAD_NAME) and function call overhead (CALL).
Key Takeaways
- Bytecode inspection demystifies Python’s runtime execution model.
- Prefer built-in literals (
[],{}) over constructors (list(),dict()) to avoid global lookups. - Use
dis.dis()to verify compiler optimizations across Python versions.
CPython compiles source code into bytecode executed by a stack-based virtual machine, which modern versions enhance with adaptive specializing execution and a Tier 1/Tier 2 JIT architecture. Understanding this pipeline allows developers to write Python patterns that minimize interpreter overhead and maximize inline-cache efficiency.
The Compilation and Execution Pipeline
CPython’s lifecycle processes raw text through a tokenizer, abstract syntax tree (AST) generator, and a compiler yielding a code object containing bytecode. The core virtual machine (Python/ceval.c) evaluates this bytecode using a massive evaluation loop.
To analyze bytecode generation and inspect how specialized instructions are formed, use the built-in dis module:
pythonimport dis
def compute_total(items):
total = 0
for x in items:
total += x
return total
dis.dis(compute_total)
3 0 RESUME Général 0
2 LOAD_CONST 1 (0)
4 STORE_FAST 1 (total)
4 6 GET_ITER
…
Specializing Adaptive Bytecode and Inline Caches
Modern CPython (3.11+) utilizes adaptive bytecode. Instructions start as generic operations, but during execution, they monitor their inputs (type profiling) and specialize themselves. For instance, a generic BINARY_OP transforms into BINARY_OP_ADD_INT or BINARY_OP_ADD_FLOAT if it observes consistent types.
This specialization relies on inline caches (ICs). Consider the performance difference of uniform versus polymorphic loops:
pythonimport time
def process_ints(data):
acc = 0
for val in data:
acc += val # Specialized rapidly to integer addition
return acc
def process_mixed(data):
acc = 0
for val in data:
acc += val # Polymorphic fallback; forces de-optimization
return acc
ints = list(range(1_000_000))
mixed = list(range(500_000)) + [float(x) for x in range(500_000)]
start = time.perf_counter()
process_ints(ints)
print(f"Uniform Time: {time.perf_counter() - start:.4f}s")
start = time.perf_counter()
process_mixed(mixed)
print(f"Polymorphic Time: {time.perf_counter() - start:.4f}s")
Mixing types in performance-critical loops forces CPython’s adaptive interpreter to repeatedly invalidate cache entries, degrading performance to slow generic paths.
Leveraging the Tier 2 JIT Compiler
Python 3.13 introduces an experimental Tier 2 JIT compiler. Unlike the Tier 1 stack-based interpreter, Tier 2 translates hot execution traces into a sequence of Superinstructions or machine code representations (using copy-and-patch technology).
To write JIT-friendly code, focus on reducing dynamic dispatch overhead:
- Avoid global variable lookups inside hot loops: Globals require dictionary lookups. Use local bindings (
local_func = math.sin). - Keep signatures stable: Avoid polymorphic functions that accept changing types per invocation.
- Utilize
__slots__: Reduces instance dictionary overhead, helping attribute lookups stabilize.
python# JIT-Friendly Class Structure
class Point:
__slots__ = ('x', 'y')
def __init__(self, x: float, y: float):
self.x = x
self.y = y
def distance_squared(p: Point) -> float:
# Stable attribute access maps efficiently down to direct memory offsets
return p.x * p.x + p.y * p.y
Key Takeaways
- CPython transforms source code into bytecode executed via a stack virtual machine, enhanced by adaptive runtime specialization.
- Inline caches accelerate operations dynamically, but polymorphic inputs trigger frequent de-optimizations and slow down execution.
- Maximizing execution speed requires type consistency in loops, local variable binding, and minimized global namespace lookups.
- Features like `__slots__` stabilize object layouts, aligning with CPython's optimization assumptions for attribute access.
Domain-Specific Languages (DSLs) let you express business logic or configuration rules cleanly by bypassing general-purpose syntax overhead. This chapter implements a zero-dependency, functional parsing combinator pattern in Python 3.12+ to construct a robust mini-language for dynamic UI rules.
The Parsing Combinator Architecture
A parser combinator is a higher-order function that accepts a string input, attempts to consume a specific pattern, and returns a tuple containing the parsed abstract syntax tree (AST) node alongside the unconsumed remaining input. If parsing fails, it returns None.
pythonfrom __future__ import annotations
from dataclasses import dataclass
from typing import Callable, Optional, Tuple, Any
@dataclass(frozen=True)
class ParseResult:
value: Any
remainder: str
Parser = Callable[[str], Optional[ParseResult]]
def lit(expected: str) -> Parser:
"""Matches an exact literal string."""
def parse(input_str: str) -> Optional[ParseResult]:
if input_str.startswith(expected):
return ParseResult(expected, input_str[len(expected):])
return None
return parse
def seq(p1: Parser, p2: Parser) -> Parser:
"""Sequencing combinator: matches p1 then p2."""
def parse(input_str: str) -> Optional[ParseResult]:
res1 = p1(input_str)
if not res1:
return None
res2 = p2(res1.remainder)
if not res2:
return None
return ParseResult((res1.value, res2.value), res2.remainder)
return parse
def alt(p1: Parser, p2: Parser) -> Parser:
"""Alternation combinator: tries p1, falls back to p2."""
def parse(input_str: str) -> Optional[ParseResult]:
return p1(input_str) or p2(input_str)
return parse
The lit, seq, and alt functions form the foundational algebra. Because parsers are first-class citizens, they can be composed dynamically to handle complex grammars without external parsing generators like ANTLR or Lark.
Building a Rule-Based DSL
Consider a DSL designed to evaluate feature-flag conditions (e.g., user.tier == "enterprise" OR user.beta == true). We will build parsers for identifiers, comparison operators, and boolean logic expressions.
pythonimport string
def whitespace(parser: Parser) -> Parser:
"""Wraps a parser to consume leading whitespace."""
def parse(input_str: str) -> Optional[ParseResult]:
stripped = input_str.lstrip(string.whitespace)
return parser(stripped)
return parse
def parse_identifier(input_str: str) -> Optional[ParseResult]:
"""Parses variable names like user.tier or beta."""
chars = []
i = 0
while i < len(input_str) and (input_str[i].isalnum() or input_str[i] in "._"):
chars.append(input_str[i])
i += 1
if not chars:
return None
return ParseResult("".join(chars), input_str[i:])
def parse_string_literal(input_str: str) -> Optional[ParseResult]:
"""Parses double-quoted string literals."""
if not input_str.startswith('"'):
return None
end_idx = input_str.find('"', 1)
if end_idx == -1:
return None
return ParseResult(input_str[1:end_idx], input_str[end_idx + 1:])
def parse_comparison(input_str: str) -> Optional[ParseResult]:
"""Parses comparisons like field == "value"."""
res_id = whitespace(parse_identifier)(input_str)
if not res_id:
return None
res_op = whitespace(alt(lit("=="), lit("!=")))(res_id.remainder)
if not res_op:
return None
res_val = whitespace(parse_string_literal)(res_op.remainder)
if not res_val:
return None
ast = {
"type": "Comparison",
"left": res_id.value,
"operator": res_op.value,
"right": res_val.value
}
return ParseResult(ast, res_val.remainder)
Evaluating the Generated AST
Once your parser converts a raw text stream into a structured AST, evaluation becomes a pure, recursive tree walk over Python dictionaries.
pythondef evaluate_ast(node: dict, context: dict) -> bool:
if node["type"] == "Comparison":
keys = node["left"].split(".")
val = context
for key in keys:
if not isinstance(val, dict) or key not in val:
return False
val = val[key]
if node["operator"] == "==":
return val == node["right"]
if node["operator"] == "!=":
return val != node["right"]
raise ValueError(f"Unknown node type: {node['type']}")
# Try It Yourself
dsl_code = 'user.tier == "enterprise"'
parsed = whitespace(parse_comparison)(dsl_code)
if parsed and parsed.remainder == "":
ast = parsed.value
print("Generated AST:", ast)
context = {"user": {"tier": "enterprise"}}
print("Evaluation Result:", evaluate_ast(ast, context))
else:
print("Syntax Error or Unconsumed Input")
Expected Output:
textGenerated AST: {'type': 'Comparison', 'left': 'user.tier', 'operator': '==', 'right': 'enterprise'}
Evaluation Result: True
Performance and Edge Cases
- Left Recursion: Standard recursive descent combinators will cause infinite recursion loops if grammar rules are left-recursive (e.g.,
expr -> expr + term). Structure your grammar rules iteratively or right-recursively. - Backtracking Overhead:
altcombinators cause performance degradation when paths overlap extensively (exponential backtracking). Mitigate this by factoring out common prefixes or introducing lookahead tokens. - Error Reporting: Basic combinators fail silently with
None. Production-grade systems should track the maximum consumed input index (high_water_mark) to report exact line and column numbers on failure.
Key Takeaways
- Parser combinators leverage Python's first-class functions to compose modular, testable language grammars without external dependencies. - Separating AST parsing from AST evaluation keeps your DSL clean, secure, and easily extensible. - Whitespace handling must be applied explicitly or via wrapper combinators to prevent parsing stalls.Concepts Python avancés
Au-delà des bases, Python offre de nombreuses fonctionnalités avancées pour écrire du code concis, efficace et robuste. Des sujets tels que la compréhension des listes, les générateurs et la gestion des exceptions peuvent vous aider à faire passer vos compétences en programmation au niveau supérieur.
1. Compréhensions des listes
Les compréhensions de listes fournissent un moyen concis de créer des listes. Ils peuvent remplacer les boucles dans de nombreux cas :
python# Traditional loop
squares = []
for i in range(10):
squares.append(i ** 2)
# Using list comprehension
squares = [i ** 2 for i in range(10)]
print(squares)
2. Gestion des exceptions
Utilisez des blocs try-sauf pour gérer efficacement les erreurs et les exceptions :
pythontry:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
# is executed if try did not work
# and the exception is not the same as in except
print("Not execute but no ZeroDivisionError.")
finally:
# is always executed
print("Execution complete.")
# Outputs an error message
# and a final execution statement
3. Générateurs
Les générateurs vous permettent d'itérer efficacement sur de grands ensembles de données sans stocker la séquence entière en mémoire :
pythondef count_up_to(n):
count = 1
while count <= n:
yield count
count += 1
for number in count_up_to(5):
print(number)
# Outputs: 1 2 3 4 5
L'exploration de ces sujets avancés peut améliorer considérablement vos capacités de programmation Python.