[Python-Dev] @decoration of classes
Jack Diederich
jack at performancedrivers.com
Tue Mar 29 02:55:50 CEST 2005
On Sat, Mar 26, 2005 at 12:36:08PM -0800, Josiah Carlson wrote:
>
> Eric Nieuwland <eric.nieuwland at xs4all.nl> wrote:
> >
> > Given the ideas so far, would it possible to:
> >
> > def meta(cls):
> > ...
> >
> > @meta
> > class X(...):
> > ...
>
> It is not implemented in Python 2.4. From what I understand, making it
> happen in Python 2.5 would not be terribly difficult. The question is
> about a "compelling use case". Is there a use where this syntax is
> significantly better, easier, etc., than an equivalent metaclass? Would
> people use the above syntax if it were available?
>
For compelling, I think the code smell put off by the "no conflict" metaclass
generator recipe (which also appeared in Alex Martelli's PyCon talk) is fairly
compelling from a duck typing point of view.
# would you rather
class K:
__metaclass__ = no_conflict(MetaA, MetaB)
# or
@decoA
@decoB
class K: pass
Unless you actually want a class two inherit magic methods from two different
types you don't need two metaclasses. You just need the class manipulations
that are done in two different metaclasses.
I get around this[1] by defining a function that calls things that manipulate
classes, the metaclass's init will make the 'register' function static if it
is defined in the __dict__ and then call it with (name, cls).
If I called that method 'decorate' instead and spelled it @decorate I'd be
a happy camper.
-jackdied
[1] "Register" metatype, define the register method to screw around with
your class definition or leave it out to let your parent class do its thing
class Register(type):
def __init__(cls, name, bases, dict):
if ('register' in dict):
setattr(cls, 'register', staticmethod(dict['register']))
cls.register(name, cls)
I call it Register because largely I just use it to check the __dict__ for
special methods and put classes in one or more global buckets. I have cron
jobs that operate on the different buckets.
More information about the Python-Dev
mailing list