Search code examples
pythondictionaryinstance

How can I create only one instance of a class depending on an index in Python?


I have a function that lets you create an instance of an automata by a given index. The user chooses an option from a menu and the index of the row chosen determines the automata to use.

def create_automata(idx, board):
    n_automatas = {
        0: GameOfLife(board),
        1: LangtonAnt(board, (board.height // 2) - 4, board.width // 2),
        2: BrianBrain(board),
        3: DayNight(board)
    }

    return n_automatas[idx]

The problem is that the dictionary already creates an instance of every class. I do not want this as the board given at a given situation will not work, for example, in GameOfLife, but it will in BrianBrain. In top of that, if I were to add even more automatas, the dict will create instances that I will not use.

How can I return an automata without creating more instances than I need (without the use of if/elif statements)?


Solution

  • One easy way is to store callables in your dictionary rather than instantiated objects:

    def create_automata(idx, board):
        n_automatas = {
            0: GameOfLife,
            1: lambda board: LangtonAnt(board, (board.height // 2) - 4, board.width // 2),
            2: BrianBrain,
            3: DayNight,
        }
    
        return n_automatas[idx](board)
    

    Note that this code becomes a lot cleaner if you can change your LangtonAnt constructor to just take the board and derive the other parameters on its own (if all the constructors have the same signature there's no need to specially wrap that one in a lambda).