Data Science and Machine Learning Internship ...
- 22k Enrolled Learners
- Weekend/Weekday
- Live Class
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.
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
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.
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 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.
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
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.
Now that we know how decorators work in python, let us explore a rather complex features with the help of a few examples.
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.
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.
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.
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 Python Decorator Tutorial
If you found this article on “Python Decorator Tutorial” relevant, check out the Edureka Python Certification Training, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe.
We are here to help you with every step on your journey and come up with a curriculum that is designed for students and professionals who want to be a Python developer. The course is designed to give you a head start into Python programming and train you for both core and advanced Python concepts along with various Python frameworks like Django.
If you come across any questions, feel free to ask all your questions in the comments section of “Python Decorator Tutorial” and our team will be glad to answer.
Course Name | Date | Details |
---|---|---|
Python Programming Certification Course | Class Starts on 30th November,2024 30th November SAT&SUN (Weekend Batch) | View Details |
Python Programming Certification Course | Class Starts on 28th December,2024 28th December SAT&SUN (Weekend Batch) | View Details |
edureka.co