from module import a, b, c foo(a) foo(b) foo(c)
Is there a way to avoid having to call foo(x)
for each imported object?
Some context: a, b, c are webpage classes and foo is a route() function that creates a route for each webpage.
Update: There will be a growing list of imported classes in the main module as the application grows. I mentioned a, b, and c simply as an example. I am looking for something like import a, b, c to classes_list
and then I can iterate over the classes_list
instead of calling foo on each of the imported classes.
Advertisement
Answer
Assuming you have no other imports, you could iterate over globals().items() to gather all the classes. You may need to filter further if there are additional classes in your overall imports.
import inspect from pandas import DataFrame, Grouper, ExcelFile imps = globals().items() filtered_imps = [x[1] for x in imps if inspect.isclass(x[1])] print(filtered_imps)
Produces:
[<class '_frozen_importlib.BuiltinImporter'>, <class 'pandas.core.frame.DataFrame'>, <class 'pandas.core.groupby.grouper.Grouper'>, <class 'pandas.io.excel._base.ExcelFile'>]
Then you can foo()
over the list as necessary in a loop or as part of the comprehension, perhaps using a try ... except
to deal with exceptions on the way.