I'm working on a project which due to the complexity of the business logic has had to pull out some classes to do computation related to some values in a database. To link the code and database, both when inserting and selecting, I need to get a list of all the class names contained within a single file. It works for me, but is this a sane approach?
import inspect
import my_module
my_module_class_names = [
name for name, clazz in inspect.getmembers(my_module, inspect.isclass)
if clazz.__module__ == my_module.__name__
]
inspect.getmembers(my_module, inspect.isclass)
gets any class members ofmy_module
.if clazz.__module__ == my_module.__name__
ensures that classesimport
ed intomy_module
are excluded from the list. This is the main reason I'm asking for a review - I only thought to include this clause because I had alreadyimport
ed other classes, and therefore the list had extraneous members.
Alternatively, from within my_module
:
import inspect
import sys
def class_names() -> List[str]:
return [
name for name, clazz in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if clazz.__module__ == sys.modules[__name__].__name__
]