Sitemap
Rai Mohit Samshersingh

Rai Mohit Samshersingh

Decorators in Python

2 min readJun 28, 2022

Decorators are interesting feature of the Python, it allows to add extra functionality to an existing code.

Decorators are used to change the behavior of a function or a class by wrapping another function.

Syntax:

@decorator
def ordinary_func():
methods

Let’s understand decorators with the help of examples.

  1. Function as an object.
def convert(text):
return text.upper()
obj = convertprint(obj('hello'))Output:
HELLO

In the above example, function convert is assigned to a variable. It will create an object by name obj.

2 . Passing the function as an argument

def convert_upper(text):
return text.upper()
def convert_lower(text):
return text.lower()
def greet(func):
greeting = func("""Hi, Greeting from a function passed as an argument.""")
print (greeting)
greet(convert_upper)
greet(convert_lower)
Output:
HI, GREETING FROM A FUNCTION PASSED AS AN ARGUMENT.
hi, greeting from a function passed as an argument.

Here the function convert_upper(text) and convert_lower(text) is passed as an argument in function greet().

Get Rai Mohit Samshersingh’s stories in your inbox

Join Medium for free to get updates from this writer.

3. A function can return another function

def multiplier(x):
def multiply(y):
return x*y
return multiplymultiply_5 = multiplier(5)print(multiply_5(10))Output:
50

In the above example, we have created a function inside of another function and then have returned the function created inside.

Decorator function Example:

def decorator_func(func):
def inner(num):
print("num1 =", num)
print("result:", end='\t')
func(num)
return inner


@decorator_func
def square(num1):
print(num1**2)


@decorator_func
def cube(num1):
print(num1**3)

square(5)
cube(5)

OUTPUT:

num1 = 5
result: 25
num1 = 5
result: 125
num1 = 12345
result: 15

In above example, decorator_func(func) is an decorator function which is adding extra functionality in functions square(num1) and cube(num1).

Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.

--

--