I recently started learning Python. Let me explain what I'm trying to accomplish. I have this .py script, which basically has several functions (hard-coded in a script) that all need to be added to one list so that I can get the function I need, just using the index operator as it should:
needed_function = function_list [required_function_index]
My first attempt to implement this led to the following code structure:
(imports) function_list = [] (other global variables) def function_0 = (...) function_list.append(function_0) def function_1 = (...) function_list.append(function_1) def function_2 = (...) function_list.append(function_2) (rest of code)
But I do not like this solution, because it is not very elegant. My goal is to simply add a function definition to the script (without calling add), and the script will automatically add it to the list of functions.
I was thinking of defining all the functions within the framework of another function, but I do not think that I get anything with them. I thought it might be possible to "tag" each function as a decorator, but I realized that decorators (if I understand them correctly) are called every time the function is called, and not just once.
After a while, I came up with this solution:
(imports) (global variables) def function_0 = (...) def function_1 = (...) def function_2 = (...) function_list= [globals()[x] for x in globals() if re.match('^function_[0-9]+$', x)] (rest of code)
I like this a bit more as a solution, but my only embarrassment is that I would prefer for the sake of cleanliness to fully define the function_list at the top of the script. However, I cannot do this, since the call to globals () at the top of the script will not contain functions, since they are not defined yet.
Maybe I just need to settle for a less elegant solution, or maybe I'm not writing my script in an idiomatic way. In any case, any suggestions and suggestions are welcome.