Packing and Unpacking with Python and Asterisks

The people that are new to python are often confused by the use of the asterisk. Mostly in functions arguments, but not only.

The * and ** are operators for so called packing and unpacking.

*args packs all the arguments into a single variable and allow a function to accept any number of arguments.

1
2
def my_func(*args):
    pass

*kwargs packs all the keywords arguments into a single variable and allow a function to accept any number of keyword arguments.

1
2
def my_func(**kwargs):
    pass

You can also put both of them at your functions definition.

1
2
def my_func(*args, **kwargs):
    pass

This is especially useful when you want to pass though arguments to another function, e.g. the constructor of a superclass:

1
2
3
class MyClass(MySuperClass):
    def __init__(*args, **kwargs):
        super(MyClass, self).__init__(self, *args, **kwargs)

You can also call functions with *my_list and **my_dict to unpack positional and keyword arguments.

1
2
3
4
5
6
def my_func(a, b, c, d)
    print a, b, c, d

my_list = [1, 2]
my_dict = dict(a=1, b=2)
my_func(*my_list, **my_dict)