For context, I am trying to solve questions from a website, and for each question I am usually implementing 2-3 solutions via a function for each solution. I time each function using a timing wrapper, and I call each questions' solution python file from a global main.py. Now, what I am currently doing in the main.py is
from problem1 import func1, func2, func3
l = [func1, func2, func3]
for x in l:
x(argument)
Now this works well given that I will always have 3 functions. But I want to be able to account for a variable number of functions without having to change the main everytime. I thought of just doing
from problem1 import * as func_list
for x in func_list:
x(argument)
But this doesn't work as you can't import everything from a file/module under 1 variable. Is there a solution for this problem or is my approach for the initial time testing situation itself completely wrong?
CodePudding user response:
You can define __all__
in your file
problem1.py
def func1(argument):
pass
def func2(argument):
pass
def func3(argument):
pass
__all__ = [func1, func2, func3]
main.py
import problem1
l = problem1.__all__
for x in l:
x(argument)
CodePudding user response:
You can try to use dir()
function to get everything from inside a module you imported:
import problem1
d = dir(problem1)
for i in d:
function = getattr(problem1, i)
if callable(function):
result = function("parameter")