avatarAayushi Johari

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

7732

Abstract

with python decorators. Take a look at an example below to understand how it works.</p><div id="01ab"><pre>def function1(<span class="hljs-keyword">function</span>): def <span class="hljs-keyword">wrapper</span>(): print("hello") <span class="hljs-keyword">function</span>() print("how are you?") <span class="hljs-keyword">return</span> <span class="hljs-keyword">wrapper</span> @function1 def function2(): print("pythonista")

function2()</pre></div><h2 id="46d7">Output:</h2><div id="aa47"><pre>hello pythonista how <span class="hljs-keyword">are</span> you?</pre></div><p id="90d5">The output will be similar to the program above, the only difference is we have used the pie syntax with the @ symbol.</p><h1 id="896e">Using Decorators With Arguments</h1><p id="cd4a">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.</p><div id="359e"><pre>def function1(<span class="hljs-keyword">function</span>): def <span class="hljs-keyword">wrapper</span>(*args, **kwargs): print("hello") <span class="hljs-keyword">function</span>(*args, **kwargs) print("welcome to edureka") <span class="hljs-keyword">return</span> <span class="hljs-keyword">wrapper</span> @function1 def function2(<span class="hljs-type">name</span>): print(f"{name}")

function2("pythonista")</pre></div><h2 id="24f3">Output:</h2><div id="5f88"><pre>hello pythonista welcome <span class="hljs-keyword">to</span> edureka</pre></div><h2 id="99cd">Returning Values From Decorated Functions</h2><p id="fedb">Let’s take a look at an example to see how we can return a value from a decorated function.</p><div id="b0db"><pre>def function1(<span class="hljs-keyword">function</span>): def <span class="hljs-keyword">wrapper</span>(*args, **kwargs): <span class="hljs-keyword">function</span>(*args, **kwargs) print("it worked") <span class="hljs-keyword">return</span> <span class="hljs-keyword">wrapper</span> @function1 def function2(<span class="hljs-type">name</span>): print(f"{name}")

function2("python")</pre></div><h2 id="9b16">Output:</h2><div id="0685"><pre>python <span class="hljs-keyword">it</span> worked</pre></div><p id="0de9">Make sure to return your wrapper function with arguments to avoid any errors.</p><h1 id="17e1">Fancy Decorators In Python</h1><p id="a154">Now that we know how decorators work in python, let us explore a rather complex features with the help of a few examples.</p><h2 id="1aa7">Class Decorators</h2><p id="4205">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.</p><div id="c41b"><pre><span class="hljs-keyword">class</span> <span class="hljs-title class_">Square</span>: <span class="hljs-keyword">def</span> <span class="hljs-title function_">init</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, side</span>): <span class="hljs-variable language_">self</span>._side = side <span class="hljs-variable">@property</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">side</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>): <span class="hljs-keyword">return</span> <span class="hljs-variable language_">self</span>._side <span class="hljs-variable">@side</span>.setter <span class="hljs-keyword">def</span> <span class="hljs-title function_">side</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span>, value</span>): <span class="hljs-keyword">if</span> value >= <span class="hljs-number">0</span>: <span class="hljs-variable language_">self</span>._side = value <span class="hljs-symbol">else:</span> print(<span class="hljs-string">"error"</span>) <span class="hljs-variable">@property</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">area</span>(<span class="hljs-params"><span class="hljs-variable language_">self</span></span>): <span class="hljs-keyword">return</span> <span class="hljs-variable language_">self</span>._side ** <span class="hljs-number">2</span> <span class="hljs-variable">@classmethod</span> <span class="hljs-keyword">def</span> <span class="hljs-title function_">unit_square</span>(<span class="hljs-params">cls</span>): <span class="hljs-keyword">return</span> cls(<span class="hljs-number">1</span>) s = <span class="hljs-title class_">Square</span>(<span class="hljs-number">5</span>) print(s.side) print(s.area)</pre></div><h2 id="3956">Output:</h2><div id="6721"><pre>5 25</pre></div><p id="284c">Another way of decorating the class is by decorating the whole class. Let us take an example to understand this.</p><div id="9930"><pre><span class="hljs-keyword">from</span> dataclasses <span class="hljs-keyword">import</span> dataclass @dataclass <span class="hljs-keyword">class</span> <span class="hljs-symbol">Cards: <span class="hljs-symbol">rank</span>: <span class="hljs-symbol">str</span></span> <span class="hljs-symbol">suit: <span class="hljs-symbol">str</span></span></pre></div><p id="6f88">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.</p><h2 id="7606">Singleton Class</h2><p id="b833">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.</p><div id="bb31"><pre><span class="hljs-keyword">import</span> functools

