What are the common uses of Python decorators?


In this article, we will learn the common uses of python decorators

What are Python Decorators?

Python decorators are pieces of code that allow existing functions to be added to or updated without changing the underlying function definition. When the program is run, it tries to edit another section of itself, which is known as metaprogramming.

A decorator is a type of function that takes a function and returns another function or takes a class and returns another class. It can be any callable (functions, classes, methods, etc.) and it can return anything; it can also take a method.

Python decorators are simple to use.

A decorator takes in a callable, which is any object that implements the special method __call()__ is said as callable, adds some functionality, and returns a callable.

Example

@somedecorator
def exmple_decorators():
   print("Hello tutorialspoint python decorators")

Writing decorators, on the other hand, require a completely distinct set of skills. And it's not a simple matter; you must fully understand the following −

  • Closures
  • Working with functions as first-class arguments,
  • Variable arguments
  • argument unpacking, and
  • Even some information about how Python loads its source code.

It takes a long time to grasp and perfect all of this. And you've already got a long list of things to learn.

Is it worthwhile to spend your time on this?

The answer is obviously YES. What are the primary advantages of writing decorators? What do they allow you to perform effortlessly and strongly in your daily development?

Let us see!

Analytics, Logging, and Instrumentation

We frequently need to specifically measure what's going on and collect metrics that quantify distinct operations, especially with huge applications. A decorator can solve this requirement extremely readably and simply by encapsulating such notable events in their own function or method.

Validation and Runtime Checks

The type system in Python is strongly typed but dynamic. For all of its advantages, this means that some problems may try to sneak through, which more statically typed languages (such as Java) would detect at compilation time.

Beyond that, you may want to implement more complex, custom checks on data entering and exiting your system. Decorators can help you manage all of this and apply it to multiple functions at the same time.

Creating Frameworks

Once you've learned writing decorators, you'll be able to gain from their simplistic syntax, which allows you to easily add semantics to the language. It's the next best thing to being able to extend Python's syntax.

This is used by many famous open-source frameworks. It is used by the web app framework Flask to route URLs to functions that handle HTTP requests.

Reusing Impossible-to-reuse Code

With an elegant function syntax, functional programming support, and a full-featured object system, Python provides some very powerful tools for encapsulating code into an easily reusable form. However, some patterns of code reuse cannot be captured by these alone.

Consider working with a flakey API. You send queries to something that understands JSON over HTTP, and it works 99.9% of the time. But A small percentage of all requests will result in the server returning an internal error, requiring you to retry the request. In such an instance, you'd add some retry logic.

Example

# Creating a decorator function
def decoratorFunction(demofunction):
	def innerFunc():
		print("Yup...It is a decorated function")
		demofunction()
	return innerFunc()

# Creating a regular ordinary function
def normalFunction():
	print("Yup...It is a normal ordinary function")

decoratedResult = decoratorFunction(normalFunction)
decoratedResult

Output

On execution, the above program will generate the following output −

Yup...It is a decorated function
Yup...It is a normal ordinary function

The decoratorFunction() is a decorator in the preceding example. In brief, a decorator is a wrapper that wraps an object (without altering it) and adds new functionality to the original object. Because this is a popular technique, Python offers a syntax feature (called Decorator) to make it easier. Consider the below as an example −

The below function:

@decorated_func
def ordinary_function():
   print("This is ordinary function")

is equal to

def ordinary_function():
   print("This is ordinary function")
decorated = decorated_func(ordinary_func)

Boosting Your Career

Writing decorators is difficult at first. Neither is it rocket science, but it takes so much effort to learn and understand the details that many developers would never bother. And this works in your favour. Other developers will use your decorators if you become the person on your team who learns to write them properly and writes decorators that answer real-world problems. Decorators are so simple to utilize once the hard work of writing them is over. This can greatly increase the positive impact of the code you develop. And it might even make you a master.

Conclusion

Decorators are an incredible feature that may be used for a wide range of purposes. It is not simply "function or class that takes function or class and returns function or class".

Whatever method you use to learn to build decorators, you may be excited about what you'll be able to achieve with them and how it will, no joke, forever transform the way you write Python code!

Updated on: 15-Dec-2022

264 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements