Canonicalise Args And Kwargs To Kwarg-canonical Form
I've asked a similar question here for posarg-canonical form. Any possible args should be converted to keyword-form, with the defaults being omitted based on the result of the is o
Solution 1:
You can use the following function - you basically move arguments which have a default value into whatever was in **kwargs (if it's not actually assigned to its own default value):
import inspect
def canonicalize(f, *args, **kwargs):
sig = inspect.signature(f)
bargs = sig.bind(*args, **kwargs)
# Pop out the named kwargs variable defaulting to {}
ret_kwargs = bargs.arguments.pop(inspect.getfullargspec(f).varkw, {})
# For all possible signature values
for k, v in sig.parameters.items():
# If the name exists in the bound arguments and has a default value
if k in bargs.arguments and v.default is not inspect.Parameter.empty:
# Remove from the bound arguments dict
val = bargs.arguments.pop(k)
# If the value isn't the same as the default value add it to ret_kwargs
if val is not v.default:
ret_kwargs[k] = val
# bargs.args here will be made up of what's left in bargs.arguments
return bargs.args, ret_kwargs
Post a Comment for "Canonicalise Args And Kwargs To Kwarg-canonical Form"