I have a following small Python program:
def wrap(func):
print "before execution ..."
a = func()
print "after execution ..."
return a
@wrap
def dosomething():
print "doing something ..."
When I execute above script I should not get any output as I am not calling:
dosomething()
But when I execute this script I get the following output:
before execution ...
doing something ...
after execution ...
Please explain the reason for this behavior
A decorator is just a callable that takes a function as an argument and returns a replacement function. We’ll start simply and work our way up to useful decorators.
The @ symbol applies a decorator to a function so it's equal to:
dosomething = wrap(dosomething)
Which runs wrap. and prints the output.
Here's some info about decorators: https://wiki.python.org/moin/PythonDecorators
http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/