I come from a background in static languages. Can someone explain (ideally through example) the real world advantages of using **kwargs over named arguments
There are two common cases:
First: You are wrapping another function which takes a number of keyword argument, but you are just going to pass them along:
def my_wrapper(a, b, **kwargs):
do_something_first(a, b)
the_real_function(**kwargs)
Second: You are willing to accept any keyword argument, for example, to set attributes on an object:
class OpenEndedObject:
def __init__(self, **kwargs):
for k, v in kwargs.items():
setattr(self, k, v)
foo = OpenEndedObject(a=1, foo='bar')
assert foo.a == 1
assert foo.foo == 'bar'