Bienvenido a Python
Python es un lenguaje de programación versátil y de alto nivel conocido por su legibilidad y amplio apoyo de la comunidad. Desarrollado a principios de la década de 1990, enfatiza la sintaxis clara y concisa, lo que lo convierte en una excelente opción tanto para principiantes como para profesionales. La extensa biblioteca estándar de Python y su próspero ecosistema de paquetes de terceros permiten su uso en muchos campos, desde desarrollo web y análisis de datos hasta inteligencia artificial y computación científica. Su facilidad de aprendizaje, junto con sus poderosas capacidades, hacen de Python una habilidad valiosa para cualquiera que busque sumergirse en la programación o avanzar en su carrera tecnológica.
Introducción a Python
Cómo instalar Python y escribir tu primer "¡Hola, mundo!" programa.
Python es uno de los lenguajes de programación más populares debido a su simplicidad y versatilidad. Ya seas un codificador principiante o experimentado, instalar Python y ejecutar tu primer script es un proceso sencillo.
Paso 1: descargar e instalar Python
-
Visite el sitio web oficial
Vaya a Python.org y descargue la última versión estable de Python para su sistema operativo (Windows, macOS o Linux). -
Ejecute el instalador
-
Para Windows: haga doble clic en el archivo
.exedescargado y marque "Agregar Python a la RUTA" antes de hacer clic en "Instalar". Ahora". -
Para Mac: descargue el instalador de macOS y siga las instrucciones de configuración.
-
Para Linux: use el administrador de paquetes (por ejemplo, para Ubuntu).
shsudo apt install python3 -
Verificar la instalación
Abra una terminal o símbolo del sistema y escriba:
shpython --version
o
shpython3 --version
Esto debería mostrar la versión de Python instalada.
Paso 2: Elija un IDE o editor de código
Python viene con IDLE, un entorno de desarrollo integrado (IDE) integrado, que es ideal para principiantes. Sin embargo, los usuarios más avanzados suelen preferir editores como:
-
Código VS – Ligero y potente, con extensiones de Python.
-
PyCharm – IDE rico en funciones para desarrolladores profesionales.
-
Jupyter Notebook: lo mejor para ciencia de datos y codificación interactiva.
Para principiantes, iniciar IDLE (instalado con Python) es la forma más sencilla de comenzar a codificar.
Paso 3: escriba y ejecute su primer script de Python
-
Usando IDLE:
-
Abrir IDLE.
-
Haga clic en Archivo → Nuevo archivo.
Escriba el siguiente código:
pythonprint("Hello, World!") -
-
Guarde el archivo con una extensión
.py(por ejemplo,hello.py). -
Ejecútelo seleccionando Ejecutar → Ejecutar módulo o presionando
F5. -
Usando la línea de comando:
-
Abra una terminal o símbolo del sistema.
-
Navega a la carpeta donde guardaste
hello.py. -
Ejecute el script escribiendo:
python hola.py -
-
Deberías ver el resultado:
¡Hola mundo!
¡Felicitaciones! Ha instalado Python con éxito y ha ejecutado su primer script. 🎉
Para más detalles, visite la documentación oficial de Python en docs.python.org. ¡Feliz codificación! 🚀
Sintaxis de Python
1. Sangría de Python (sin llaves para bloques)
Python usa indentation (espacios en blanco) para definir bloques de código en lugar de llaves {} como en otros lenguajes. Esto hace que el código Python sea más legible pero también significa que una sangría incorrecta provocará errores.
Ejemplo correcto:
pythonif 5 > 3:
print("Five is greater than three") # Proper indentation
Ejemplo incorrecto (genera error de sangría):
pythonif 5 > 3:
print("This will cause an error!") # No indentation
Python aplica la sangría para mejorar la estructura y la legibilidad del código. La sangría recomendada es 4 espacios por nivel.
2. Indexación de base cero
Python sigue indexación basada en cero, lo que significa que el primer elemento de una secuencia (como una lista, cadena o tupla) comienza en index 0, no 1.
Ejemplo:
pythonfruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Outputs: apple
print(fruits[2]) # Outputs: cherry
Ejemplo incorrecto (IndexError):
pythonprint(fruits[3]) # IndexError: list index out of range
Dado que Python comienza a contar desde 0, intentar acceder a un índice que es igual o mayor que la longitud de la secuencia genera un error.
3. Comentarios en Python
Los comentarios ayudan a los desarrolladores a comprender el código agregando explicaciones. Python admite comentarios de una sola línea y de varias líneas.
Comentario de una sola línea:
python# This is a single-line comment
print("Hello, World!") # Inline comment
Comentario de varias líneas:
python"""
This is a multi-line comment.
It is often used for documentation.
"""
print("Hello, World!")
Aunque las comillas triples se pueden utilizar para comentarios de varias líneas, están destinadas principalmente a docstrings, que son comentarios especiales colocados dentro de funciones de documentación.
4. Sensibilidad a mayúsculas y minúsculas
Python distingue entre mayúsculas y minúsculas, lo que significa que trata las letras mayúsculas y minúsculas de manera diferente. Los nombres de variables, nombres de funciones y palabras clave se deben utilizar de forma coherente.
Ejemplo:
pythonmyVar = 5
MyVar = 10
print(myVar) # Outputs: 5
print(MyVar) # Outputs: 10 (different variable)
Aquí, myVar y MyVar se consideran dos variables diferentes debido a su capitalización.
Ejemplo incorrecto:
pythonPrint("Hello") # NameError: name 'Print' is not defined
Las funciones integradas de Python como print() deben escribirse en minúsculas.
5. Variables y escritura dinámica
Python está tipificado dinámicamente, lo que significa que no es necesario declarar explícitamente el tipo de una variable. El tipo se determina automáticamente en función del valor asignado.
Ejemplo:
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'>
Reasignación de diferentes tipos de datos:
pythona = 5 # Initially an integer
a = "Python" # Now reassigned as a string
print(a) # Outputs: Python
Dado que Python permite la escritura dinámica, el tipo de una variable puede cambiar durante la ejecución.
Conclusión
Comprender la sintaxis básica de Python es esencial para escribir código limpio y eficiente. Las conclusiones clave incluyen:
-
Python aplica indentación en lugar de llaves para los bloques de código.
-
Indexación basada en cero significa que el primer elemento de una secuencia está en el índice
0. -
Comentarios mejoran la legibilidad del código y pueden ser de una sola línea (
#) o multilínea (""" """). -
Python distingue entre mayúsculas y minúsculas, por lo que
Varyvarse tratan como diferentes variables. -
Python admite tipificación dinámica, lo que permite que las variables cambien de tipo.
Dominar estos conceptos básicos proporcionará una base sólida para aprender conceptos más avanzados de Python. ¡Feliz codificación! 🚀
imprimir
La función print() en Python se utiliza para mostrar la salida en la pantalla. Es una de las funciones más utilizadas, especialmente para la depuración y la interacción del usuario. En esta breve guía, exploraremos diferentes formas de usar print() de manera efectiva, incluido cómo imprimir múltiples valores, formatear la salida y controlar los separadores y caracteres finales.
1. Básico print() Uso
La forma más sencilla de utilizar print() es pasar una cadena o un número dentro del paréntesis:
pythonprint("Hello, World!") # Outputs: Hello, World!
print(42) # Outputs: 42
Puedes imprimir múltiples valores separándolos con una coma ,:
pythonprint("Hello", "Python") # Outputs: Hello Python
De forma predeterminada, Python inserta un espacio entre los valores.
2. Usando el sep Parámetro
El parámetro sep controla el separador entre múltiples valores en print(). Por defecto, es un espacio, pero puedes cambiarlo por cualquier otra cosa:
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. Usando el parámetro <code inline="">end</code></span></h2>
<p><span style="font-family: Roboto;">De forma predeterminada, <code inline="">print()</code> agrega una nueva línea (<code inline="">\n</code>) al final de la salida. Puede cambiar este comportamiento utilizando el parámetro <code inline="">end</code>:</span></p>
```python
print("Hello", end=" ")
print("World!")
# Outputs: Hello World! (on the same line)
Aquí, end=" " reemplaza la nueva línea predeterminada con un espacio.
4. Variables de impresión
Puedes imprimir variables como cadenas literales:
pythonname = "Alice"
age = 25
print("Name:", name, "Age:", age)
# Outputs: Name: Alice Age: 25
Como alternativa, puede utilizar f-strings para obtener una salida más limpia:
pythonprint(f"Name: {name}, Age: {age}")
# Outputs: Name: Alice, Age: 25
5. Impresión de caracteres especiales
Utilice secuencias de escape para formatear la salida:
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;">Conclusión</span></h2>
<p><span style="font-family: Roboto;">La función <code inline="">print()</code> es una poderosa herramienta en Python que le permite mostrar la salida de varias maneras. Conclusiones clave:</span></p>
<ul>
<li>
<p><span style="font-family: Roboto;">Utilice <code inline="">print(valor1, valor2,…)</code> para imprimir múltiples valores.</span></p>
</li>
<li>
<p><span style="font-family: Roboto;">Cambie el separador usando <code inline="">sep="custom_separator"</code>.</span></p>
</li>
<li>
<p><span style="font-family: Roboto;">Control de finales de línea con <code inline="">end="custom_end"</code>.</span></p>
</li>
<li>
<p><span style="font-family: Roboto;">Utilice <code inline="">f-strings</code> para un mejor formato.</span></p>
</li>
</ul>
<p><span style="font-family: Roboto;">Dominar <code inline="">print()</code> hará que la depuración y el manejo de resultados en Python sean mucho más fáciles.</span></p>
Variables
Las variables se utilizan para almacenar datos en Python. Actúan como contenedores con nombre para valores de diferentes tipos (números, cadenas, etc.). Las variables de Python deben seguir ciertas reglas de nomenclatura:
- El nombre de una variable debe comenzar con una letra o un guión bajo (
_). - El nombre de una variable no puede comenzar con un número.
- Una variable no puede usar palabras clave reservadas de Python (consulte el módulo
keyword).
1. Creando variables
En Python, las variables se crean automáticamente cuando les asignas un valor usando el operador de asignación =.
No se necesita ninguna declaración explícita.
pythona = 10
b = "Hello"
c = 3.14
print(a, b, c) # Outputs: 10 Hello 3.14
2. Asignación de múltiples variables
En los casos de modificar dos o más variables a la vez y utilizar ciertos valores para cálculos en curso, es útil cambiarlo simultáneamente.
pythona, b = 4, 5
print(a) # Outputs: 4
print(b) # Outputs: 5
```<h2><span style="font-family: Roboto;">3. Uso de entradas para crear variables</span></h2>
<p><span style="font-family: Roboto;">
Las variables también se pueden crear a partir de la entrada del usuario usando la función <code>input()</code>.
De forma predeterminada, <code>input()</code> devuelve una cadena, pero puedes convertirla a otros tipos si es necesario.
</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. Conversión de tipo
A veces es posible que necesite realizar conversiones entre tipos de datos (por ejemplo, de cadena a entero).
Las funciones comunes incluyen int(), float() y 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. Operadores y variables
Las variables se pueden utilizar junto con arithmetic, comparación, y otros operadores de asignación. Consulte las secciones dedicadas a operadores para obtener detalles y ejemplos.
Operaciones binarias en Python
1. Operadores aritméticos
Los operadores aritméticos realizan cálculos matemáticos entre dos operandos. Python admite suma, resta, multiplicación, división, módulo, división mínima y exponenciación.
Ejemplos:
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)
Los operadores aritméticos siempre devuelven un nuevo valor sin cambiar las variables originales.
2. Operadores de comparación
Los operadores de comparación comparan dos valores y devuelven un resultado booleano (True o False).
Estos incluyen igualdad, desigualdad, mayor/menor que y sus combinaciones.
Ejemplos:
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
Los resultados de la comparación se utilizan a menudo dentro de if declaraciones o bucles para controlar el flujo del programa.
3. Operadores lógicos
Los operadores lógicos combinan valores booleanos y devuelven True o False.
Los tres operadores son y, or y not (unario).
Ejemplos:
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)
Los operadores lógicos se utilizan con frecuencia en condiciones, p. comprobar varios requisitos a la vez.
4. Operadores bit a bit
Los operadores bit a bit actúan sobre las representaciones binarias de números enteros.
Incluyen & (Y), | (O), ^ (XOR), << (desplazamiento a la izquierda) y >> (desplazamiento a la derecha).
Ejemplos:
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)
Las operaciones bit a bit se utilizan a menudo en programación de bajo nivel, criptografía u optimización del rendimiento.
5. Operadores de asignación
Los operadores de asignación asignan valores a las variables. También pueden combinar la asignación con operaciones aritméticas o bit a bit.
Ejemplos:
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
Los operadores de asignación son una forma abreviada de actualizar una variable en su lugar, lo que hace que el código sea más conciso.
Enteros
Los números enteros son números enteros, ya sean positivos, negativos o cero. Son uno de los tipos numéricos básicos de Python y se utilizan para operaciones matemáticas.
1. Creando números enteros
Se pueden crear números enteros asignando valores enteros a las variables:
pythona = 10
b = -5
c = 0
print(a, b, c)
2. Operaciones con números enteros
Los números enteros admiten varias operaciones aritméticas:
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. Conversión de tipo
Conversión de otros tipos a números enteros:
pythonnum = int("123")
print(num) # Outputs: 123
num = int(3.1415)
print(num) # Outputs: 3
Flotadores
Los flotantes representan números reales que pueden tener partes fraccionarias. Son otro tipo numérico básico en Python y son esenciales para los cálculos decimales.
1. Creando flotantes
Los flotantes se pueden crear asignando valores decimales a las variables:
pythona = 3.1415
b = -0.5
c = 100.0
print(a, b, c)
2. Operaciones flotantes
Los flotadores admiten varias operaciones aritméticas:
pythonprint(2.5 + 1.5) # Addition
print(5.0 / 2) # Division
print(3.1415 ** 2) # Exponentiation
print(7.3 % 3) # Modulus
3. Conversión de tipo
Conversión de otros tipos a flotantes:
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
Booleanos en Python
El tipo de datos bool representa valores lógicos y tiene exactamente dos valores: True y False. En Python, bool es una subclase de int (donde True == 1 y False == 0).
1. Valores Verdaderos y Falsos (Truthiness)
- Falsy (evaluado como False):
None,False,0, cadenas vacías, listas vacías, tuplas vacías, diccionarios vacíos. - Truthy (evaluado como True): Cualquier número distinto de cero y cualquier colección no vacía.
Cadenas
Las cadenas son secuencias de caracteres utilizados para representar texto. Son inmutables y se pueden definir mediante comillas simples, dobles o triples para cadenas de varias líneas.
1. Creando cadenas
Se pueden crear cadenas usando diferentes tipos de comillas:
pythona = 'Hello, World!'
b = "Python is great"
c = """This is a
multi-line string"""
print(a, b, c, sep='\n')
2. Operaciones de cadena
Las cadenas admiten varias operaciones como concatenación y repetición:
pythonprint("Hello" + " World") # Concatenation
print("Hello" * 3) # Repetition
print("Hello"[0]) # Accessing characters
print("Hello"[1:3]) # Slicing
3. Métodos de cadena
Las cadenas tienen varios métodos integrados para su manipulación:
pythontext = "hello world"
print(text.upper()) # Outputs: HELLO WORLD
print(text.lower()) # Outputs: hello world
print(text.replace("world", "earth")) # Outputs: hello earth
Funciones de cadena
Las cadenas tienen muchos métodos útiles para recortar, dividir y reemplazar texto.
Recortar con .strip()
pythontext = " hello world "
print(text.strip()) # "hello world"
print(text.lstrip()) # "hello world "
print(text.rstrip()) # " hello world"
División de cadenas
pythonline = "apple,banana,cherry"
print(line.split(",")) # ['apple', 'banana', 'cherry']
words = "one two three".split()
print(words) # ['one', 'two', 'three']
Reemplazar texto
pythonsentence = "I like cats"
print(sentence.replace("cats", "dogs"))
# "I like dogs"
Unir cadenas
pythonparts = ["2025", "09", "26"]
date = "-".join(parts)
print(date) # "2025-09-26"
Errores comunes
.strip()elimina los espacios en blanco de forma predeterminada, pero puedes pasar caracteres:"hello!!".strip("!")..split()sin argumentos se divide en cualquier espacio en blanco, no solo espacios..replace()reemplaza todas las ocurrencias, a menos que pase un tercer argumento (recuento máximo)..join()requiere que todos los elementos sean cadenas (no números).
Formato de cadenas y métodos de mayúsculas y minúsculas
Python ofrece varios métodos para formatear cadenas y ajustar mayúsculas y minúsculas. Esto ayuda a crear resultados dinámicos y controlar la apariencia del texto.
Formateando con .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)
Conversión de caso
pythontext = "Hello World"
print(text.upper()) # "HELLO WORLD"
print(text.lower()) # "hello world"
Partición de cadenas
pythonline = "user:password"
print(line.partition(":"))
# ('user', ':', 'password')
.partition() se divide en una tupla de 3 partes:
texto anterior, el propio separador y texto posterior.
Errores comunes
- El uso de
.format()con claves faltantes o incorrectas generaKeyErroroIndexError. .upper()/.lower()crean una nueva cadena, no modifican la original..partition()solo se divide en la primera aparición del separador.
Listas
Las listas son secuencias versátiles y mutables que se utilizan para almacenar colecciones de elementos. Se definen entre corchetes [] y admiten una variedad de operaciones de modificación y acceso.
1. Creando una lista
Definir una lista con varios elementos:
pythonmy_list = [1, 2, 3, "Python", True]
print(my_list)
2. Acceso y modificación de listas
Las listas admiten indexación, división y métodos para modificar su contenido:
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. Lista de comprensiones
Las listas por comprensión proporcionan una forma concisa de crear listas iterando sobre secuencias y, opcionalmente, aplicando condiciones:
python# Creating a list of squares for numbers 0 to 9
squares = [x**2 for x in range(10)]
print(squares)
Listas de indexación
En Python, las listas son colecciones ordenadas y puede acceder a los elementos utilizando su index. La indexación comienza en 0 para el primer elemento. Los índices negativos cuentan desde el final de la lista, siendo -1 el último elemento.
Indización básica
pythonfruits = ["apple", "banana", "cherry"]
print(fruits[0]) # Outputs: apple
print(fruits[-1]) # Outputs: cherry
Modificación de elementos mediante índice
pythonnumbers = [10, 20, 30]
numbers[1] = 25
print(numbers) # Outputs: [10, 25, 30]
Errores comunes
- IndexError: Accediendo a un índice fuera del rango de la lista.
- Mutable vs Inmutable: Solo las listas mutables se pueden modificar mediante indexación; las tuplas no admiten la asignación.
Listas de corte
Slicing le permite extraer una parte de una lista usando la sintaxis list[start:stop:step]. El índice start es inclusivo, stop es exclusivo y step define el intervalo.
Rebanado básico
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
Invertir una lista
pythonprint(numbers[::-1]) # Outputs: [5, 4, 3, 2, 1, 0]
Errores comunes
- El índice de parada es exclusivo;
list[start:stop]no incluye el elemento enstop. - Los índices negativos pueden ser complicados; asegúrese de que se utilicen correctamente con la longitud de la lista.
- Slicing devuelve una nueva lista; no modifica el original a menos que se le vuelva a asignar.
Funciones y métodos específicos de la lista
Python proporciona muchas funciones y métodos integrados específicamente para que las listas manipulen, consulten y transformen datos de manera eficiente.
Métodos comunes
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)
Otros métodos útiles
pythonnumbers = [3, 1, 4, 2]
numbers.sort() # Sorts in ascending order
numbers.reverse() # Reverses the list
print(numbers)
Funciones integradas para listas
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
Trabajar con varias listas
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() es útil cuando necesita tanto la posición como el valor de un elemento de lista.
zip() es útil cuando se combinan dos o más listas elemento por elemento.
Errores comunes
- Métodos como
sort()yreverse()modifican la lista en su lugar y devuelvenNone. - Eliminar elementos que no existen genera
ValueError. - Tenga cuidado con
pop()en listas vacías; generaIndexError. zip()se detiene en la longitud de lista más corta.
Tuplas
Las tuplas son secuencias inmutables que se utilizan para almacenar una colección de elementos. Se definen entre paréntesis () y son útiles cuando desea garantizar la integridad de los datos.
1. Creando una tupla
Una tupla simple que contiene diferentes tipos de datos:
pythonmy_tuple = (10, "hello", 3.14)
print(my_tuple)
2. Accediendo a elementos de tupla
Acceda a los elementos por su índice, similar a las listas:
python# Accessing the first element
print(my_tuple[0]) # Outputs: 10
# Slicing the tuple
print(my_tuple[1:]) # Outputs: ('hello', 3.14)
Dado que las tuplas son inmutables, sus valores no se pueden cambiar después de su creación.
Conjuntos (Sets) en Python
Un conjunto (set) es una colección desordenada de elementos únicos. No permite elementos duplicados.
Sets en comparación con Tuplas
Una tupla es una secuencia ordenada e inmutable que permite duplicados y admite indexación (t[0]). Un conjunto es desordenado, mutable, no admite duplicados ni indexación, pero proporciona búsqueda $O(1)$ instantánea y operaciones de teoría de conjuntos.
Diccionarios
Los diccionarios almacenan datos en pares clave-valor, lo que hace que la búsqueda de datos sea eficiente. Se crean usando llaves {} y se puede acceder a ellos mediante sus claves.
1. Crear un diccionario
Un diccionario básico que asigna frutas a sus colores:
pythonfruit_colors = {
"apple": "red",
"banana": "yellow",
"cherry": "red"
}
2. Acceso y modificación de datos
Acceda a un valor usando su clave, agregue un nuevo par clave-valor o actualice uno existente:
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"
Recorrer claves y valores usando el método items():
pythonfor fruit, color in fruit_colors.items():
print(f"{fruit} is {color}")
Funciones del diccionario
Diccionarios (dict) almacenan datos como pares clave-valor.
Python proporciona métodos como .keys() y .values()
para acceder a las claves y valores por separado.
Claves de acceso
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)
Acceso a valores
pythonprint(person.values()) # dict_values(['Alice', 25, 'Zurich'])
# Loop through values
for value in person.values():
print("Value:", value)
Usar claves y valores juntos
python# Often combined with a for-loop
for key in person.keys():
print(key, "->", person[key])
Errores comunes
.keys()y.values()devuelven vistas especiales, no listas normales. Si necesita una lista, envuélvala conlist().- Los diccionarios están desordenados antes de Python 3.7. En Python moderno, mantienen el orden de inserción.
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).
Condicionales: if, elif y else
Las declaraciones condicionales en Python le permiten ejecutar bloques de código en función de si una condición es Verdadera o Falsa. La estructura básica usa if, seguido opcionalmente de elif (si no) y else como respaldo.
1. Declaración if básica
Utilice la instrucción if para ejecutar código solo cuando se cumpla una condición:
pythonx = 10
if x > 5:
print("x is greater than 5")
# Outputs: x is greater than 5
2. Declaración if-else
Incluye un bloque else para ejecutar código cuando no se cumple la condición:
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 Cadena
Para múltiples condiciones, use elif para verificar condiciones adicionales:
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
Estas construcciones le permiten crear estructuras sólidas de toma de decisiones en sus programas Python.
para-bucle (Conceptos básicos)
Un bucle for en Python repite el código para cada elemento de una secuencia (como una lista, cadena o rango de números).
A diferencia de while, el número de repeticiones normalmente se conoce de antemano.
Contando con range()
pythonfor i in range(5):
print("Number:", i)
# Prints 0, 1, 2, 3, 4
range(5) genera números desde 0 hasta (pero sin incluir) 5.
Recorrer una lista
pythonfruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print("I like", fruit)
El bucle visita cada elemento de la lista uno por uno.
Recorriendo una cadena
pythonword = "hi!"
for char in word:
print(char)
# Prints h, i, !
Usando break y 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
Errores comunes
- Errores uno por uno: Recuerde que
range(n)se detiene antes den. - Olvidar que
enverifica los elementos:para x en la listaproporciona elementos, no índices. - Mezcla
interrupciónycontinuar:breakfinaliza el ciclo,continuesolo omite el paso actual.
while-bucle (Conceptos básicos)
A while el bucle repite un bloque de código siempre que su condición sea True.
A diferencia de los bucles for, el número de repeticiones no está fijado de antemano.
La condición se verifica antes de cada repetición.
Importante: Tenga cuidado con la condición. Si nunca se convierte en False,
el bucle se ejecutará para siempre (un bucle infinito).
Ejemplo de conteo simple
pythonx = 0
while x < 5:
print("Counted to:", x)
x += 1 # Important: update the counter!
Este bucle comienza en x = 0 y se detiene una vez que x ya no es menor que 5.
Detención anticipada con 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
Aquí usamos mientras que True pero escapamos con break una vez que se cumple una condición.
Omitiendo iteraciones con continue
pythonx = -3
while x <= 3:
x += 1
if x == 0: # skip division by zero
continue
print("1/", x, "=", 1/x)
La instrucción continue omite el paso del ciclo actual y pasa al siguiente.
Errores básicos
- Olvidar actualizar la variable:
Si falta
x += 1, la condición nunca cambia, y el bucle se ejecuta para siempre. - Condiciones demasiado amplias:
mientras que Truees seguro solo si incluye unbreak. adecuado
Declaraciones de control de bucle: break, continue y pass
Python proporciona declaraciones especiales que alteran el flujo normal de los bucles. Son útiles para un control detallado de la iteración, el manejo de casos excepcionales y hacer que el código sea más expresivo.
break — Salir de un bucle
break termina inmediatamente el bucle circundante más cercano, independientemente de la condición del bucle. Se usa comúnmente cuando se cumple una condición objetivo y no se necesita más iteración.
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 — Saltarse una iteración
continue omite el resto de la iteración actual y salta directamente a la siguiente. A menudo se utiliza para filtrar casos no deseados.
pythonfor n in range(5):
if n % 2 == 0:
continue
print(f"Odd: {n}")
# Prints Odd: 1, 3
pass — Declaración de marcador de posición
pass no hace nada y actúa como un marcador de posición sintáctico. Es útil cuando se requiere sintácticamente un bloque de código pero aún no se debe realizar ninguna acción (por ejemplo, durante el desarrollo o en métodos de clase abstractos).
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">Errores comunes</h2>
<ul>
<li><strong>Confuso <code>break</code> con <code>return</code>:</strong> <code>break</code> sale solo del bucle, no de la función. Utilice <code>return</code> para salir de una función por completo.</li>
<li><strong>Bucles infinitos con <code>continue</code>:</strong> En <code> while</code> bucles, colocar <code>continue</code> antes de actualizar las variables del bucle puede causar la condición para no cambiar nunca.</li>
<li><strong>Mal uso de <code>pass</code>:</strong> Dado que <code>pass</code> no hace nada, dejarlo en el código de producción sin querer puede ocultar lógica faltante o errores.</li>
</ul>
<h2>Comparación rápida</h2>
<ul>
<li><code>break</code>: Salir del ciclo por completo.</li>
<li><code>continue</code>: Saltar a la siguiente iteración.</li>
<li><code>pass</code>: no hacer nada, solo marcador de posición.</li>
</ul>
Bucles anidados
Los bucles anidados son bucles dentro de bucles. El bucle exterior se ejecuta una vez por cada iteración del bucle interior, multiplicando el total de iteraciones. Son esenciales para trabajar con datos multidimensionales, combinatoria y problemas algorítmicos.
Producto cartesiano
pythoncolors = ["red", "blue"]
sizes = ["S", "M", "L"]
for color in colors:
for size in sizes:
print(color, size)
Anidado mientras
pythoni = 1
while i <= 3:
j = 1
while j <= 2:
print(i, j)
j += 1
i += 1
Errores
Explosión de complejidad: Dos bucles anidados sobre n elementos dan como resultado O(n²) complejidad. Agregar más niveles aumenta drásticamente el tiempo de ejecución.
Sombreado de variables: La reutilización accidental de nombres de variables en bucles internos y externos puede anular valores inesperadamente.
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.
Funciones y expresiones Lambda
Las funciones en Python se definen utilizando la palabra clave def y le permiten encapsular código para su reutilización. Además, las expresiones lambda proporcionan una abreviatura para crear pequeñas funciones anónimas.
1. Definición de funciones
Utilice def para definir una función, opcionalmente con parámetros:
pythondef greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
# Outputs: Hello, Alice!
2. Funciones Lambda
Las expresiones Lambda crean pequeñas funciones anónimas. Son útiles para funciones breves y simples:
python# A lambda that adds two numbers
add = lambda a, b: a + b
print(add(3, 4)) # Outputs: 7
Tanto las funciones regulares como las expresiones lambda son herramientas esenciales para organizar y simplificar su código.
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étodos básicos de archivo
La función incorporada open() devuelve un objeto de archivo que puede usar para leer o escribir archivos en el disco.
El modo determina las acciones permitidas: 'r' (leer, predeterminado), 'w' (escribir, sobrescribir), 'a' (añadir).
Al abrir un archivo no se leen ni se escriben datos por sí solo; debe llamar a los métodos de archivo que se muestran a continuación. Cierre siempre los archivos cuando haya terminado (o, preferiblemente, utilice un administrador de contexto).
Modos: ejemplos rápidos
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() - leer el contenido completo
read() devuelve el resto del archivo como una sola cadena. Si se vuelve a llamar cuando ya está al final, devuelve una cadena vacía.
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() - lee la siguiente línea
readline() devuelve la siguiente línea (incluida la nueva línea final si está presente).
Al llamarlo repetidamente se avanza a través del archivo. Un argumento size (por ejemplo, readline(50)) limita el número de caracteres devueltos; not selecciona la “enésima línea”.
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(): obtiene todas las líneas como una lista</span></h2>
<p><span style="font-family: Roboto;">
<code>readlines()</code> devuelve una lista donde cada elemento está a una línea del archivo (incluidos los caracteres de nueva línea). Úselo con cuidado en archivos muy grandes.
</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() — escribe cadenas en un archivo
write() requiere una cadena. Convierta otros tipos con str(). El comportamiento (sobrescribir o agregar) depende del modo utilizado al abrir el archivo.
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() y mejores prácticas
close() libera el identificador del archivo y garantiza que los datos almacenados en el búfer se vacíen al disco. Olvidarse de cerrar puede bloquear otros programas o perder datos. El patrón recomendado es el administrador de contexto que se cierra automáticamente.
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
Pequeños ejemplos prácticos
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;">Errores comunes y soluciones rápidas</span></h2>
<ul>
<li><span style="font-family: Roboto;"><strong>FileNotFoundError</strong>: verifique la ruta o use una ruta absoluta.</span></li>
<li><span style="font-family: Roboto;"><strong>PermissionError</strong>: asegúrese de tener permisos de escritura/lectura para la carpeta de destino.</span></li>
<li><span style="font-family: Roboto;"><strong>UnicodeDecodeError</strong>: especifique la <code>codificación</code> correcta (por ejemplo, <code>"utf-8"</code>, <code>"latin-1"</code>) o abrir en modo binario <code>"rb"</code> para bytes sin formato.</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.
Importación de módulos en Python
Python le permite ampliar la funcionalidad importando modules (archivos que contienen código, funciones y clases de Python). Los módulos pueden integrarse, personalizarse o instalarse desde fuentes externas (como PyPI).
1. Sintaxis de importación básica
Utilice la instrucción import para incorporar un módulo a su programa.
pythonimport math
print(math.sqrt(16)) # Outputs: 4.0
2. Importación de funciones o alias específicos
Puede importar funciones específicas o cambiar el nombre de los módulos para su comodidad.
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. Módulos integrados de uso común</span></h2>
<p><span style="font-family: Roboto;">Algunos de los módulos integrados más útiles incluyen:</span></p>
<ul>
<li><span style="font-family: Roboto;"><code>math</code> → Funciones matemáticas (sqrt, pi, sin, cos...)</span></li>
<li><span style="font-family: Roboto;"><code>random</code> → Números aleatorios, barajado, opciones</span></li>
<li><span style="font-family: Roboto;"><code>datetime</code> → Fechas y horas</span></li>
<li><span style="font-family: Roboto;"><code>os</code> → Interacciones del sistema operativo (archivos, directorios)</span></li>
<li><span style="font-family: Roboto;"><code>sys</code> → Parámetros y funciones específicos del sistema</span></li>
<li><span style="font-family: Roboto;"><code>json</code> → Trabajar con datos JSON</span></li>
</ul>
<h2><span style="font-family: Roboto;">4. Instalación de módulos externos</span></h2>
<p><span style="font-family: Roboto;">
Muchos módulos populares no están integrados y deben instalarse a través de <code>pip</code> (administrador de paquetes 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. Resolución de errores de importación</span></h2>
<p><span style="font-family: Roboto;">
Problemas comunes al importar módulos:
</span></p>
<ul>
<li><span style="font-family: Roboto;"><strong>ModuleNotFoundError</strong>: El módulo no está instalado.
➝ Solución: ejecute <code>pip install modulename</code>.</span></li>
<li><span style="font-family: Roboto;"><strong>ImportError</strong>: No se puede importar una función/clase específica.
➝ Solución: consulte la documentación del módulo para conocer los nombres de funciones correctos.</span></li>
<li><span style="font-family: Roboto;"><strong>Conflictos de versión</strong>: Es posible que una versión del módulo no sea compatible con su versión de Python.
➝ Solución: actualice con <code>pip install --upgrade modulename</code>.</span></li>
<li><span style="font-family: Roboto;"><strong>Problemas del entorno virtual</strong>: El módulo está instalado en un entorno diferente.
➝ Solución: active el entorno correcto antes de ejecutar el script.</span></li>
</ul>
<h2><span style="font-family: Roboto;">6. Comprobación de módulos instalados</span></h2>
```bash
pip list # Shows installed modules
pip show numpy # Details about a specific module
Saber cómo importar y administrar módulos le permite extender la funcionalidad de Python mucho más allá de sus características 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 — Instalar e importar
NumPy es el paquete principal para la computación numérica en Python (matrices, matemáticas rápidas, álgebra lineal).
Instálelo con pip o su administrador de paquetes, luego impórtelo (convencionalmente como np).
Instalar
shell# with pip
pip install numpy
# or with conda
conda install numpy
Importar
pythonimport numpy as np
# now use np.array, np.linspace, np.zeros, ...
Errores comunes
- Asegúrese de instalar en el mismo entorno Python que ejecuta (problemas de entorno virtualenv/conda).
- La importación como cualquier otra cosa que no sea
npestá permitida pero es poco común; otras personas esperannp.
NumPy Arrays: crear, indexar, dividir
Las matricesNumPy son como listas pero con tipos numéricos fijos y operaciones vectorizadas rápidas. Puede convertir listas, crear matrices anidadas (2D) e indexarlas o dividirlas.
Crear a partir de listas
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)
Indexación (1D y 2D)
pythonprint(a[0]) # first element -> 1
print(b[1, 2]) # second row, third column -> 6
print(b[0][1]) # alternative syntax -> 2
Rebanado
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)
Errores comunes
- Las matrices NumPy requieren un tipo d uniforme: los objetos Python mixtos conducen a
dtype=object. - Los sectores son **vistas**, no copias; modificar un sector puede cambiar la matriz original.
Forma de matriz y la propiedad .shape
.shape devuelve una tupla con el tamaño de cada dimensión. Es una propiedad (sin paréntesis).
Ejemplos
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)
Errores comunes
- Llamar a
.shape()entre paréntesis es incorrecto: es una propiedad, no una función. reshaperequiere tamaños que se multipliquen al mismo número de elementos (o use-1para inferencia automática).
NumPy — Funciones básicas (linspace, ceros, aleatorio, ...)
NumPy ofrece prácticos constructores y ayudantes para matrices y secuencias de uso común.
Constructores comunes
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]
Números aleatorios
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)
Comportamiento del tipo de datos
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 una matriz tiene un tipo d entero, las operaciones in situ se convertirán a ese tipo d (posible truncamiento).
- Para permitir flotantes, cree la matriz con
dtype=floato transmita con.astype().
Matplotlib — Instalar e importar
Matplotlib es la biblioteca de trazado estándar para Python. Instálelo con su administrador de paquetes e importe el módulo pyplot (comúnmente como plt).
Instalar
shell# with pip
pip install matplotlib
# or with conda
conda install matplotlib
Importar
pythonimport matplotlib.pyplot as plt
# optionally import numpy for data
import numpy as np
Errores comunes
- Instale en el entorno activo (virtualenv/conda) utilizado por su script o cuaderno.
- En algunos entornos (por ejemplo, servidores sin cabeza) es posible que necesite un backend no interactivo para guardar cifras.
Matplotlib — Uso básico (plt.plot, plt.show, save)
Flujo de trabajo de trazado simple: cree datos, llame a funciones de trazado y luego muestre o guarde la figura.
Gráfico de líneas 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)
Varias series y guardado
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()
Errores comunes
- Llame a
plt.show()después de configurar el gráfico; de lo contrario, es posible que algunos servidores no muestren el estilo completo. - Al trazar varias figuras, utilice
plt.figure()ofig, ax = plt.subplots()para mantenerlas separadas.
Matplotlib — Modificadores y estilos (título, leyenda, ejes, aspecto)
Utilice etiquetas, límites, leyendas y métodos de ejes para ajustar la apariencia y el diseño de los gráficos.
Etiquetas, título, leyenda
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()
Límites y aspecto del eje
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()
Ocultar ejes o ticks
pythonax = plt.gca()
ax.xaxis.set_visible(False) # hide x-axis
ax.yaxis.set_visible(False) # hide y-axis
Errores comunes
- Cambiar las propiedades del eje requiere un objeto
Axes(deplt.gca()o el retorno deplt.subplots()). - Muchas opciones de estilo son persistentes en la figura/ejes actuales: llámalas en el orden correcto o crea una nueva figura para gráficos separados.
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.Conceptos avanzados de Python
Más allá de lo básico, Python ofrece muchas funciones avanzadas para escribir código conciso, eficiente y sólido. Temas como comprensión de listas, generadores y manejo de excepciones pueden ayudarlo a llevar sus habilidades de programación al siguiente nivel.
1. Lista de comprensiones
Las listas por comprensión proporcionan una forma concisa de crear listas. Pueden reemplazar bucles en muchos casos:
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. Manejo de excepciones
Utilice bloques try-except para manejar correctamente errores y excepciones:
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. Generadores
Los generadores le permiten iterar sobre grandes conjuntos de datos de manera eficiente sin almacenar la secuencia completa en la memoria:
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
Explorar estos temas avanzados puede mejorar significativamente sus capacidades de programación en Python.