I have a module where all classes that implement my “policies” are defined.
class 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?:The
get_slug_to_class_itemsfunction finds classes that inherit fromPolicy_Base(recursively iterating on the class hierarchy) and returns a generator of 2-tuples (slug, class) to be set as the items of the expecteddict.Note it’s important that all modules with “policy” classes are imported before calling
get_slug_to_class_items.