December 7, 2016

function with *args in Python

Sometimes we have some functions with infinite argument, we can pass a list with all elements or pass a generator or *args to it.

def normalize_purchases_status(purchases):
    for purchase in purchases:
        purchase.status = 'xxx'


another version of normalize_purchases_status

def normalize_purchases_status(*purchases):
    for purchase in purchases:
        purchase.status = 'xxx'


the second version looks better than first one, caller must guarantee argument is not None, because there is no check in callee

if we pass a generator, it will failed because the callee don’t know the type of argument.

a list, tuple, dict, generator is a Iterable, if it is a iterable, we can iterate it.

Powered by Hugo & Kiss.