A decorator is a higher-order function that takes a function and returns a new function. It is used to modify the behavior of a function or a method. Decorators are used to add functionality to an existing function without modifying its structure.
This is the pattern used by decorators in Python. The @decorator syntax is just a shorthand for calling decorator with the decorated function as an argument.
πΆβπ«οΈ Without the decorator sugar:
This way of decorating may not seem inmediately useful, but it is useful when applied to functions that you donβt call directly yourself.
π With the decorator syntax:
The boilerplate with parameters π
This is the more generic use case for decorators.
If youβve called @decorator_handlerwithout arguments, then the decorated function will be passed in as _func.
If youβve called it with arguments, then _func will be None, and some of the keyword arguments may have been changed from their default values.
The asterisk (*) in the argument list means that you canβt call the remaining arguments as positional arguments.
_func is a positional argument.
Example
Output:
Measuring time
Given the following problem:
Write a function format_number that takes a non-negative number as its only parameter. Your function should convert the number to a string and add commas as a thousand separators. For example, calling format number(1000000) should return β1,000,000β
Implement a HOF that measures the time performance and run a profiler to check the performance of the function: