Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #29928

Re: metaclass question

References <50609BC5.3020004@simplistix.co.uk>
From Ian Kelly <ian.g.kelly@gmail.com>
Date 2012-09-24 14:53 -0600
Subject Re: metaclass question
Newsgroups comp.lang.python
Message-ID <mailman.1210.1348520018.27098.python-list@python.org> (permalink)

Show all headers | View raw


On Mon, Sep 24, 2012 at 11:43 AM, Chris Withers <chris@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: metaclass question Ian Kelly <ian.g.kelly@gmail.com> - 2012-09-24 14:53 -0600

csiph-web