Python 3D Academyবাংলা

Your first decorator: wrapping a function

🌍 In real life. A gift shop wraps your present. The gift inside doesn't change at all, but now there is something extra around it: paper, a ribbon, a card that says who it's from.

A decorator wraps a function the same way. It adds something before and/or after the function runs (a message, a check, a change to the result) without touching the function's own code. Step by step:

  1. a decorator is a function that takes a function (func)
  2. inside, it defines a wrapper that does the extra work and calls func
  3. it returns the wrapper
  4. @announce on the line above def means greet = announce(greet): the name now points to the wrapper, with the real function inside

The idea in one sentence: a decorator is a function that takes a function and returns a wrapper that adds something before or after it, and @name above a def applies it.

Its words:

  • decorator: def announce(func): ... return wrapper
  • wrapper: the new function that runs the extra job and calls the original
  • @announce: shorthand for greet = announce(greet)
def announce(func):
    def wrapper(name):
        print("starting")
        result = func(name)
        print("finished")
        return result
    return wrapper

@announce
def greet(name):
    return "Hello, " + name

print(greet("Ana"))
@announce is just a short way to write greet = announce(greet) after the def.

Why it matters: the same decorator can wrap many functions. Write the extra job once (logging, timing, checking), then put @its_name on any function that needs it. A wrapper can also change the result before giving it back, like a gift shop that adds a bow:

def shout(func):
    def wrapper(text):
        return func(text).upper() + "!"
    return wrapper

@shout
def order(food):
    return "one " + food + " please"

@shout
def thanks(name):
    return "thank you " + name

print(order("samosa"))
print(thanks("Bo"))

Mistakes and edge cases.

  • Forgetting to return the wrapper. The decorator then returns None, so greet becomes None, and calling it gives TypeError: 'NoneType' object is not callable.
  • Forgetting to return the result. A wrapper that calls func() but doesn't return it makes every decorated function give back None.
  • Calling the function in the decorator. return func() runs it once at definition time; the decorator must return a function.
  • A wrapper with no parameters. It only fits functions with no arguments; the next lesson fixes that.

Quiz

  1. What does this print?

    def loud(func):
        def wrapper():
            return func().upper()
        return wrapper
    
    @loud
    def hello():
        return "hi"
    
    print(hello())
  2. What does this print?

    def bell(func):
        def wrapper():
            print("ding")
            return func()
        return wrapper
    
    @bell
    def lunch():
        return "rice"
    
    print(lunch())
    print(lunch())
  3. What does @announce above def greet mean?

    • greet = announce(greet)
    • announce = greet(announce)
    • Call greet, then call announce
  4. What does this print?

    def plus_ten(func):
        def wrapper(n):
            return func(n) + 10
        return wrapper
    
    @plus_ten
    def double(n):
        return n * 2
    
    print(double(5))
  5. Which line has a mistake?

    def announce(func):
        def wrapper():
            print("starting")
            return func()
        return wrapper()
    
    @announce
    def work():
        return "done"
    
    print(work())

Coding tasks

  1. Write a decorator announce whose wrapper prints "starting", calls the function (it takes no arguments), prints "finished", and returns the function's result.

  2. Write a decorator double_result for functions of one argument: its wrapper returns twice what the function returns.

  3. Write a decorator shout for functions of one argument: its wrapper returns the function's text in capitals with "!" on the end. Use it on order(food), which returns "one " + food + " please".