How to create a list of functions for call in python

Question:

If I had approximately 10 commands, and they all served specific purposes, so they couldn’t be modified, but I wanted to put them in a list without calling them.

def print_hello():
    print("hello")

command_list = [print_hello()]

This would only print "hello", then leave command_list equal to [None]

How would I get it so that when I type command_list[0], it would perform print_hello()?

My question is like this one here, but I don’t understand. How to add a function call to a list?

Answers:

If you want to add them to the list without calling them, just refrain from calling them:

command_list = [print_hello]

At the time you want to call them, call them:

command_list[0]()

If you want something to happen by just doing command_list[0], you could subclass list and give it a

def __getitem__(self, index):
    item = list.__getitem__(self, index)
    return item()

(untested). Then the item getting operation on the list causes the function to be called.

Answered By: glglgl
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.