PythonTipado Estático y DataclassesLección 11 de 24
Type Hints y Anotaciones
Python 3.5+ introdujo anotaciones de tipo opcionales. Puedes indicar que una función recibe un str y devuelve un int: def longitud(texto: str) -> int:. Python no las verifica en ejecución por defecto, pero herramientas como mypy, pyright o el propio VS Code las usan para detectar errores antes de correr el código.
Las type hints mejoran enormemente la legibilidad en proyectos grandes y en equipos. El módulo typing provee tipos especiales como List, Dict, Optional, Union, Callable y Tuple. En Python 3.10+ puedes usar la sintaxis nativa: str | None en lugar de Optional[str]. En código profesional, las type hints son cada vez más estándar.
from typing import Optional, Union, List, Dict, Tuple, Callable, Any
from typing import TypeVar, Generic
# Anotaciones básicas
def saludar(nombre: str, veces: int = 1) -> str:
return (f"Hola, {nombre}!\n") * veces
# Optional: puede ser el tipo o None
def buscar_usuario(id: int) -> Optional[dict]:
usuarios = {1: {"nombre": "Ana"}}
return usuarios.get(id) # Puede ser dict o None
# Union: puede ser varios tipos
def procesar(valor: Union[int, float, str]) -> str:
return str(valor)
# Con Python 3.10+ puedes usar | en lugar de Union
def procesar_moderno(valor: int | float | str) -> str:
return str(valor)
# List, Dict con tipos internos
def filtrar_mayores(numeros: List[int], minimo: int) -> List[int]:
return [n for n in numeros if n >= minimo]
def crear_indice(palabras: List[str]) -> Dict[str, int]:
return {p: len(p) for p in palabras}
# Callable: tipo para funciones
def aplicar(func: Callable[[int], int], valor: int) -> int:
return func(valor)
aplicar(lambda x: x**2, 5) # 25
# TypeVar para generics
T = TypeVar("T")
def primero(lista: List[T]) -> Optional[T]:
return lista[0] if lista else None
print(primero([1, 2, 3])) # 1 (tipo int)
print(primero(["a", "b"])) # "a" (tipo str)
# Python 3.12: nueva sintaxis type
type Vector = list[float]
type Matrix = list[Vector]
Consejo🔍 Instala mypy con pip install mypy y ejecuta mypy archivo.py para detectar errores de tipo antes de ejecutar el programa.
Practica esta lección
Resuelve los ejercicios del curso de Python en la app, gratis y con corrección automática.
Empezar a practicar