本文介绍了将 args 和 kwargs 规范化为参数规范形式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法,给定一个函数的签名,将它的 args 和 kwargs 规范化.也就是说,任何已经在函数签名中传入的 kwargs 都应该转换为 args.

例如:

def myfunc(a, b=0, c=0, **kwargs):经过def规范化(func, *args, **kwargs):东西 = 检查.签名(功能)# 在这里用 args/kwargs 做一些事情返回 new_args, new_kwargs

示例输出:

对象,例如:

bound_args.apply_defaults()args = bound_args.argskwargs = bound_args.kwargs

I'm looking for a way, given a function's signature, to canonicalize it's args and kwargs. That is, any kwargs passed in already in the signature of the function should be converted to args.

For example:

def myfunc(a, b=0, c=0, **kwargs):
    pass

def canonicalize(func, *args, **kwargs):
    something = inspect.signature(func)
    # Do something with args/kwargs here
    return new_args, new_kwargs

Example output:

>>> canonicalize(myfunc, 1, 2, g=3)
(1, 2), {'g': 3}
>>> canonicalize(myfunc, 1)
(1,), {}
>>> canonicalize(myfunc, 1, b=2)
(1, 2), {}
>>> canonicalize(myfunc, 1, g=3, b=2)
(1, 2), {'g': 3}
>>> canonicalize(myfunc, 1, g=3, c=2)
(1, 0, 2), {'g': 3}
解决方案

You can use inspect.signature and its bind(...) method, eg:

bound_args = inspect.signature(myfunc).bind(1, g=3, c=2)
# <BoundArguments (a=1, c=2, kwargs={'g': 3})>

Then access what you need from the BoundArguments object, eg:

bound_args.apply_defaults()
args = bound_args.args
kwargs = bound_args.kwargs

这篇关于将 args 和 kwargs 规范化为参数规范形式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-24 18:25