Til

not stolen from simonw

View the Project on GitHub Coding4Hours/Til

Decorators

Decorators can make python also a kinda nice language but still, meh.

# this is the decorator function
def add_exclamation(func):
  def wrapper(name):
    return func(name) + '!'
  return wrapper

# this is the function being decorated -- the decoratee (?)
def hello(name):
  return 'hello ' + name

# actually decorating the function
hello = add_exclamation(hello)

# now our function's behaviour has changed slightly
print(hello('tom'))    # hello tom!
def add_exclamation(func):
  def wrapper(name):
    return func(name) + '!'
  return wrapper

@add_exclamation
def hello(name):
  return 'hello ' + name

print(hello('tom'))    # hello tom!