In Python, a decorator is a function that modifies the behaviour of another function or method.
Decorators are powerful tools for adding functionality to existing functions or methods without modifying their original code.
They allow us to wrap a function inside another function, thereby providing additional functionality before or after the execution of the original function.
Here's a basic example of a decorator:
Python lets us define the nested function. Nested functions are called inner functions.
def your_decorator(func): def wrapper(): print("Something is happening before the function is called.") func() print("Something is happening after the function is called.") return wrapper @your_decorator def say_hello(): print("Hello!") # Calling the decorated function say_hello()
Something is happening before the function is called. Hello! Something is happening after the function is called.
"your_decorator" is a decorator function that takes another function (func) as an argument.
Inside "your_decorator", a nested function wrapper is defined. This function adds some functionality before and after calling the original function.
"say_hello" is decorated by placing "@your_decorator" above its definition. This indicates that "say_hello" should be passed to "your_decorator", and the resulting function should replace "say_hello".
When "say_hello" is called, it's a wrapper that gets executed, which then calls the original "say_hello" function.
def greeting(func): def wrapper(msg): print("Started Execution.") func(msg) print("End Execution") return wrapper @greeting def say_hello(msg): print("Hi!,", msg) # Hi!, Greeting, Client # Hi!, Greet, Employee # Calling the decorated function say_hello("Greeting, Client") greetEmp = say_hello greetEmp("Greet, Employee")
Started Execution. Hi!, Greeting, Client End Execution Started Execution. Hi!, Greet, Employee End Execution
it starts with the `say_hello("Greeting, Client")` function gets invoked with `msg` and @greeting decorator is applied on top of it, so control goes to the `greeting` function with the `say_hello` function as an argument.
The `say_hello` function has one argument named `msg`. The `greeting` function has `say_hello` function as parameter named `func` and `wrapper` function is the inner function of `greeting`.
Then `wrapper` function get invoked and print "Started Execution" and in next line `func(msg)` get invoked and call original function `say_hello` function and print `Hi!, Greeting, Client` and then it will print next line `End Execution.`
After that, we assigned the `say_hello` function to the `greetEmp` function and invoked it with a new `msg`.
Decorators are commonly used for various purposes such as logging, authorization, memoization, and more.
They provide a clean and concise way to extend the behaviour of functions and methods in Python.