metaclasses and Exceptions

François Pinard pinard at iro.umontreal.ca
Sat Jul 31 08:33:11 EDT 2004


[Mark Nottingham]

> I have to define a fairly large number (~40) of exceptions, and
> need to keep a dictionary keyed on an error code for each, so that
> the appropriate exception can be looked up.  While I can manage
> it manually, it would be much cleaner and more reliable to use
> a metaclass to automatically create the dictionary from class
> attributes.

Yes, it is a bit annoying that exceptions are not types.  However, what
you could do with metaclasses for building a registry of exceptions,
you could achieve with module introspection.  Here is some example code:


---------------------------------------------------------------------->
class Erreur(Exception):
    diagnostic = "Erreur Pyam"

    def __str__(self):
        if self.args:
            return self.diagnostic + ': ' + ', '.join(map(str, self.args))
        return self.diagnostic

class ErreurDenotation(Erreur):
    diagnostic = "Dénotation invalide"

# [etc.]

def fabriquer_erreur_selon_nom():
    # J'aurais bien voulu donner une méta-classe à Erreur pour fabriquer le
    # registre au vol, mais une classe dérivée de Exception _doit_ être une
    # ancienne classe, pour des raisons techniques internes à Python.
    from types import ClassType
    for nom, valeur in globals().iteritems():
        if isinstance(valeur, ClassType) and issubclass(valeur, Erreur):
            erreur_selon_nom[nom] = valeur

erreur_selon_nom = {}
fabriquer_erreur_selon_nom()
----------------------------------------------------------------------<


-- 
François Pinard   http://www.iro.umontreal.ca/~pinard



More information about the Python-list mailing list