Let’s say you have a bunch of classes in a module that you want to extract and run a common operation on.

How would you achieve this?

Your first instinct might be to import the module with all the classes in it and use python’s dir function to extract all the classes.

However, you can’t do that because of all the other attributes that get defined on a python module. For example, if you do:

1
2
3
import my_module

dir(my_module)

You’d see an output something like the following:

1
2
3
4
5
6
7
8
9
10
11
12
['ClassA',
 'ClassB',
 'ClassC',
 '__builtins__',
 '__cached__',
 '__doc__',
 '__file__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
]

Thus, if we want to get only the classes from the module, we need to do something else. What is that something else?

OK, so we know we can use dir to get a list of all the attributes for a given module. We just need a way to filter out things that aren’t classes. For that, we can use the isclass function from python’s inspect module.

This would look like the following:

1
2
3
4
5
import inspect
import my_module
module_attributes = dir(my_module)  
module_attributes = [getattr(my_module,attr) for attr in module_attributes]
classes = [attr for attr in module_attributes if inspect.isclass(attr)]

And if you print out classes, it should now look something like this:

1
2
3
4
['ClassA',
 'ClassB',
 'ClassC',
]

Awesome! Now we have all of the classes in a list and can we can do whatever we want with them, whether that be calling some common static method, passing them to a function, instantiate some objects, or whatever.

I hope this was helpful.