stacked decorators and consolidating

MRAB python at mrabarnett.plus.com
Tue Oct 29 13:42:45 EDT 2013


On 29/10/2013 16:54, Tim Chase wrote:
> I've got some decorators that work fine as such:
>
>    @dec1(args1)
>    @dec2(args2)
>    @dec3(args3)
>    def myfun(...):
>      pass
>
> However, I used that sequence quite a bit, so I figured I could do
> something like
>
>    dec_all = dec1(args1)(dec2(args2)(dec3(args3)))
>
> to consolidate the whole mess down to
>
>    @dec_all
>    def myfun(...):
>      pass
>
> However, this yields different (test-breaking) results.  Messing
> around, I found that if I write it as
>
>    dec_all = lambda fn: dec1(args1)(dec2(args2)(dec3(args3)(fn)))
>
> it works and passes all preexisting tests.
>
> What am I missing that would cause this difference in behavior?
>
If you apply the stacked decorators you get:

     myfun = dec1(args1)(dec2(args2)(dec3(args3)(myfun)))

If you apply dec_all you get:

     myfun = dec1(args1)(dec2(args2)(dec3(args3)))(myfun)

See the difference? You need the lambda to fix that.



More information about the Python-list mailing list