# Python Decorators

In general term, decorators are those who decorates something to make it prettier. Similarly, In python, decorators are those functions which decorates another function.

**Some Information related to python decorators:**

* Decorators takes a function as an argument and returns at another function.
    
* Decorators adds new features and functionalities to the existing function.
    

**Usage** To add an additional feature to the function without touching that actual function.

**Example** Let us consider we have a function **calculate\_area** which takes length and breadth as two parameters.

```plaintext
def calculate_area(length, breadth):
    return length*breadth
```

The above function is an ordinary function which can take negative values as length and breadth in the parameter and can return negative area, which is actually not possible in reality.

```plaintext
area = calculate_area(20,-30)
print("Area is ", area)
```

Output:-

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1662740811723/1QFJSJcHq.png align="left")

Now, for the validation, extra new logic has to be written and implemented into that function. Suppose, you have no permission to modify but also have to add new logic in that function, you have to use decorator.

Using decorator, we can write the function as follows,

```plaintext
def validate(func):   # this is the decorator function.
    def inner(length,breadth):
        if length<0 or breadth<0:
            return "Length and breadth field cannot be negative.\n Please enter the valid data."
        return func(length,breadth)
    return inner


@validate
def calculate_area(length, breadth):    #this is the actual function.
    return f"Area is {length*breadth}"

print(calculate_area(20,-30))
```

Output:-

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1662824647813/5wSIi-uhZU.png align="left")

In the above function, we have written the decorator function that adds the new functionality to that actual function, that simply validates the input from the user and avoids the invalid input.

In gist, we can say decorators in python is the important function that is useful to add the new functionality to another function.
