get a list of classes in this module

Mark McEahern marklists at mceahern.com
Wed Jun 12 15:24:04 EDT 2002


> I know I can use inspect.getmembers() to do this, but what if I
> want to put
> the helper method in the same file as the classes (i.e., validation.py)?
> How do I refer to *this* module?  Why do I want the helper in the same
> module?  Well, heck, why not?  ;-)

What I'm doing currently is using the base class, which I know will be
there, and using it to get the module and from there the subclasses:

class CreditCardValidation:
  ...

def validation_factory():
  c = CreditCardValidation
  m = inspect.getmodule(c)
  all_classes = inspect.getmembers(m, inspect.isclass)
  d = [k, v for k, v in all_classes.items() if issubclass(v, c)]

Then I doh! realized I can just use $baseclass.__subclasses_() method!

def validation_factory():
  classes = CreditCardValidation.__subclasses__()
  d = {}
  for c in classes:
    d[c.__name__] = c
  return d

Cheers,

// mark

p.s.  If I'm misusing the "factory" name, I'm all ears for other suggestions
for the name of this method.

-






More information about the Python-list mailing list