Python — Check if object is instance of any class from a certain module

You can use inspect.getmembers to get all the classes in your module:

inspect.getmembers(my_module,inspect.isclass)

This will return a list of name-class pairs. You just want the classes:

my_module_classes = tuple(x[1] for x in inspect.getmembers(my_module,inspect.isclass))

One thing that I managed to overlook when I initially wrote this answer is the ability to check a class’s __module__ attribute. You might be able to get away with checking if the __module__ is what you expect it to be:

from somewhere import module

if getattr(obj, '__module__', None) == module.__name__:
    # obj is from module.

This is likely to be cheaper than isinstance checking against a large list of class names.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)