-1

I dont understand how decorators execute. Since the decorated function is being overwritten

For the following example

def get_text(name):
  return "{0}".format(name)

def decorate(func):
  def func_wrapper(name):
    return "{0}".format(func(name))
  return func_wrapper

When the following statement will be executed, get_text will be overwritten by what the decorator returns.

get_text = decorate(get_text)

Since get_text is overwritten. How can the original get_text function run inside the returned statement from the decorator. When I do the following

print get_text("John")
Mustafa Khan
  • 397
  • 1
  • 5
  • 13
  • Where did you get that example? – mikeb Feb 01 '16 at 13:30
  • 3
    `get_text` isn't overwritten, there's just a reference pointing somewhere else now. The original function still exists. – L3viathan Feb 01 '16 at 13:30
  • 1
    You have a *"closure"* over `func`, which allows `func_wrapper` to continue to access the original function even once the identifier references the wrapper. – jonrsharpe Feb 01 '16 at 13:34
  • I found links and answers at http://stackoverflow.com/questions/739654/how-can-i-make-a-chain-of-function-decorators-in-python which explained what you probably need to know. – sabbahillel Feb 01 '16 at 13:35

1 Answers1

0

Use it like this:

def decorate(func):
  def func_wrapper(name):
    return "{0} decorated".format(func(name))
  return func_wrapper

@decorate
def get_text(name):
  return "{0}".format(name)

print get_text('name')
output:
>>name decorated
Kenly
  • 24,317
  • 7
  • 44
  • 60