Python Decorator: Learn How To Use Decorators In Python

Aayushi Johari
Edureka
Published in
6 min readSep 23, 2019
Python Decorator Tutorial — Edureka

Functions in python give the optimized implementation of running logic of any program, multiple times with hassle-free execution. Decorators in python also revolve around the concept of Python functions. In this article, we will go through the Python Decorators in detail including various examples in this python decorator tutorial. The following topics are discussed in this blog.

  • What Are Functions In Python?
  1. First-Class Object
  2. Inner Functions
  • Decorators In Python
  1. Decorator With Arguments
  2. Returning value
  • Fancy Decorators In Python
  1. Class Decorator
  2. Singleton Class
  3. Nested Decorator

What Are Functions In Python?

Decorators in Python is an advanced topic. So before moving on make sure you are thoroughly clear with the concept of python functions. There are a few prerequisites that one must understand before moving on to decorators in Python.

  • First-Class Objects
  • Inner Functions

First-Class Objects

In python, everything is treated as an object including all the data types, functions too. Therefore, a function is also known as a first-class object and can be passed around as arguments.

Let’s take a look at an example to understand how it works.

def func1(name):
return f"Hello {name}"
def func2(name):
return f"{name}, How you doin?"
def func3(func4):
return func4('Dear learner')

print(func3(func1))
print(func3(func2))

Output:

Hello Dear learner
Dear learner, how you doin?

In the above example, we have used the string interpolation to get the name and passed func1 and func2 as an argument in func3.

Inner Functions

In python, it is possible to define functions inside a function. That function is called an inner function. Here is an example to show how we can use inner functions in python.

def func():
print("first function")
def func1():
print("first child function")
def func2():
print(" second child function")
func1()
func2()
func()

Output:

first function
first child function
second child function

In the above program, it does not matter how the child functions are declared. The output depends on how the child functions are executed. They are locally scoped with the func() so they cannot be called separately.

If you call them separately you will get an error because they are stored as variables inside the func() and can be called only if func() is called.

Returning a function from a function

It is possible to return a function using another function. Take a look at the example below to understand this.

def func(n):
def func1():
return "edureka"
def func2():
return "python"
if n == 1:
return func1
else:
return func2
a = func(1)
b = func(2)
print(a())
print(b())

Output:

edureka
python

Decorators In Python

Decorators in Python are very powerful which modify the behavior of a function without modifying it permanently. It basically wraps another function and since both functions are callable, it returns a callable.

In hindsight, a decorator wraps a function and modifies its behavior. Let us take a look at a simple example to understand how we can work with decorators in python.

def function1(function):
def wrapper():
print("hello")
function()
print("welcome to python edureka")
return wrapper
def function2():
print("Pythonista")
function2 = function1(function2)

function2()

Output:

hello
pythonista
welcome to python edureka

To make things a little easier for the programmers, we have a syntactic sugar with python decorators. Take a look at an example below to understand how it works.

def function1(function):
def wrapper():
print("hello")
function()
print("how are you?")
return wrapper
@function1
def function2():
print("pythonista")

function2()

Output:

hello
pythonista
how are you?

The output will be similar to the program above, the only difference is we have used the pie syntax with the @ symbol.

Using Decorators With Arguments

When you have a function with arguments, it becomes trickier for the decorator function since it also needs arguments in the declaration. To tackle this we can use the *args and **kwargs in the inner wrapper function. Take a look at the following example to understand this.

def function1(function):
def wrapper(*args, **kwargs):
print("hello")
function(*args, **kwargs)
print("welcome to edureka")
return wrapper
@function1
def function2(name):
print(f"{name}")

function2("pythonista")

Output:

hello
pythonista
welcome to edureka

Returning Values From Decorated Functions

Let’s take a look at an example to see how we can return a value from a decorated function.

def function1(function):
def wrapper(*args, **kwargs):
function(*args, **kwargs)
print("it worked")
return wrapper
@function1
def function2(name):
print(f"{name}")

function2("python")

Output:

python
it worked