def singleton(cls): @functools.wraps(cls) def wrapper(*args, **kwargs): <span class="hljs-keyword">if</span> <span class="hljs-keyword">not</span> wrapper.instance: wrapper.instance = cls(*args, **kwargs) <span class="hljs-keyword">return</span> wrapper.instance wrapper.instance = None <span class="hljs-keyword">return</span> wrapper

@singleton <span class="hljs-keyword">class</span> <span class="hljs-symbol">One: <span class="hljs-symbol">pass</span></span>

<span class="hljs-symbol">first</span> = <span class="hljs-symbol">One</span>() <span class="hljs-symbol">second</span> = <span class="hljs-symbol">One</span>() <span class="hljs-symbol">print</span>(<span class="hljs-symbol">first</span> <span class="hljs-symbol">is</span> <span class="hljs-symbol">second</span>)</pre></div><h2 id="a0f3">Output:</h2><div id="d6c3"><pre><span class="hljs-literal">True</span></pre></div><p id="9f31">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.</p><h2 id="6302">Nesting Decorators</h2><p id="5256">You can use multiple decorators by stacking them on top of e

Options

ach other. Let us take an example to understand how this works.</p><div id="ed91"><pre><span class="hljs-variable">@function1</span> <span class="hljs-variable">@function2</span> def <span class="hljs-built_in">function</span>(name): <span class="hljs-built_in">print</span>(f<span class="hljs-string">"{name}"</span>)</pre></div><p id="3ce8">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.</p><h2 id="5ff6">Arguments In A Decorator</h2><p id="930b">It is always useful to pass arguments in a decorator. Let us consider the following example.</p><div id="a779"><pre><span class="hljs-keyword">import</span> functools def repeat(num): def decorator_repeat(func): @functools.wraps(func) def <span class="hljs-keyword">wrapper</span>(*args, **kwargs): <span class="hljs-keyword">for</span> _ <span class="hljs-keyword">in</span> range(num): <span class="hljs-keyword">value</span> = func(*args, **kwargs) <span class="hljs-keyword">return</span> <span class="hljs-keyword">value</span> <span class="hljs-keyword">return</span> <span class="hljs-keyword">wrapper</span> <span class="hljs-keyword">return</span> decorator_repeat

@repeat(num=<span class="hljs-number">4</span>) def <span class="hljs-keyword">function</span>(<span class="hljs-type">name</span>): print(f"{name}")

