Test if class is in module before importing the module

Viewed 48

Is it possible to test if a class is in a module before importing the module?

Given root_package.sub_package.some_module.a_class I would like to see if some_module has an attribute a_class before attempting to import the module using importlib.

I can write custom code to test for the a_class definition in the module source file but was hoping for standard library functionality to do this with.

1 Answers
try:
    from module import Class
    # remove imported class if you just need to test
    del Class
    print("Found")
except ImportError:
    print("Not Found")
Related