问题
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