Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / Python

typing.ParamSpec

Captura los parámetros para que un decorador conserve ante el comprobador las reglas posicionales y por nombre.

Versión: Python 3.14; repository image, production runtime not attested

Sintaxis

P = ParamSpec("P")

Captura los parámetros para que un decorador conserve ante el comprobador las reglas posicionales y por nombre.

La pareja P.args y P.kwargs anota los argumentos del envoltorio.

Este debe reenviarlos realmente y pasar por posición un argumento solo por nombre provoca TypeError.

Ejemplos

from collections.abc import Callable
from typing import ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")

def relay(f: Callable[P, R]) -> Callable[P, R]:
    def wrapped(*args: P.args, **kwargs: P.kwargs) -> R:
        return f(*args, **kwargs)
    return wrapped

@relay
def price(n: int, *, rate: int) -> int:
    return n * rate

print(price(3, rate=4))
try:
    price(3, 4)
except TypeError:
    print("keyword only")

Resultado

12
keyword only

Este debe reenviarlos realmente y pasar por posición un argumento solo por nombre provoca TypeError.

Fuentes