metaclass question

Ian Kelly ian.g.kelly at gmail.com
Mon Sep 24 16:53:06 EDT 2012


On Mon, Sep 24, 2012 at 11:43 AM, Chris Withers <chris at simplistix.co.uk> wrote:
> Hi All,
>
> Is there a metaclass-y way I could cause the following:
>
> class TheParser(Parser):
>     def handle_ARecord(self):
>         pass
>     def handle_ARecord(self):
>         pass
>
> ...to raise an exception as a result of the 'handle_ARecord' name being
> reused?

In Python 2.x, no.

In Python 3.x, the __prepare__ method of the metaclass allows you to
specify a custom namespace object for the class definition.  The most
commonly cited use case is to use an OrderedDict to remember the order
in which the attributes are defined, but you could also use a dict
subclass that raises an exception if an attribute is redefined.  See
the docs at:

http://docs.python.org/dev/reference/datamodel.html#preparing-the-class-namespace



More information about the Python-list mailing list