python - Concatenate required arguments and optional args in function? -
i want define function accepts , arbitrary number of dictionaries @ least 2 , want iterate on of them. i'm creating list of first 2 , append optional ones:
def func(dict1, dict2, *dicts): dicts = [dict1, dict2] + list(dicts) d in dicts: # stuff
but feel that's bit unnecessarily complicated. wondered if 1 alternative checking length of *dicts
might better because don't need create new iterable:
def func(*dicts): if len(dicts) < 2: raise valueerror('too few dictionaries, must give function @ least 2.') d in dicts: # stuff
but still don't feel that's convenient since need explain somewhere because function signature looks accept arbitrary number of dicts (even 0 or 1). there way have signature of first option without having create complete new iterable in function?
the first approach seems fine me, can simplify tiny bit using tuple instead of list first pair don't need list
call:
all_dicts = (dict1, dict2) + dicts
and if you're iterating, don't need make temporary variable:
for d in (dict1, dict2) + dicts:
Comments
Post a Comment