之前我曾使用 Signature.bind(argument_dict)
将参数字典转换为具有 .args
和 的
可以传递给函数。BoundArguments
对象.kwargs
def foo(a: str, b: str, c: str): ...
argument_dict= {"a": "A", "c": "C", "b": "B"}
import inspect
sig = inspect.signature(foo)
bound_arguments = sig.bind(**argument_dict)
foo(*bound_arguments.args, **bound_arguments.kwargs)
但是当函数具有仅限位置参数时,这似乎不可能。
def foo(a: str, /, b: str, *, c: str): ...
import inspect
sig = inspect.signature(foo)
argument_dict= {"a": "A", "b": "B", "c": "C"}
bound_arguments = sig.bind(**argument_dict) # Error: "a" is positional-only
在这种情况下如何以编程方式调用该函数?
这是从参数字典构造 BoundArguments
的 native 方法吗?
最佳答案
我只能找到这样的东西,使用字典中的仅位置参数:
pos_only = [k for k, v in sig.parameters.items() if v.kind is inspect.Parameter.POSITIONAL_ONLY]
positionals = [argument_dict.pop(k) for k in pos_only]
bound_arguments = sig.bind(*positionals, **argument_dict)
关于python - 如何在给定参数字典的情况下调用仅位置参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64234526/