如何键入注释具有可选参数的装饰器?

问题描述 投票:3回答:1

这是我正在尝试正确键入注释的确切函数:

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

def throtle(_func: Optional[F] = None, *, rate: float = 1) -> Union[F, Callable[[F], F]]:
    """Throtles a function call, so that at minimum it can be called every `rate` seconds.

    Usage::

        # this will enforce the default minimum time of 1 second between function calls
        @throtle
        def ...

    or::

        # this will enforce a custom minimum time of 2.5 seconds between function calls
        @throtle(rate=2.5)
        def ...

    This will raise an error, because `rate=` needs to be specified::

        @throtle(5)
        def ...
    """

    def decorator(func: F) -> F:
        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            time.sleep(rate)
            return func(*args, **kwargs)

        return cast(F, wrapper)

    if _func is None:
        return decorator
    else:
        return decorator(_func)

虽然我在通过mypy时没有收到任何错误,但我不相信我做了正确的事情,也不确定我怎么能证明这一点。

python python-3.x mypy
1个回答
2
投票

你的代码类型检查,但可能它没有做你想要的,因为你正在返回一个Union

要检查mypy推断某些变量的类型,您可以使用reveal_type

# Note: I am assuming you meant "throttle" and so I changed your spelling
def throttle1(
    _func: Optional[F] = None, *, rate: float = 1.0
) -> Union[F, Callable[[F], F]]:
    # code omitted


@throttle1
def hello1() -> int:
    return 42


reveal_type(hello1) # Revealed type is 'Union[def () -> builtins.int, def (def () -> builtins.int) -> def () -> builtins.int]'

假设我们希望hello1是一个返回int的函数(即def () -> builtins.int),我们需要尝试别的东西。

简单的策略

最简单的事情是总是要求throttle的用户“调​​用装饰器”,即使他/他没有覆盖任何参数:

def throttle2(*, rate: float = 1.0) -> Callable[[F], F]:
    def decorator(func: F) -> F:
        @functools.wraps(func)
        def wrapper(*args: Any, **kwargs: Any) -> Any:
            time.sleep(rate)
            return func(*args, **kwargs)

        return cast(F, wrapper)

    return decorator


@throttle2() # Note that I am calling throttle2 without arguments
def hello2() -> int:
    return 42

reveal_type(hello2) # Revealed type is 'def () -> builtins.int'


@throttle2(rate=2.0)
def hello3() -> int:
    return 42

reveal_type(hello3) # Revealed type is 'def () -> builtins.int'

这已经有效并且非常简单。

使用typing.overload

如果以前的解决方案不可接受,您可以使用overload

# Matches when we are overriding some arguments
@overload
def throttle3(_func: None = None, *, rate: float = 1.0) -> Callable[[F], F]:
    ...

# Matches when we are not overriding any argument
@overload
def throttle3(_func: F) -> F:
    ...


def throttle3(
    _func: Optional[F] = None, *, rate: float = 1.0
) -> Union[F, Callable[[F], F]]:
    # your original code goes here


@throttle3 # Note: we do not need to call the decorator
def hello4() -> int:
    return 42


reveal_type(hello4) # Revealed type is 'def () -> builtins.int'


@throttle3(rate=2.0)
def hello5() -> int:
    return 42


reveal_type(hello5) # Revealed type is 'def () -> builtins.int'

您可以通过阅读overloadits official documentation了解有关如何使用mypy's documentation on Function overloading的更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.