Make sure to return your wrapper function with arguments to avoid any errors.

Fancy Decorators In Python

Now that we know how decorators work in python, let us explore a rather complex features with the help of a few examples.

Class Decorators

There are two ways to decorate a class in python. The first one is where you can decorate the methods inside a class, there are built-in decorators like @classmethod, @staticmethod and @property in python. @classmethod and @staticmethod define methods inside a class that is not connected to any other instance of a class. @property is normally used to customize the getters and setters of a class attribute. Lets take a look at an example to understand this.

class Square:
def __init__(self, side):
self._side = side
@property
def side(self):
return self._side
@side.setter
def side(self, value):
if value >= 0:
self._side = value
else:
print("error")
@property
def area(self):
return self._side ** 2
@classmethod
def unit_square(cls):
return cls(1)
s = Square(5)
print(s.side)
print(s.area)

Output:

5
25

Another way of decorating the class is by decorating the whole class. Let us take an example to understand this.

from dataclasses import dataclass
@dataclass
class Cards:
rank: str
suit: str

Decorating a class does not reflect on its methods. It is almost similar to writing a decorator of a function, the only difference is the class in the argument instead of a function.

Singleton Class

A singleton class only has one instance. There are plenty of singletons in python including True, None, etc. Let us take a look at an example to understand this better.

import functools

def singleton(cls):
@functools.wraps(cls)
def wrapper(*args, **kwargs):
if not wrapper.instance:
wrapper.instance = cls(*args, **kwargs)
return wrapper.instance
wrapper.instance = None
return wrapper

@singleton
class One:
pass

first = One()
second = One()
print(first is second)

Output:

True

Using ‘is’ only returns true for objects that are the same instance. The above example uses the same approach as any other function decorator. The only difference is we have used cls instead of function. Also, the first and second are the exact same instance.

Nesting Decorators

You can use multiple decorators by stacking them on top of each other. Let us take an example to understand how this works.

@function1
@function2
def function(name):
print(f"{name}")

This is how we can use nested decorators by stacking them onto one another. In the above example, it is only a mere depiction, for it to work you would have to define function1 and function2 with wrapper functions inside each of them.

Arguments In A Decorator

It is always useful to pass arguments in a decorator. Let us consider the following example.

import functools
def repeat(num):
def decorator_repeat(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
for _ in range(num):
value = func(*args, **kwargs)
return value
return wrapper
return decorator_repeat

@repeat(num=4)
def function(name):
print(f"{name}")

function("python")

Output:

python
python
python
python

This brings us to the end of this article where we have learned how we can use Decorator in Python with examples. I hope you are clear with all that has been shared with you in this article.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

1. Machine Learning Classifier in Python

2. Python Scikit-Learn Cheat Sheet

3. Machine Learning Tools

4. Python Libraries For Data Science And Machine Learning

5. Chatbot In Python

6. Python Collections

7. Python Modules

8. Python developer Skills

9. OOPs Interview Questions and Answers

10. Resume For A Python Developer

11. Exploratory Data Analysis In Python

12. Snake Game With Python’s Turtle Module

13. Python Developer Salary

14. Principal Component Analysis

15. Python vs C++

16. Scrapy Tutorial

17. Python SciPy

18. Least Squares Regression Method

19. Jupyter Notebook Cheat Sheet

20. Python Basics

21. Python Pattern Programs

22. Generators in Python

23. Web Scraping With Python

24. Python Spyder IDE

25. Mobile Applications Using Kivy In Python

26. Top 10 Best Books To Learn & Practice Python

27. Robot Framework With Python

28. Snake Game in Python using PyGame

29. Django Interview Questions and Answers

30. Top 10 Python Applications

31. Hash Tables and Hashmaps in Python

32. Python 3.8

33. Support Vector Machine

34. Python Tutorial

Originally published at https://www.edureka.co on September 23, 2019.

--

--

Aayushi Johari
Edureka

A technology enthusiast who likes writing about different technologies including Python, Data Science, Java, etc. and spreading knowledge.