Suppose I have the following 2 arbitrary classes:
class C1():
def __init__(self, a):
self.a = a
class C2():
def __init__(self, a):
self.a = a
And the following parameters:
c1_args = [1, 2, 3, 4, 5]
c2_args = [1, 2, 3]
I want to run a function (let's call it do_something()
) n times, taking as arguments every possible pair of instances of (C1,C2) based on the parameters provided. To do this, I created a nested loop, as shown below:
for x in c1_args:
c1_instance = C1(x)
for y in c2_args:
c2_instance = C2(y)
do_something(c1_instance, c2_instance)
Now, I want to be able to generalize it for any number of classes (and parameters). For that, a simple - yet highly inefficient - way to do it would be to use itertools.product()
, which I adapted from here:
import itertools
def generalize(classes, args):
combos = itertools.product(*args)
for combo in combos:
instances = [classes[i](args[i]) for i in range(len(combo))]
do_something(instances)
This is highly inefficient because it must create the same instance multiple times - in my example above, C1(1) must be created 3 times, once for every C2 instance created. That's irrelevant with the simple classes I provided above but with bigger classes it is heavily time consuming.
I suspect one solution would be recursion, based on what I found here. Unfortunately I can't seem to make it work for my case (mostly due to my ignorance on recursion - apologies for that)