Search⌘ K
AI Features

Python Decorators

Explore how Python decorators modify functions and enable code reuse in Flask. Understand routing, handling unique URI identifiers, and managing server responses in API development.

Introduction to Python decorator

A Python decorator is a function that takes a function and replaces it with the modified version. Let’s look at an example.

Python 3.5
import time
def with_timer(f):
def new_function(*args, **kwargs):
start_time = time.time()
result = f(*args, **kwargs)
end_time = time.time()
print('Elapsed time:', end_time - start_time)
return result
return new_function
@with_timer
def pointless_waiting(s):
time.sleep(s)
return 'Done'
pointless_waiting(2)

Explaining the code

The example defines a function called with_timer that takes in a function, f, and outputs a function new_function. The input function argument, f, is used inside new_function, but is sandwiched between timer computations and a timer output. The *args and **kwargs arguments are how we specify all positional and keyword arguments. The use of the function with_timer with the at-notation @ makes it a ...