I come from a background in static languages. Can someone explain (ideally through example) the real world advantages of using **kwargs over named arguments
**kwargs
are good if you don't know in advance the name of the parameters. For example the dict
constructor uses them to initialize the keys of the new dictionary.
dict(**kwargs) -> new dictionary initialized with the name=value pairs in the keyword argument list. For example: dict(one=1, two=2)
In [3]: dict(one=1, two=2)
Out[3]: {'one': 1, 'two': 2}
Another reason you might want to use **kwargs
(and *args
) is if you're extending an existing method in a subclass. You want to pass all the existing arguments onto the superclass's method, but want to ensure that your class keeps working even if the signature changes in a future version:
class MySubclass(Superclass):
def __init__(self, *args, **kwargs):
self.myvalue = kwargs.pop('myvalue', None)
super(MySubclass, self).__init__(*args, **kwargs)