Nishant
Nishant

Reputation: 21914

What is the significance of the wrapper method?

def decorator(func):
   def wrapper(func):
     do something before
     func()
     do something later

   return wrapper

func = decorator(func) ----> This is my decoarated function func() does the decorated stuff and gives me the output .

Why not just decorate it simply ?

def decorator(func):

    do something before
    func()
    do something later

decorator(func)

The only advantage I can see is that in one case I get the func object for assigning and re-use . I suppose the question is a bit vague , but I am thinking why do we need to return a function object if our purpose is to just decorate ? I mean whats the advantage ?

Upvotes: 1

Views: 81

Answers (2)

mipadi
mipadi

Reputation: 410612

Consider what the decorator syntax means. This:

@decorator
def say_hi():
    print "Hello!"

is syntactic sugar for this:

def say_hi():
    print "Hello!"
say_hi = decorator(say_hi)

So, a decorator basically takes in a function, and returns a new, modified function. Put another way, before decoration, say_hi is a function; afterwards, it is still a function…albeit a modified one.

If the decorator was written like this:

def decorator(fn):
  return "Something else"

Then, before decoration, say_hi would be a function, but afterwards, it would have the value "Something else" (a string) instead -- and now it's no longer callable!

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251363

You have to return a function object to re-use if you want to ever use the decorated function in more than one place.

In your second example, calling decorator(func) calls func. That means that if you want the decorator behavior (i.e., the "something before" and "something after"), you have to call decorator(func) every time.

The point of a decorator is that you effectively do func = decorator(func) and then, forever after, when you call func it automatically invokes the decorator behavior.

Upvotes: 3

Related Questions