Support decorators that modify parameter types and preserve keywords
还没有人认领这个 Issue。
- 主要语言
- Python
- 星标
- 1.8k
- 派生
- 302
- 平均合并
- 23 小时
- 30 天内合并 PR
- 8
描述
For osandov/drgn#364, I'd like to be able to define a decorator that modifies the parameter types of the functions it wraps, but also preserves keywords.
For a toy example, imagine a decorator that wraps a function taking an int as the first parameter (possibly as a keyword argument) so that it can also take a str that is automatically converted to an int. I can do this manually with overloads:
import inspect
import functools
from typing import Any, Callable, TypeVar, overload
R = TypeVar("R")
def takes_int_or_str(f: Callable[..., R]) -> Callable[..., R]:
param = next(iter(inspect.signature(f).parameters))
@functools.wraps(f)
def wrapper(*args: Any, **kwds: Any) -> R:
if param in kwds:
if isinstance(kwds[param], str):
kwds[param] = int(kwds[param])
elif isinstance(args[0], str):
return f(int(args[0]), *args[1:], **kwds)
return f(*args, **kwds)
return wrapper
@overload
def f(x: int) -> int: ...
@overload
def f(x: str) -> int: ...
@takes_int_or_str
def f(x: int) -> int:
return x * x
f(1)
f("2")
f(x="3")
But this is tedious and error-prone if you have a lot of functions using the decorator. ParamSpec almost gets me what I want, but it doesn't preserve keywords:
import inspect
import functools
from typing import Any, Callable, Concatenate, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def takes_int_or_str(
f: Callable[Concatenate[int, P], R]
) -> Callable[Concatenate[int | str, P], R]:
param = next(iter(inspect.signature(f).parameters))
@functools.wraps(f)
def wrapper(*args: Any, **kwds: Any) -> R:
if param in kwds:
if isinstance(kwds[param], str):
kwds[param] = int(kwds[param])
elif isinstance(args[0], str):
return f(int(args[0]), *args[1:], **kwds)
return f(*args, **kwds)
return wrapper
@takes_int_or_str
def f(x: int) -> int:
return x * x
f(1)
f("2")
# error: Unexpected keyword argument "x" for "f" [call-arg]
f(x="3")
This seems somewhat related to #1273, although I want to specify the transformation by parameter, not by input type.
P.S. I used Callable here, but my real use cases need a Protocol with __call__ because they have more complicated signatures.
贡献指南
这个仓库没有索引到贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
调研方向
从这个 issue 中的装饰器示例开始,并将所请求的行为与相关 issue #1273 进行比较。考虑基于参数的转换应如何与 ParamSpec、关键字参数、Callable 和 Protocol 签名交互;当行为被充分明确地规范化,足以支持所述的位置调用和关键字调用时,即可视为完成。
由索引模型根据 Issue 内容生成。
评估
- 技术栈
- python
- 领域
- developer-experience
- Issue 类型
- 功能
- 难度
- 5/5
- 预计耗时
- 一周以上
- 活跃度
- 停滞
- 描述清晰度
- 基本清楚
- 新手友好度
- 30/100