Need a way to check if an object is an instance of any class in some particular module.
I know I can do it by explicitly importing every class from that module and checking with a tuple:
from my_module import ClassOne, ClassTwo
>>> isinstance(my_obj, (ClassOne, ClassTwo))
# Test my_obj against the module itself
>>> isinstance(my_obj, my_module)
TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
# Try to test against a wildcard attribute on my_module
>>> isinstance(my_obj, my_module.*)
SyntaxError: invalid syntax
#Try to build a tuple of clases with iteration to check against
>>> for klass in my_module:
TypeError: 'module' object is not iterable
You can use
inspect.getmembers to get all the classes in your module:
This will return a list of name-class pairs. You just want the classes:
my_module_classes = tuple(x 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.