Python decorator

def test(f):
    print "before ..."
    f()
    print "after ..."
 
@test
def func():
    print "func was called"

Run this file, and there is output:

before ...
func was called
after ...

The two functions are not called and there is supposed to have no output.

But when Python compiler finds the decorator "@", these steps are executed:

  1. call function test, the input parameter for test is the function named "func"

  2. test function is being executed

What you're doing is calling test, then using the result of that call to decorate func. Therefore runs immediately.

Last updated