I want to make following function:
1)input is a number.
2)functions are indexed, return a function whose index matches given number
here’s what I came up with:
def foo_selector(whatfoo):
def foo1():
return
def foo2():
return
def foo3():
return
...
def foo999():
return
#something like return foo[whatfoo]
the problem is, how can I index the functions (foo#)?
I can see functions foo1 to foo999 by dir(). however, dir() returns name of such functions, not the functions themselves. In the example, those foo-functions aren’t doing anything. However in my program they perform different tasks and I can’t automatically generate them. I write them myself, and have to return them by their name.
Use a decorator to accumulate a list of functions.
Now you can easily access the functions by index in a list.
You could also create a dictionary if you want to access the functions by name:
Or extract the index from the name, and use that as the dict key (since dicts are not ordered, you’ll want to sort the keys if you want to iterate over them in some order):
Or explicitly pass the index number to the decorator: