小编rog*_*ham的帖子

可以带或不带参数使用的类型装饰器

我有一个装饰器,可以在不带参数或带参数的情况下调用(所有字符串):

\n
@decorator\ndef fct0(a: int, b: int) -> int:\n    return a * b\n\n\n@decorator("foo", "bar")  # any number of arguments\ndef fct1(a: int, b: int) -> int:\n    return a * b\n
Run Code Online (Sandbox Code Playgroud)\n

尽管已阅读mypy 文档的相关部分,但我很难提供适当的类型提示,以便类型检查器能够正确验证装饰器的使用。

\n

这是我到目前为止所尝试过的:

\n
from typing import overload, TypeVar, Any, Callable\n\nF = TypeVar("F", bound=Callable[..., Any])\n\n@overload\ndef decorator(arg: F) -> F:\n    ...\n\n@overload\ndef decorator(*args: str) -> Callable[[F], F]:\n    ...\n\ndef decorator(*args: Any) -> Any:\n    # python code adapted from https://stackoverflow.com/q/653368\n\n    # @decorator -> shorthand for @decorator()\n    if len(args) == 1 and callable(args[0]):\n …
Run Code Online (Sandbox Code Playgroud)

python python-decorators mypy python-typing pyright

5
推荐指数
1
解决办法
749
查看次数

标签 统计

mypy ×1

pyright ×1

python ×1

python-decorators ×1

python-typing ×1