Skip to content Skip to sidebar Skip to footer

Why Are Decorator Functions Designed In The Way They Are?

It was bothering me for a long time. Why are decorator functions designed like that, they seem to me over complicated. Let's take for example something like this: def dec(f): d

Solution 1:

A decorator should return a function not the result of a function. In your first example, it returns a function ... In the second, it returns whatever your function f returns. - julien

  1. Why second sample does not works?

    Because you are calling the function on the return, you are not returning a function.

  2. Why args,kwargs are "magically" appears if we are using a nested function?

    They don't appear magically, we are declaring them, as in:

    defdeco(*args, **kwargs):
    

    These are generic, and will match any function signature (argument list). You don't have to call them args and kwargs, that's just a convention, you could call them sharon and tracy.

  3. What can i do, to make 2nd sample work? Except nesting another function, ofcourse.

    Well you don't say what you expect the 2nd sample to do. But I guess to turn it into a decorator then:

    def func(f):
        return f
    

    But that's not doing a lot!

By the way, it is usually a bad idea to override an existing Python builtin (sum) - you have to have a very good reason for that. - cdarke

Source

Post a Comment for "Why Are Decorator Functions Designed In The Way They Are?"