Are decorators really that different from metaclasses...

Paul Morrow pm_mon at yahoo.com
Wed Aug 25 13:39:10 CEST 2004


Anthony Baxter wrote:
> On Tue, 24 Aug 2004 12:29:38 -0400, Paul Morrow <pm_mon at yahoo.com> wrote:
> 
>>....that they warrant an entirely new syntax?  It seems that they are
>>very similar in a very significant way --- they alter the default
>>behavior of something.  IMO, it's not a stretch to say that they
>>'parallel' metaclasses; that they are to functions/methods what
>>metaclasses are to classes.  So why don't they share a similar syntax?
> 
> 
> No. Function decorators are to functions as class decorators are to classes.
> 

Maybe, if they ever show up.  But until then metaclasses are the closest 
thing.


> Class decorators are not in 2.4, because you can do most things you'd
> do with a class decorator by using a metaclass, but in a completely
> different way. In my opinion, class decorators _should_ be in 2.4,
> because they're a much saner way to handle many things that require a
> metaclass today.
> 

I'd like to see a compelling example of Class decorators.  Something 
that justifies using them instead of metaclasses.



> They don't "alter the default behaviour". A metaclass allows the user
> to specify an object that builds classes in a new way. A decorator
> allows the user to specify a way to transform the already built
> function (or class, for class decorators).
> 

If you want to think about them that way, go ahead.  But it's easier 
(and I believe just as valid) to think about them in terms of altering 
the default behavior of an object.  For example...

    class Foo:
        __metaclass__ = M         # comment out for default behavior

When I use a metaclass, I don't want to "specify an object that builds 
classes in a new way".  That's an awkward way to think about it.  I want 
to change the behavior of *my* class.  Period.  Likewise, when I use a 
decorator, say 'memoized', on my function, I most definitely *do not* 
want to think about what's going on under the hood --- that my function 
is first created, then 'transformed' by the memoized decorator.  No.  I 
want to think that my function simply has the 'memoized' feature and let 
the system worry about the details of making that happen.





More information about the Python-list mailing list