Re:Python 3.12
by dagmx on Monday October 02, 2023 @10:55AM
(#37738940)
I wonder if Unpack works on a function? I assume it’s any callable.
[ Parent
| on HN ]
Re:Python 3.12
by squeaky-clean on Monday October 02, 2023 @12:10PM
(#37740088)
The type that gets Unpack[]'d needs to inherit from TypeDict, unless I'm misunderstanding what you mean.
Basically I was hoping to use it for functions that wrap others.
E.g setup something and then pass the kwargs through to the other function.
Re:Python 3.12
by benkuykendall on Monday October 02, 2023 @09:25PM
(#37746763)
If I understand you correctly, I think ParamSpec (since 3.10) is what you are looking for, especially if you want to be generic over the type of the inner function. The example from the docs (https://docs.python.org/3/library/typing.html#typing.ParamSp...):
from collections.abc import Callable
from typing import TypeVar, ParamSpec
import logging
T = TypeVar('T')
P = ParamSpec('P')
def add_logging(f: Callable[P, T]) -> Callable[P, T]:
'''A type-safe decorator to add logging to a function.'''
def inner(*args: P.args, **kwargs: P.kwargs) -> T:
logging.info(f'{f.__name__} was called')
return f(*args, **kwargs)
return inner
@add_logging
def add_two(x: float, y: float) -> float:
'''Add two numbers together.'''
return x + y