Skip to content

Instantly share code, notes, and snippets.

@carlosplanchon
Last active July 25, 2022 01:32
Show Gist options
  • Save carlosplanchon/e586fd9d6f0ed35cf2344bbf96c202c5 to your computer and use it in GitHub Desktop.
Save carlosplanchon/e586fd9d6f0ed35cf2344bbf96c202c5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
from inspect import _empty, signature
def get_multiparameter_callback(callback, **parameters):
callback_sig_p = signature(callback).parameters
# If some provider parameter does not belong to callback parameters.
unexpected_parameters = list(parameters.keys() - callback_sig_p.keys())
if len(unexpected_parameters) > 0:
raise TypeError(
f"{callback.__name__}() got the following unexpected keyword "
f"arguments: '{', '.join(unexpected_parameters)}'"
)
required_empty_parameters = list(
set(
[
callback_sig_p[i].name for i in callback_sig_p
if callback_sig_p[i].default == _empty
]
) - set(parameters)
)
if len(required_empty_parameters) > 0:
raise TypeError(
f"TypeError: {callback.__name__}() missing "
f"{len(required_empty_parameters)} required "
"positional argument(s): "
f"'{', '.join(required_empty_parameters)}'"
)
list_of_parameters = []
# For each parameter in the provided callback.
for p in callback_sig_p.keys():
if p in parameters.keys():
# If parameter is in provided parameters we append it to
# list of parameters.
list_of_parameters.append(parameters[p])
else:
# Else we try to get the default value of the function.
default_value = callback_sig_p[p].default
if default_value == _empty:
raise SyntaxError(
"non-default argument follows default argument"
)
list_of_parameters.append(default_value)
return lambda parameter: callback(*parameter), list_of_parameters
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment