tic*_*ter 8 python python-typing
假设我有一个完全类型提示的方法,仅包含关键字参数:
class A:
def func(a: int, b: str, c: SomeIntricateTypeHint) -> OutputClass:
...
Run Code Online (Sandbox Code Playgroud)
现在假设我有一个函数,它接受可变关键字参数,并将它们完全传递给该方法:
def outer_func(n_repeat: int, **kwargs: ???) -> OtherOutputClass:
a = A()
for _ in range(n_repeat):
a.func(**kwargs)
Run Code Online (Sandbox Code Playgroud)
这样做,我失去了 类型提示的好处func。我如何输入提示kwargs才能outer_func恢复这些好处?
对于额外的细节,就我而言,我个人不定义func. 它实际上是来自客户端对象的方法boto3。因此,我正在寻找一种动态创建类型提示的解决方案,而不必手动创建 TypedDict。
就我而言,它是json.loads包装器。
我get_json接受字节并进行解码,但 json.loads 将接受str | bytes | bytearray作为第一个参数。
from typing import (
ParamSpec,
Callable,
Generic,
Concatenate,
Any,
)
P = ParamSpec("P")
def __get_json_func_creator(
_: Callable[
Concatenate[Any, P],
Any
] = json.loads
):
def func(data: bytes, *args: P.args, **kwargs: P.kwargs):
return json.loads(__get_text(data), *args, **kwargs)
return func;
get_json = __get_json_func_creator()
Run Code Online (Sandbox Code Playgroud)
就您而言,您func在 class 中定义A。假设您self在方法声明中缺少参数并且打算删除a和b参数?
class A:
def func(
self,
a: int,
b: str,
c: SomeIntricateTypeHint = None
) -> OutputClass: ...
def __wrap_class_a_func(
_: Callable[
Concatenate[A, Any, Any, P],
Any
] = A.func
):
def func(n_repeat: int, *args: P.args, **kwargs: P.kwargs):
a = A()
for num in range(n_repeat):
a.func(num, str(num), **kwargs)
return func
outer_func = __wrap_class_a_func()
Run Code Online (Sandbox Code Playgroud)
不幸的是,在这种情况下,如果您想删除所有位置参数,则必须在中定义所有位置类型Concatenate
| 归档时间: |
|
| 查看次数: |
1785 次 |
| 最近记录: |