[Python-Dev] Definining properties - a use case for class decorators?

Nick Coghlan ncoghlan at gmail.com
Mon Oct 24 11:35:19 CEST 2005


Josiah Carlson wrote:
> You can get the same semantics with...
> 
> class NAME(_(TYPE), ARGS):
>     BLOCK
> 
> And a suitably defined _.  Remember, not every X line function should be
> made a builtin or syntax.

And this would be an extremely fragile hack that is entirely dependent on the 
murky rules regarding how Python chooses the metaclass for the newly created 
class. Ensuring that the metaclass of the class returned by "_" was always the 
one chosen would be tricky at best and impossible at worst.

Even if it *could* be done, I'd never want to see a hack like that in 
production code I had anything to do with.

And while writing it with "__metaclass__" has precisely the correct semantics, 
that simply isn't as readable as a new block statement would be, nor is it as 
readable as the current major alternatives (e.g., defining and invoking a 
factory function).

An alternative to a completely new function would be to simply allow the 
metaclass to be defined up front, rather than inside the body of the class 
statement:

   class @TYPE NAME(ARGS):
       BLOCK

For example:

   class @Property x():
       def get(self):
           return self._x
       def set(self, value):
           self._x = value
       def delete(self, value):
           del self._x

(I put the metaclass after the keyword, because, unlike a function decorator, 
the metaclass is invoked *before* the class is created, and because you're 
only allowed one explicit metaclass)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.blogspot.com


More information about the Python-Dev mailing list