Decorators (concept)

Computer Science · Python

Question 1 of 10

0

    What does the @abstractmethod decorator mark a method as?

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Decorators (concept) explained

    A decorator is a function that takes another function, wraps it with extra behaviour and returns the new function. It lets you add things such as logging or timing to many functions without changing their code one by one.

    The @ syntax above a function definition is shorthand. Writing @shout above def greet is the same as writing greet = shout(greet) after the definition. The decorator usually defines an inner wrapper function that runs some code, calls the original function with the same arguments and returns the result. Functions are objects in Python, so they can be passed into other functions and returned from them. A decorator that uses a wrapper replaces the original name, so use functools.wraps in production code to keep the original name and documentation.

    def shout(func):
        def wrapper(text):
            return func(text).upper() + "!"
        return wrapper
    
    @shout
    def greet(name):
        return "hello " + name
    
    print(greet("ana"))
    

    Worked example

    Trace the code above.

    1. @shout makes greet refer to wrapper, which calls the original greet.
    2. greet("ana") first runs the original function and returns "hello ana".
    3. wrapper applies .upper() to get "HELLO ANA" and adds "!".
    4. print displays HELLO ANA!

    What you will practise

    102 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • A decorator:
    • The @ symbol marks:
    • Decorators run:
    • A common use is:
    • A decorator returns:
    • In Python, a decorator is most accurately described as:
    • The line @my_dec placed above def f(): is equivalent to:
    • Functions are first-class objects in Python, which means they can:

    …and 94 more.