4

I am trying to understand decorators behavior by doing some experiments. I am not able to find any doc on what I am seeing, so may be someone can point me to something.

Here is the code using a decorator:

def register():
    def func_wrapper(func):
        print 'registered'
    return func_wrapper

@register()
def main_page_func():
    pass

When you run this code, you will get the word "registered" printed out:

registered

This is presumably the equivalent(?) code without decorator:

def register(func):
    def func_wrapper():
        print 'registered'
    return func_wrapper


def main_page_func():
    pass

main_page_func = register(main_page_func)

When you run the above, nothing gets printed out. I understand this case: func_wrapper callback is returned.

However, I am still struggling with the first case that uses decorator: Why is print statement being invoked given that main_page_func is never being called?

Thanks.

1
  • Change @register() to @register and def register(): (in the first example) to something like def register(f): and func_wrapper(func) (in the first example) to func_wrapper()
    – jedwards
    Mar 11, 2015 at 0:14

2 Answers 2

4

When you say,

@register()

it actually calls the function register() and the return value is used there, which will be func_wrapper, which accepts a function object as input. So, what you have done is

@func_wrapper
def main_page_func():
    pass

And when you decorate it like this,

main_page_func = func_wrapper(main_page_func)

func_wrapper is invoked and that is why the registered is getting printed.

To actually fix this, you need to pass the function object to register itself, like in your second example,

def register(func):         # func should be here
    def func_wrapper():     # not here
        print 'registered'
    return func_wrapper


@register                   # no parens after `register`
def main_page_func():
    pass

Now, the evaluation is like this

main_page_func = register(main_page_func)

Since the func_wrapper is not yet executed, you will not see registered getting printed, yet.

1

Erase the parentheses after the decorator and it will work just as you expect it to.

Also, your register function should take the argument func, but not neccessarily your inner function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.