Contents of module.py
:
__all__ = ["A", "B"]
class A(object):
ATTRIBUTE = 'a'
class B(object):
ATTRIBUTE = 'b'
My goal is to import this module and create the following dict: {'a': A, 'b': B}
, mapping the ATTRIBUTE
of each class to the class itself. The catch is that I don't know the names of the classes, so I cannot simply do: from module import A, B
. However, I do know that all the classes I want should be stored in the __all__
variable.
I tried the following code, which works, but it looks ugly, I wonder if there is a more pythonic way to get my expected output?
Contents of main.py
:
import module
from module import __all__ as module_all
if __name__ == '__main__':
data = {}
for obj_str in module_all:
obj = eval("module.{}".format(obj_str))
data[obj.ATTRIBUTE] = obj
print(data)
Output:
{'a': <class 'module.A'>, 'b': <class 'module.B'>}