Search code examples
pythonlistinheritanceindexingkeyword-argument

Is there an elegant way to simultaneously unpack and index key word arguments in python?


I have a method which takes some basic arguments (arg_1 & arg_2) as well as some lists of n elements, and then uses these arguments in a nested method call, once for each list element like so:

def method_one(self, a=arg_1, b=arg_2, list_1, list_2):
    
    for i in range(n):
        method_two(a=arg_1, b=arg_2, c=list_1[i], d=list_2[i])

method_two is unique to each class, but method_one exists in all of the child classes, each of which takes the same basic arguments (arg_1 & arg_2) and a varying number of list arguments (always length n).

Is there a way I can use kwargs to write a single method_one in the parent class which works for all children? Something like:

def method_one(self, a=arg_1, b=arg_2, **kwargs):
    
    for i in range(n):
        method_two(a=arg_1, b=arg_2, **kwargs[i])

in such a way that **kwargs[i] unpacks the key, and ith element of the associated value for all lists arguments in kwargs.


Solution

  • If I understand this correctly, you could pass a dictionary comprehension to the ** unpacking in method_two:

    def method_one(self, arg_1, arg_2, **kwargs):
        for i in range(n):
            method_two(
                arg_1, arg_2,
                **{name: value[i] for name, value in kwargs.items()}
            )