explain this function to me, lambda confusion

Arnaud Delobelle arnodel at googlemail.com
Tue May 20 03:21:11 EDT 2008


Bruno Desthuilliers <bruno.42.desthuilliers at websiteburo.invalid> writes:

> Paul McGuire a écrit :
>> On May 19, 11:04 am, Arnaud Delobelle <arno... at googlemail.com> wrote:
>>> Paul McGuire <pt... at austin.rr.com> writes:
>>>
>>> [...]
>>>
>>> Could you use it as a decoratore instead?
>>>
>>> integer = Word("0123456789")
>>>
>>> @integer.setParseAction
>>> def parse_integer(tokens):
>>>     return int(tokens[0])
>>>
>>> I could make your grammar clearer, because you don't mix it with
>>> processing code... and no need for lambdas!
>>
>> What a sexy little idiom!  You could really apply this to any API
>> method that accepts a callable as a single argument, and pyparsing
>> actually has several of these:
>>
>> setParseAction
>> addParseAction
>> setFailAction
>> setDebugActions
>>
>> (Unfortunately, setDebugActions requires 3 callables for its arguments
>> - one to be run when an expression is about to be parsed, one to be
>> run after parsing is complete, and one to be run if the expression
>> fails to be parsed.  So setDebugActions can't be used in this
>> decorator manner.)
>
> You just have to provide three decorators instead, one for each callback.
>
>>
>> Using these methods as decorators deviates from the typical decorator
>> usage model as I understand it - instead of wrapping the provided
>> function within some enclosing setup/teardown code (like lock/unlock,
>> or open-file/close-file, or begin-transaction/commit-transaction), and
>> then returning the created wrapper function, the decorator usage you
>> propose is one in which the decorator uses the provided function with
>> some side-effect (such as setting a property), but then just returns
>> the original function.
>
> This is already a well-known decorator pattern. It's used in CherryPy
> to mark methods that are exposed as request handlers.

Actually, IIRC the decorator provided by CherryPy is something like
(names are probably wrong, as I haven't looked at CherryPy for a
while):

def exposed(f):
    f.is_exposed = True
    return f

So it doesn't mutate anything else than the function that it
decorates, but changes slightly how the world sees that function.
This is in line with classic decorators such as staticmethod,
classmethod, etc.

-- 
Arnaud



More information about the Python-list mailing list