Search code examples
pythonpython-2.7argskeyword-argument

function not recognizing args and kwargs


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?


Solution

  • If you meant that avg and tot should be passed in as keyword args, like in your example get_event_stats(..., avg=True, tot=False) then they are populated in kwargs. You can look them up in the kwargs dict using a key lookup (like kwargs['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 returns None if it is not present, which is boolean False. Or use kwargs.get('avg', False) if you explicitly want a False if it's not present.

    def get_event_stats(elengths, einds, *args, **kwargs):
    
        master_list = []
    
        if kwargs.get('avg'):
            for arg in args:
                 do stuff...
        if kwargs.get('tot'):
            for arg in args:
                 do stuff...
    
        return master_list