Canonicalise args and kwargs to argument-canonical form

岁酱吖の 提交于 2019-12-24 10:55:46

问题


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}

回答1:


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


来源:https://stackoverflow.com/questions/55899614/canonicalise-args-and-kwargs-to-argument-canonical-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!