Function decorators in Python
In this post, we will see about function decorators in Python.
What is a function decorator?
- A decorator is a function that takes a function as an argument and returns a function.
- These are useful to wrap the functionality with the same code.
Consider the below code,
def add_outer (str):
def add_inside ():
return "Hello"
return add_inside() + str
def add(name):
return name
print(add_outer(add(" Mani")))
This will output,
Hello Mani
Now if we use decorator we can simply do it as,
def add_outer (fun):
def add_inside (name):
return "Hello" + fun(name)
return add_inside
@add_outer
def add(name):
return name
print(add(" Mani"))