In Python, * and ** allow you to capture arguments coming into a callable, even if you don't know their names ahead of time.
In [2]:
def foo(*args):
print repr(args)
foo(1, 2, 3, 4)
In [3]:
def bar(**kwargs):
print kwargs
bar(a=1, b=2, c=3)
This is particularly useful for inheritance, where you may want to override a method of the parent while maintaining the parent's method's functionality. You can do so without even knowing the parent class's signature - and if that signature changes, your descendant class will not break!
In [7]:
class Baz(object):
def my_method(self, a, b):
print 'a: %s; b: %s' % (a, b)
class Bazlet(Baz):
def my_method(self, x, *args, **kwargs):
print 'x: %s' % x
# Call the parent's corresponding method
super(Bazlet, self).my_method(*args, **kwargs)
baz = Bazlet()
baz.my_method(x=10, a=1, b=2)
Whenever you wrap a method to provide a particular interface, or create a subclass and extend a particular method, using this convention will make your code less fragile.