问题
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.
回答1:
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.
回答2:
from module import a, b, c
is already basically just shorthand for
import module
for x in ['a', 'c', 'c']:
globals()[x] = getattr(module, x)
You can insert your own wrapper around the value injected into the global namespace.
import module
for x in ['a', 'b', 'c']:
globals()[x] = foo(getattr(module, x))
# foo(getattr(module, x)) # If you don't actually need the global name
For multiple modules, you can define a dict mapping module names to class names and use importlib.import_module
, rather than an import
statement, to do the actual import.
from importlib import import_module
classes = {'a': 'A', 'b': 'B'}
for m, c in classes.items():
globals()[c] = getattr(import_module(m), c)
回答3:
You could add the imports to a list then use a for loop:
import_list = [a,b,c]
for x in import_list:
foo(x)
来源:https://stackoverflow.com/questions/65080864/how-do-i-make-a-list-of-imported-classes-in-python