Fruitful Approach Fruitful Approach - 1 year ago 121
Python Question

When do I use **kwargs vs kwargs (*args vs args)?

I need to store both args & kwargs in a tuple for calling later, so in that case would the appropriate value in the tuple *args or args? In other words, will this work:

def __init__(self, *args, **kwargs):
self._buildCalls = [
(self.__init__, args, kwargs)
self._building = False

def __getattr__(self, attr):
if self.building():
if hasmethod(self, attr):
return lambda *args, **kwargs: self.argSaver(attr, *args, **kwargs)
return super().__getattr__(attr)

def argSaver(self, method, *args, **kwargs):
self._buildCalls.append((method, args, kwargs))
return method(*args, **kwargs)

Answer Source

Here's a sample function signature:

def foo(a, b, *args, **kwargs):

Here *args represents the arguments after a and b that aren't required, are passed like 'non-named' arguments (foo(1, 2, 3, 4, 5)) and the function gets them as a list called args: args == [3, 4, 5].

**kwargs represents the arguments that aren't required, are passed by name (foo(1, 2, foo=3, bar=4)) and the function gets them as a dictionary called kwargs: kwargs == {'foo': 3, 'bar': 4}.

When you use the star notation outside function definition, it tries to extract data from a list or a dictionary, e.g. *[1, 2, 3] gives you three separate values that have been extracted from the list, *{'foo': 5} will extract all the keys of the dictionary, but foo(**{'foo': 5, 'bar': 6}) will attempt to pass two arguments called foo and bar with values 5 and 6 respectively to the function foo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download