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

Michele Simionato mis6 at pitt.edu
Wed Jun 11 18:51:53 CEST 2003


Andrew Bennetts <andrew-pythonlist at puzzling.org> wrote in message news:<mailman.1055334140.8489.python-list at python.org>...
> 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.

I would *never* use in production code Andrew's suggestion (I realize
he also would not use it). But just to defend metaclasses, I want
to say that this kind of Evil Things have nothing to do with them:

class C(object):
    def __new__(cls,x):
        return x

c=C(1)
print type(c) #=><type 'int'> !

The problem is with __new__, the metaclass issue is a red herring.
I would not change the current behaviour of __new__, I found at least 
a convenient use case for this, but of course I am not advocating this 
kind of abuses.

                                    Michele




More information about the Python-list mailing list