装饰器的类型注释

2024-04-19 04:43:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这不是一个大问题,但我只是想知道如何解决这个问题。 因为我不熟悉在Python上使用函数注释,所以我不熟悉它。下面我有一个问题

当你制作一个装饰器并想在其上添加注释时,你是如何做到的

例如,下面这样的代码

def decorator(func: Callable[[*args,**kwargs], <what type should be here?>]) -> <??>:
    def new_func(*args, **kwargs):
        return func(*args, **kwargs)
    return new_func

Tags: 函数代码newreturndeftypeargs装饰
1条回答
网友
1楼 · 发布于 2024-04-19 04:43:54

使用Any作为返回类型,并返回另一个Callable返回类型Any。从PEP 484python standard libraryCallable的第一个参数必须是可调用参数的类型,而不是参数本身。因此,在Callable中使用*args**kwargs是不可接受的。相反,您必须使用省略号...(它允许任何数量的位置和关键字参数类型)

Decorator函数使用泛型类型(typing.TypeVar)更清晰地表示。用外行的话说,泛型是允许类型作为参数的东西

mypy docsFYImypypython的静态类型检查程序包)中进行解释:

Decorator functions can be expressed using generic types. Generics can be restricted to using values that are subtypes of specific types with the keyword argument bound=.... An upper bound can be used to preserve the signature of the wrapper function a decorator decorates.

因此,您的示例如下:

from typing import Any, Callable, TypeVar, cast

F = TypeVar('F', bound=Callable[..., Any])

def decorator(func: F) -> F:
    def new_func(*args, **kwargs):
        return func(*args, **kwargs)
    return cast(F, new_func)

也从mypy docsPEP 484转述:

The bound on F is used so that calling the decorator on a non-function will be rejected. Also, the wrapper function (new_func) is not type-checked because there is (currently) no support for specifying callback signatures with a variable number of arguments of a specific type, so we must cast the type at the end.

相关问题 更多 >