explain this function to me, lambda confusion

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue May 20 03:09:13 EDT 2008


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.




More information about the Python-list mailing list