What is a decorator in Python?

A decorator is a function that takes another function, adds some extra behaviour to it, and returns the new function. You apply it by writing @decorator_name above the function, and the original code stays unchanged.

def shout(func):
    def wrapper():
        result = func()
        return result.upper()
    return wrapper

@shout
def greet():
    return "hello"

print(greet())

Output:

Tutorials Class - Output Window

HELLO

Writing @shout above greet is the same as writing greet = shout(greet). Decorators are used for logging, timing, login checks and caching. Use functools.wraps inside real decorators to keep the original function name. Learn more in Python Decorators.


Learn more about the similar topics:
Tutorials
Python Decorators
Python Closures
Python Iterators and Generators
Python Modules
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is a decorator in Python?
What are iterators in Python?
What is a generator in Python?
What is the GIL in Python?
What is the difference between a module and a package in Python?
How does Python manage memory?
What is the with statement in Python?