Properties using metaclasses (was: Function/Method Decorator Syntax)

Andrew Bennetts andrew-pythonlist at puzzling.org
Wed Jun 11 08:21:12 EDT 2003


On Wed, Jun 11, 2003 at 01:03:00PM +0200, Gerrit Holl wrote:
> Andrew Bennetts wrote:
> 
[...]
> > class C(object):
> >     class x(EvilProperty):
> >         """An evil test property"""
> >         def get(self):
> >             print 'Getting'
> >             return 1
> >         def set(self, value):
> >             print 'Setting to', value
[...]
> 
> Just a question: Why would this be evil? I think it is explicit, simple,
> sparse, readable, practical, unambiguous... The only real anti-zen-behaviour
> is that it's nested rather than flat. But for the rest, I don't see the
> problem, what is it?

Because I'm suspicious of metaclasses in general... although this is a
pretty neat solution, and I'm tempted to use it.  :)

Of course, the metaclass is behind the scenes, and the result is a simple
property, so there's no lingering weirdness.  The only really nasty thing is
that I'm abusing the "class" keyword: when I say "class x(EvilProperty)", x
is not a class.  *That's* what I consider evil, and why I hesitate to use
this in real code.

A more extreme example of abusing class was shown to me at PyCon by a fellow
Twisted developer (who shall remain nameless so that he won't get mobbed by
angry hordes ;) ... it looked something like this:

----
class Adder(type):
    def __new__(cls, name, bases, dict):
        return reduce(lambda x,y: x+y, bases, 0)

class C(1, 2, 3, 4, 5):
    __metaclass__ = Adder

print C
----

There's some things the class keyword was just never meant to do.

-Andrew.






More information about the Python-list mailing list