<span class="hljs-keyword">function</span>("python")</pre></div><h2 id="3b41">Output:</h2><div id="f1a6"><pre><span class="hljs-keyword">python</span> <span class="hljs-keyword">python</span> <span class="hljs-keyword">python</span> <span class="hljs-keyword">python</span></pre></div><p id="6f32">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.</p><p id="920f">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 <a href="https://www.edureka.co/blog/?utm_source=medium&amp;utm_medium=content-link&amp;utm_campaign=python-decorator-tutorial">Edureka’s official site.</a></p><p id="ad40">Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.</p><blockquote id="f61a"><p>1. <a href="https://readmedium.com/machine-learning-classifier-c02fbd8400c9">Machine Learning Classifier in Python</a></p></blockquote><blockquote id="aeec"><p>2. <a href="https://readmedium.com/python-scikit-learn-cheat-sheet-9786382be9f5">Python Scikit-Learn Cheat Sheet</a></p></blockquote><blockquote id="4f96"><p>3. <a href="https://readmedium.com/python-libraries-for-data-science-and-machine-learning-1c502744f277">Machine Learning Tools</a></p></blockquote><blockquote id="70d0"><p>4. <a href="https://readmedium.com/python-libraries-for-data-science-and-machine-learning-1c502744f277">Python Libraries For Data Science And Machine Learning</a></p></blockquote><blockquote id="df91"><p>5. <a href="https://readmedium.com/how-to-make-a-chatbot-in-python-b68fd390b219">Chatbot In Python</a></p></blockquote><blockquote id="2f07"><p>6. <a href="https://readmedium.com/collections-in-python-d0bc0ed8d938">Python Collections</a></p></blockquote><blockquote id="bec4"><p>7. <a href="https://readmedium.com/python-modules-abb0145a5963">Python Modules</a></p></blockquote><blockquote id="e4cf"><p>8. <a href="https://readmedium.com/python-developer-skills-371583a69be1">Python developer Skills</a></p></blockquote><blockquote id="c733"><p>9. <a href="https://readmedium.com/oops-interview-questions-621fc922cdf4">OOPs Interview Questions and Answers</a></p></blockquote><blockquote id="cd6f"><p>10. <a href="https://readmedium.com/python-developer-resume-ded7799b4389">Resume For A Python Developer</a></p></blockquote><blockquote id="eb77"><p>11. <a href="https://readmedium.com/exploratory-data-analysis-in-python-3ee69362a46e">Exploratory Data Analysis In Python</a></p></blockquote><blockquote id="be4d"><p>12. <a href="https://readmedium.com/python-turtle-module-361816449390">Snake Game With Python’s Turtle Module</a></p></blockquote><blockquote id="58f4"><p>13. <a href="https://readmedium.com/python-developer-salary-ba2eff6a502e">Python Developer Salary</a></p></blockquote><blockquote id="e4e2"><p>14.<a href="https://readmedium.com/principal-component-analysis-69d7a4babc96"> Principal Component Analysis</a></p></blockquote><blockquote id="cbe1"><p>15. <a href="https://readmedium.com/python-vs-cpp-c3ffbea01eec">Python vs C++</a></p></blockquote><blockquote id="bcf0"><p>16. <a href="https://readmedium.com/scrapy-tutorial-5584517658fb">Scrapy Tutorial</a></p></blockquote><blockquote id="8506"><p>17. <a href="https://readmedium.com/scipy-tutorial-38723361ba4b">Python SciPy</a></p></blockquote><blockquote id="ebe8"><p>18. <a href="https://readmedium.com/least-square-regression-40b59cca8ea7">Least Squares Regression Method</a></p></blockquote><blockquote id="0679"><p>19. <a href="https://readmedium.com/jupyter-notebook-cheat-sheet-88f60d1aca7">Jupyter Notebook Cheat Sheet</a></p></blockquote><blockquote id="7972"><p>20. <a href="https://readmedium.com/python-basics-f371d7fc0054">Python Basics</a></p></blockquote><blockquote id="1296"><p>21. <a href="https://readmedium.com/python-pattern-programs-75e1e764a42f">Python Pattern Programs</a></p></blockquote><blockquote id="0bbb"><p>22. <a href="https://readmedium.com/generators-in-python-258f21e3d3ff">Generators in Python</a></p></blockquote><blockquote id="d49b"><p>23. <a href="https://readmedium.com/web-scraping-with-python-d9e6506007bf">Web Scraping With Python</a></p></blockquote><blockquote id="3e77"><p>24.<a href="https://readmedium.com/spyder-ide-2a91caac4e46"> Python Spyder IDE</a></p></blockquote><blockquote id="2ade"><p>25. <a href="https://readmedium.com/kivy-tutorial-9a0f02fe53f5">Mobile Applications Using Kivy In Python</a></p></blockquote><blockquote id="6893"><p>26. <a href="https://readmedium.com/best-books-for-python-11137561beb7">Top 10 Best Books To Learn & Practice Python</a></p></blockquote><blockquote id="41f0"><p>27. <a href="https://readmedium.com/robot-framework-tutorial-f8a75ab23cfd">Robot Framework With Python</a></p></blockquote><blockquote id="32ec"><p>28. <a href="https://readmedium.com/snake-game-with-pygame-497f1683eeaa">Snake Game in Python using PyGame</a></p></blockquote><blockquote id="6b43"><p>29. <a href="https://readmedium.com/django-interview-questions-a4df7bfeb7e8">Django Interview Questions and Answers</a></p></blockquote><blockquote id="20ea"><p>30. <a href="https://readmedium.com/python-applications-18b780d64f3b">Top 10 Python Applications</a></p></blockquote><blockquote id="1f20"><p>31. <a href="https://readmedium.com/hash-tables-and-hashmaps-in-python-3bd7fc1b00b4">Hash Tables and Hashmaps in Python</a></p></blockquote><blockquote id="c2fd"><p>32. <a href="https://readmedium.com/whats-new-python-3-8-7d52cda747b">Python 3.8</a></p></blockquote><blockquote id="d542"><p>33. <a href="https://readmedium.com/support-vector-machine-in-python-539dca55c26a">Support Vector Machine</a></p></blockquote><blockquote id="3e18"><p>34. <a href="https://readmedium.com/python-tutorial-be1b3d015745">Python Tutorial</a></p></blockquote><p id="80c5"><i>Originally published at <a href="https://www.edureka.co/blog/python-decorator-tutorial/">https://www.edureka.co</a> on September 23, 2019.</i></p></article></body>

Python Decorator: Learn How To Use Decorators In Python

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.

Python
Python Decorators
Python Development
Python Developers
Python Programming
Recommended from ReadMedium