mercredi 4 juillet 2018

Python: determine base class of a class_object

I have the following code:

if __name__ == '__main__':

module_name = sys.argv[1]
is_lite = sys.argv[2]

importlib.import_module(module_name)

for name, class_object in inspect.getmembers(sys.modules[module_name]):
    if inspect.isclass(class_object) and not inspect.isabstract(class_object):

        try:
            print "\n\n\n"
            print "Executing: "
            print class_object
            print "\n\n\n"

            instance = class_object()
            instance.execute(is_lite)
        except:
            pass

All objects to be instantiated are actually sub-classes of a class named: Foo which is abstract.

The class_objects returns by inspect contains ALL classes contained in the module, it means that imports are also present in the list, and import are not sub-classes of Foo.

What I am looking for is simply a method to obtain the following information:

is(class_object, Foo)

or

class_object.class == Foo.class

This would allow me to get rid of the try catch and have a more logical and robust code.

But so far I found nothing, it seems there no simple way of retrieving the information that is contained into modules returned by the inspect framework.

I also tried to use the builtin issubclass method but it is failling probably because class_object is not an instance of the class but simply a describer of it.

Thanks for help.





Aucun commentaire:

Enregistrer un commentaire