OiO.lk Blog python How to iterate through categorical combinatorics of different Enum classes in Python?
python

How to iterate through categorical combinatorics of different Enum classes in Python?


I have a function – main() that takes in an instance of a class InputPermutation as it’s only argument. The idea being that differences in the results from a run of the main() are based solely on the differences in the InputPermutation class. I need to iterate through all possible configurations of the InputPermutation class and record the results from main() for each of the runs.

InputPermutation has attributes which are instances of different Enum classes. I need to iterate through all possible Enum class instances for each of the InputPermutation attributes to get all possible configurations.

Here is a simplified model of the problem I am facing.

from enum import Enum

class Colour(Enum):
    GREEN = "green"
    BLUE = "blue"
    RED = "red"

class Country(Enum):
    ENGLAND = "england"
    JAPAN = "japan"
    AUSTRALIA = "australia"

class InputPermutation:
    def __init__(self, colour: Colour, country: Country):
        self.colour = colour
        self.country = country

def main(input_permutation: InputPermutation) -> dict:
    
    colour = input_permutation.colour.value
    country = input_permutation.country.value

    result = {colour: country}

    return result

def iterate() -> dict:

    pass

I need help making this iterate() function, cannot figure out how to make this work…

I would like the function to return a single dictionary, where each key is a "run_index", just a number increasing by 1 for each run of main(). Each value would ideally be a dictionary of the structure below:

{
    1: {"green": "england"},
    2: {"green": "japan"},
    3: {"green": "australia"},
    4: {"blue": "england"},
    # etc...
}

I would like it to scale, so no matter how many different Enum classes, (or new options within the existing Enum classes) are added to the InputPermutation class, the function still will iterate through all the options. I have managed to get this output already without making it scalable in this way.

The issue could be specific to my use of the Enum classes. The reason I have opted for this is because of the drop-down it gives me when I am choosing options to select for. It also standardises the option inputs by locking you into typing them in a specific format before converting them to strings which reduces the likelihood of typing errors if that makes sense.

The problem does have a real world applicability for a model I am making, but I thought this country : colour thing would be easier to work with here…



You need to sign in to view this answers

Exit mobile version