IOKELU
Nivel: Avanzado – Guía 13
💡 Prueba el código:
Ejecuta cualquier ejemplo en nuestra consola interactiva: Abrir consola de Python →

Tipado estático avanzado con typing

El módulo typing permite añadir anotaciones de tipo para mejorar la calidad del código, detectar errores antes de tiempo y documentar mejor las funciones. En esta guía aprenderás a usar tipos avanzados como Union, Optional, TypedDict, Protocol, TypeVar, Generic y anotaciones modernas con | (PEP 604).

Tabla de contenidos

  • Anotaciones básicas
  • Union y Optional
  • TypedDict
  • Protocol
  • TypeVar y Generic
  • Callable
  • PEP 604: tipos con |
  • Ejercicios
  • Mini‑proyecto

1. Anotaciones básicas

def sumar(a: int, b: int) -> int:
    return a + b

2. Union y Optional

from typing import Union, Optional

def procesar(x: Union[int, str]):
    print(x)

def obtener() -> Optional[int]:
    return None

3. TypedDict

from typing import TypedDict

class Usuario(TypedDict):
    nombre: str
    edad: int

u: Usuario = {"nombre": "Ana", "edad": 30}

4. Protocol

Protocol permite definir interfaces sin herencia explícita.

from typing import Protocol

class Hablador(Protocol):
    def hablar(self) -> str: ...

class Persona:
    def hablar(self) -> str:
        return "Hola"

def saludar(obj: Hablador):
    print(obj.hablar())

saludar(Persona())

5. TypeVar y Generic

from typing import TypeVar, Generic

T = TypeVar("T")

class Caja(Generic[T]):
    def __init__(self, valor: T):
        self.valor = valor

c1 = Caja(10)
c2 = Caja("hola")

6. Callable

from typing import Callable

def ejecutar(func: Callable[[int], int]):
    print(func(10))

ejecutar(lambda x: x * 2)

7. PEP 604: tipos con |

def procesar(x: int | str):
    print(x)

def obtener() -> int | None:
    return None

8. Ejercicios

9. Mini‑proyecto: Sistema de validación tipado

from typing import Protocol, TypedDict

class Validador(Protocol):
    def validar(self, datos: dict) -> bool: ...

class Usuario(TypedDict):
    nombre: str
    edad: int

class ValidadorUsuario:
    def validar(self, datos: Usuario) -> bool:
        return datos["edad"] >= 18

v = ValidadorUsuario()
print(v.validar({"nombre": "Ana", "edad": 20}))

Siguiente guía

Data classes →