[Python-ideas] __decorate__ method

Paul Moore p.f.moore at gmail.com
Tue Apr 20 09:35:49 CEST 2010


On 20 April 2010 03:37, Zac Burns <zac256 at gmail.com> wrote:
> I would like to propose an extension to behavior the decorator syntax. For
> @decorator '@' should see if decorator supplies a __decorate__ method. If
> so, call the __decorate__ method. Otherwise, call decorator directly.
>
> Guido does say that __decorate__ should not replace __call__ here
> http://markmail.org/message/ig6diu6j55flxr6c, saying
>
> """
> Q: Is there a strong feeling (in any direction) about calling the
> decorator's "decorate" or "__decorate__" attribute, rather than its
> "__call__" attribute?
>
> A: It should be __call__; that's the only backwards compatible way, and
> makes it easy to create decorators as functions.
>
> """
>
> (Sidenote: Can someone explain what the backward incompatibility is?)

A key use case for decorators was to implement classmethods and
similar things, where the "old form" is to use f=classmethod(f) after
the definition.

class A:
    def f(cls):
        ...
    f = classmethod(f)

becomes

class A:
    @classmethod
    def f(cls):
        ...

The backward compatibility requirement is that classmethod (and
similar user defined cases) don't have to change.

> There is one use case I have run into where I wanted to make a distinction
> between __call__ and __decorate__. It is a Null object, which is like None
> but supplies several interfaces. It's an empty collection, a context that
> does nothing, a callable that returns None, and should be a decorator that
> returns the original function - except that it's already a callable that
> returns None. This object is cool for doing stuff like:
> """
> with (blocking if block else Null):
>    doSomething()
> """
> Rather than
> """
> if block:
>    with blocking:
>       doSomething()
> else:
>    doSomething
> """
> And, it fits in several spots like "os.walk(x, onerror=Null)" for example.
>
> I'll admit, the use case here is fairly spurious. There may be use cases
> which are more 'real'. If not, C'est la vie.

I can't see why you'd ever want to use Null as a decorator - so I'm
unconvinced by your use case. In any case, even if there is a reason
for having a null decorator, it's not clear to me that it can't be a
different object from your Null object - there's no reason to have all
the functionality covered by one "kitchen sink" object.

So sorry, but I'd say this proposal isn't justified (I'd assume it's
probably disallowed under the moratorium anyway).

Paul.



More information about the Python-ideas mailing list