【问题标题】:How to call a function with positional-only parameters given an arguments dictionary?如何在给定参数字典的情况下调用仅位置参数的函数?
【发布时间】:2020-10-06 22:13:10
【问题描述】:

之前我使用Signature.bind(argument_dict) 将参数字典转换为BoundArguments 对象,该对象具有可以传递给函数的.args.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 的原生方式吗?

【问题讨论】:

    标签: python signature pep570


    【解决方案1】:

    我只能找到这样的东西,只使用字典中的位置参数:

    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)
    

    【讨论】:

      猜你喜欢
      • 2020-09-10
      • 1970-01-01
      • 2018-07-13
      • 2021-08-23
      • 1970-01-01
      • 1970-01-01
      • 2012-11-30
      • 2020-03-29
      • 1970-01-01
      相关资源
      最近更新 更多