Python: inspecting module to pick out classes of certain type?
I have a module where all classes that implement my "policies" are defined.
cla开发者_JS百科ss Policy_Something(Policy_Base):
slug='policy-something'
...
class Policy_Something_Else(Policy_Base):
slug='policy-something-else'
...
I need to create a mapping from slug to class. Something like:
slug_to_class = {
'policy-something': Policy_Something,
'policy-something-else': Policy_Something_Else
}
I was thinking instead of automatically creating slug_to_class by inspecting the module and looking for classes that inherit from Policy_Base (similar to how unittest finds tests, I assume).
Any reason I shouldn't do that? If not, how exactly would I do that?
Since your "policy" classes inherit from Policy_Base
, why not import all relevant modules and then do something like this?:
import re
def slugify(s):
return re.sub(r'\W+', '-', s.lower().replace('_', '-'))
def get_slug_to_class_items(policy_class):
yield (slugify(policy_class.__name__), policy_class)
for subclass in policy_class.__subclasses__():
for slug, subclass in get_slug_to_class_items(subclass):
yield (slug, subclass)
slug_to_class = dict(get_slug_to_class_items(Policy_Base))
# print repr(slug_to_class)
The get_slug_to_class_items
function finds classes that inherit from Policy_Base
(recursively iterating on the class hierarchy) and returns a generator of 2-tuples (slug, class) to be set as the items of the expected dict
.
Note it's important that all modules with "policy" classes are imported before calling get_slug_to_class_items
.
精彩评论