A general situation:
- I don't know what modules I'll be inspecting beforehand, I don't know what will be in them: classes, methods, etc.
- I do know what class I'm seeking, and what I need to do with it. e.g. I'll need to run a particular method, cls.register
- I need to find the most effective way to do this.
I haven't even gotten to specific code, or I'd post it. However I think I have some options:
- Just run everything in the module through
try
/except
if
/else
seeking for the method I need- Using inspect to find the exact match of classes in the module
- Using the meta class to add an attribute
this_is_class_sought=True
1-3 seem too crude, 4 seems like too much effort.
My situation:
I trying to integrate Flask-Classy with an application creator/factory.
I have a bunch of view files, I don't know what will be in these files. I need to find all classes that subclass FlaskView, but not FlaskView itself, and then run then class registration function.
So, for example from dir(a_module)
for randomly encountered module:
['FlaskView', 'AView', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'forms', 'models', 'redirect', 'render_template', 'request', 'url_for']
I need to determine that AView
is there, and run the registration method. 3, above seems likely, but I haven't exactly determined how to differentiate AView
, yet.
What is the best way to do this?
EDIT:
I must emphasize that the whole point is that I do not know what modules I'll be looking at, or what they will contain. I need to efficiently extract the information I need and act based on that information.
EDIT2:
__subclasses__() simplifies much for my purposes.