ID EN
Typing

Concatenate

Python 3.11

Special form for annotating higher-order functions.

Syntax

PYTHON
typing.Concatenate

Examples

Example 1
PYTHON
from collections.abc import Callable
from threading import Lock
from typing import Concatenate, ParamSpec, TypeVar

P = ParamSpec('P')
R = TypeVar('R')

 Use this lock to ensure that only one thread is executing a function
 at any time.
my_lock = Lock()

def with_lock(f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
    '''A type-safe decorator which provides a lock.'''
    def inner(*args: P.args, **kwargs: P.kwargs) -> R:
         Provide the lock as the first argument.
        return f(my_lock, *args, **kwargs)
    return inner

@with_lock
def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
    '''Add a list of numbers together in a thread-safe manner.'''
    with lock:
        return sum(numbers)

 We don't need to pass in the lock ourselves thanks to the decorator.
sum_threadsafe([1.1, 2.2, 3.3])

See Also

Callable ParamSpec Callable ParamSpec threading.Lock ParamSpec ParamSpec Annotating callable objects