Decorator Dissection

El Pitonero pitonero at gmail.com
Sat Apr 2 15:29:20 EST 2005


Ron_Adam wrote:
> On 2 Apr 2005 08:39:35 -0800, "Kay Schluehr" <kay.schluehr at gmx.net>
> wrote:
>
> >There is actually nothing mysterious about decorators.
>
> I've heard this quite a few times now, but *is* quite mysterious if
> you are not already familiar with how they work.  Or instead of
> mysterious, you could say complex, as they can be used in quite
> complex ways.

If the syntax were like:

decorator = function(d_arg) {
    return function(f) {
        return function(f_arg) {
            new_arg = f_arg+'-'+d_arg;
            return f(new_arg);
        }
    }
}

func = decorator('Goodbye') function(s) {
    return s;
}

Would you think it would be more easily understandable? Here,
"function()" is a metafunction (or function factory) whose role is to
manufacture a function given a parameter spec and a code body. And in
the expression

func = decorator('Goodbye')(function(s){return s;})

one pair of outter parenthesis have been omitted. Sure, it's not as
readable as Python's "def", but with today's syntax highlighters, the
special word "function" can be highlighted easily.

If the decorator does not have parameters, one has:

func = decorator function(s) {
    ....
}

or in the general case:

func = deco1 deco2 deco3 function(s) {
    ....
}




More information about the Python-list mailing list