![]() |
VOOZH | about |
Function wrappers, also known as decorators, are a powerful and useful feature in Python that allows programmers to modify the behavior of a function or class without changing its actual code. Decorators enable wrapping another function to extend or alter its behavior dynamically at runtime.
Example:
Before execution Inside function! After execution
Explanation: deco function wraps another function f inside wrap, which prints messages before and after calling f. Applying deco to func modifies its behavior dynamically.
A decorator in Python is a function that takes another function as an argument and returns a modified version of that function. It is typically used for logging, enforcing access control, instrumentation, caching and more.
There are two common ways to apply decorators.
@wrapper
def function(n):
statements(s)
def function(n):
statement(s)
function = wrapper(function)
Before Running... After
Explanation: Instead of manually assigning func = deco(func), the @deco syntax is a cleaner way to apply decorators.
countdown ran in 0.000003s countdown ran in 0.000036s
Explanation: timeit decorator records the start time, executes the function, calculates the elapsed time and prints the duration. *args and **kwargs ensure compatibility with any function signature.
Access Denied! Welcome admin, access granted.
Explanation: admin_only decorator allows function execution only for admin users, restricting access with a message otherwise. It helps enforce security controls.