當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Python typing.Concatenate用法及代碼示例


用法:

typing.Concatenate

CallableParamSpec 一起使用以鍵入注釋更高階的可調用對象,該可調用對象添加、刪除或轉換另一個可調用對象的參數。用法格式為 Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]Concatenate 當前僅在用作 Callable 的第一個參數時才有效。 Concatenate 的最後一個參數必須是 ParamSpec

例如,要注釋裝飾器with_lock,它為裝飾函數提供threading.LockConcatenate 可用於指示with_lock 需要一個將Lock 作為第一個參數的可調用對象,並返回具有不同類型簽名的可調用對象。在這種情況下,ParamSpec 表示返回的可調用對象的參數類型取決於傳入的可調用對象的參數類型:

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.'''
    global my_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])

相關用法


注:本文由純淨天空篩選整理自python.org大神的英文原創作品 typing.Concatenate。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。