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

Gerrit Holl gerrit at nl.linux.org
Wed Jun 11 11:25:01 EDT 2003


Andrew Bennetts wrote:
> 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?

> 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.

Ah, I see. But it is tempting... :)

Makes me wonder: what is the definition of a (new-style) class?
Is that anything that is an instance of type?

> 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

Hmmm...... this is kinda cool, somehow... instead of an "obfuscated code"
contest, this would be a contender for an "abusing code" contest.

Cool contest that would be :)

yours,
Gerrit.

-- 
122. If any one give another silver, gold, or anything else to keep, he
shall show everything to some witness, draw up a contract, and then hand
it over for safe keeping.
        -- 1780 BC, Hammurabi, Code of Law
--
Asperger Syndroom - een persoonlijke benadering:
	http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
	http://www.sp.nl/





More information about the Python-list mailing list