get a list of classes in this module

Mark McEahern mark at mceahern.com
Wed Jun 12 14:48:40 EDT 2002


Suppose I have a list of classes:

# validation.py
class CreditCardValidation:
  ...

class MasterCard(CreditCardValidation):
  ...

class Visa(CreditCardValidation):
  ...

and I want to make a helper method in the module to translate card type
strings into their appropriate class constructor.

# someother.py
def validate(card_number, card_type=None):
  import validation
  import inspect
  classes = inspect.getmembers(validation, inspect.isclass)
  class_dict = dict(classes)
  if not class_dict.has_key(card_type):
    # use generic validation
    c = validation.CreditCardValidation()
  else:
    c = class_dict[card_type]()
  c.card_number = card_number
  c.validate()

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?  ;-)

Should I use globals()?  I mean, that would work--so I guess the question is
whether there's a more Pythonic approach?

Cheers,

// m

-






More information about the Python-list mailing list