get a list of classes in this module

Mark McEahern marklists at mceahern.com
Thu Jun 13 14:56:22 CEST 2002


[Christian Tanzer]
> I'd recommend to use a custom metaclass to put the classes in question
> into the dictionary -- this way some other module can add credit card
> classes and it should still work.

Hmm, putting the other credit card classes in other modules creates a new
problem:  I have to import those modules.  Another way of looking at what
I'm trying to do--that I failed to state explicitly--is that I'm trying to
get a list of all the available classes at runtime, via introspection,
without having to specify them explicitly.  Having to import the other
modules amounts to having to specify them explicitly.

Here's another solution to the problem, fwiw, using classmethod to stick the
factory method inside the base class:

class CreditCardValidation(object):

  def factory(cls):
    classes = cls.__subclasses__()
    d = {}
    for c in classes:
      d[c.__name__] = c
    return d
  factory = classmethod(factory)

  def validate(self, card_number):
    raise NotImplementedError("Subclasses must override.")

class Visa(CreditCardValidation):

  def validate(self, card_number):
    print "Visa: %s" % card_number

class MasterCard(CreditCardValidation):

  def validate(self, card_number):
    print "MasterCard: %s" % card_number

f = CreditCardValidation.factory()
card_type = "Visa"
card_number = "5105 1051 0510 5100"

validator = f[card_type]()
validator.validate(card_number)

Thanks for the suggestion.  I find it much easier to just utilize
__subclasses__ than to peer into the mysteries of metaclass programming.

Cheers,

// mark

-






More information about the Python-list mailing list