Skip to content
pythonintermediate

Python Decorators

Decorators, closures and higher-order functions

6 questions

By EZ4Code Team

1. What is a decorator essentially?

A higher-order function that takes a function and returns a new function
A data type
A class
A syntactic sugar that cannot be customized
Explanation: A decorator is a callable object that takes a function (or class) and returns a new function (or class), applied using the @decorator syntactic sugar.

2. What does the following code output? def deco(f): def wrapper(): print('before') f() return wrapper @deco def hi(): print('hi') hi()

def deco(f):
    def wrapper():
        print('before')
        f()
    return wrapper

@deco
def hi():
    print('hi')

hi()
before then hi
hi then before
Only outputs hi
Error
Explanation: @deco is equivalent to hi = deco(hi); calling hi() actually calls wrapper(), which first prints 'before' then calls the original function to print 'hi'.

3. How many layers of nested functions does a parameterized decorator typically need?

Three layers: outer receives parameters, middle receives the function, inner executes
One layer
Two layers
No nesting needed
Explanation: A parameterized decorator is of the form deco(arg) returning the actual decorator, so it needs three layers of nesting: parameter layer, decorator layer, wrapper layer.

4. What is the purpose of using functools.wraps?

Preserves the metadata of the decorated function (such as __name__, __doc__)
Speeds up function execution
Makes the function asynchronous
Caches function results
Explanation: functools.wraps copies the __name__, __doc__, __module__ and other attributes of the decorated function to the wrapper, preserving metadata.

5. What is a closure?

An inner function references variables of an outer function and can still access them after the outer function returns
A private class
An anonymous function
A global variable
Explanation: A closure is a function that references free variables; even after the outer function has returned, these variables are retained and accessible by the inner function.

6. What does the following code output? def make_counter(): n = 0 def inner(): nonlocal n n += 1 return n return inner c = make_counter() print(c(), c())

def make_counter():
    n = 0
    def inner():
        nonlocal n
        n += 1
        return n
    return inner

c = make_counter()
print(c(), c())
1 2
1 1
0 1
Error
Explanation: inner modifies the outer n via nonlocal, forming a closure; each call increments, so c() returns 1 the first time and 2 the second time.

More python Quizzes