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:
You'd see an output something like the following:
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:
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:
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.
For more python tips, tricks, and guides you can check here.