Issue
Best way to keep args and kwargs for a function/method.
I have a function that I need to call with multiple set of arguments, args and kwargs.
t.addelement("tas", "alpha", action="pro", set=False)
t.addelement("mas", "beta", action="sub", set=False)
t.addelement("mas", "beta", action="sub", set=True)
I want to keep the arguments outside, like in a list and do a loop:
for args in args_list:
t.addelement(args)
What is the best way, structure to store the arguments ?
Solution
If you know the signature of the function, you could use inspect.BoundArguments. Other than that, I'm not aware of any builtin Python structure for this.
You can do something simple, similar to what others suggested:
args = (["foo"], {"baz":"baz"}) # (args, kwargs) tuple
# ...and call something with it
test(*args[0], **args[1])
However, I've come across the need a couple times and find the following to be much cleaner:
class Arguments:
""" Container for args and kwargs """
__slots__ = ["args","kwargs"]
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
def __call__(self, fn, *args, **kwargs):
""" Call something with these arguments, returning the result;
you can pass additional arguments which will be injected after the arguments
passed to the constructor (mimicking functools.partial behavior)
"""
return fn(*self.args, *args, **self.kwargs, **kwargs)
Which can be used like this:
args = Arguments("foo", bar="bar")
# apply arguments to function
def test(*args, **kwargs):
print(args, kwargs)
args(test, "baz", sit="sit")
# prints: ('foo', 'baz') {'bar': 'bar', 'sit': 'sit'}
You can enhance this structure to do more advanced argument management: specify exact positional arguments, create partial/partialmethod wrappers, merge Arguments, load from JSON, etc. (I have done so in the past, and perhaps will consider publishing a pip package)
Answered By - Azmisov
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.