I am trying to define a function like so:
def get_event_stats(elengths, einds, *args, **kwargs):
master_list = []
if avg:
for arg in args:
do stuff...
if tot:
for arg in args:
do stuff...
return master_list
I would like elengths and einds to be fixed positional args (these are just arrays of ints). I am trying to use the function by passing it a variable length list of arrays as *args and some **kwargs, in this example two (avg and tot), but potentially more, for example,
avg_event_time = get_event_stats(event_lengths, eventInds, *alist, avg=True, tot=False)
where
alist = [time, counts]
and my kwargs are avg and tot, which are given the value of True and False respectively. Regardless of how I've tried to implement this function, I get some kind of error. What am I missing here in the correct usage of *args and **kwargs?
If you meant that
avgandtotshould be passed in as keyword args, like in your exampleget_event_stats(..., avg=True, tot=False)then they are populated inkwargs. You can look them up in thekwargsdict using a key lookup (likekwargs['avg'].However if they are not present at all, then that will give a key error, so use it with the
dict.get()method:kwargs.get('avg')which returnsNoneif it is not present, which is booleanFalse. Or usekwargs.get('avg', False)if you explicitly want aFalseif it's not present.