Watch ICC World Cup 2023 Live Watch Now! Subscribe!

Decorators in Python will make your code so much better

Decorators in Python will make your code so much better, With just a @ symbol, you can analyze, test, and reuse your code. Python's readability is on
Please wait 0 seconds...
Scroll Down and click on Go to Link for destination
Congrats! Link is Generated

 With just a @ symbol, you can analyze, test, and reuse your code.

Python's readability is one of the factors that contribute to its enormous success. Everything else is dependent on it: illegible code is difficult to maintain. It's also not beginner-friendly, as a newbie befuddled by illegible code is unlikely to attempt writing their own.

Before decorators, Python was already a legible and beginner-friendly language. However, as the language became more widely used, Python developers felt compelled to add more features without cluttering the landscape or making code incomprehensible.

Decorators are a great example of a well-thought-out feature. It takes some time to get your head around, but it's well worth it. You'll note how they don't overcomplicate things and make your code sleek and snazzy as you use them.

Decorators in Python will make your code so much better
Decorators in Python will make your code so much better


First and foremost, higher-order functions.

Decorators, in a nutshell, are a convenient technique to manage higher-order functions. Let's have a look at those first!

Returning functions from functions

Let's say you only have one function, greet(), which welcomes whatever object you feed it. Let's imagine you have another method called Simon() that inserts "Simon" wherever it's needed. What is the best way to mix the two? Consider it for a moment before proceeding to the next section.

python

'Hello, Simon!' is the output. I hope that makes sense.

Of course, we could have just said hello ("Simon"). However, the point is that we might want to use "Simon" for a variety of purposes. And if we don't use "Simon" and instead use something more involved, we can save a lot of lines of code by putting it all into a function like Simon ().

Functions contained within other functions

Functions can also be defined inside other functions. That's crucial since decorators will do the same thing! It looks like this without the help of decorators:

python

Respect("yes") returns the congrats function, while respect("brother") (or some other input instead of "brother") returns the insult function. Enter respect("yes")() and respect("brother")() as standard functions to call the functions.

Is that clear? Then you're ready to go for the decorators!

Python decorators in alphabetical order

@ symbols are used in functions.

Let's see what happens if we combine the two prior ideas: a function that defines a function by taking another function. Isn't it mind-boggling? Consider the following:

python

The final line assures that startstop(roll)() is no longer required; roll() will suffice. Do you know what that call's result is? If you're not sure, give it a shot!

We could now paste this directly after startstop() as a very excellent alternative:

This accomplishes the same thing, but in the start it binds roll() to startstop().

increased adaptability

What is the benefit of that? Isn't that the same number of lines of code as before?

Yes, in this circumstance. However, once you're dealing with a little more difficult material, it becomes quite beneficial. For the first time, you can separate all decorators (such as the def startstop() section above) into their own module. That is, you save them in a file called decorators.py and include them in your main program as follows:

python

You can accomplish it without using decorators in theory. However, it simplifies your life because you won't have to deal with nested functions or infinite bracket-counting this way.


Decorators can also be nested:

We haven't yet defined exectime(), but we will do so in the next section. It's a Python function that calculates the length of a process.

A line like this would be comparable to this nesting:

The bracket counting has begun! Consider having five or six of those functions nested inside one another. Isn't the decorator notation much more readable than this layered jumble?

Decorators can even be used on functions that take arguments. Imagine a few more disputes in the line above, and you've got full mayhem. It's neat and tidy thanks to the decorators.

Finally, you can provide your decorators arguments, such as @mydecorator (argument). Yes, you can accomplish it all without the help of decorators. But, when you re-read it in three weeks, I hope you a lot of fun deciphering your decorator-free code...


Decorators cut the cream in a variety of ways.

Let's look at some classic cases when decorators are practically needed now that I've hopefully persuaded you that decorators make your life three times easier.

Calculating the length of time it takes to complete a task

Let's imagine we have a waste time() function and want to know how long it takes. Simply hire a decorator!

We're done with a dozen lines of code! Furthermore, measuretime() can be used on as many functions as you wish.


Slowing down the code

Sometimes you don't want to run code right away, but rather wait a while. That's where a decorator who works slowly comes in handy:

You can take a 5-minute break after calling awaken(), after which your console will remind you to go back to work.

Debugging and testing

Let's say you have a bunch of different functions that you call at various stages and you're losing track of what's being called when. You may improve clarity by using a simple decorator for each function definition. As follows:

A more sophisticated example can be found here. However, you must first learn how to decorate functions with parameters in order to comprehend that example. Nonetheless, it's really worth reading!

Using the same code

This should be self-evident. You can use @decorator anywhere in your code if you've specified the decorator() method. To tell you the truth, I don't believe it gets any easier than that!

Taking care of logins

Decorators can also be used to restrict access to features that should only be available to logged-in users. For reference, I'll refer you to the whole example, but the concept is simple: first, you write a function like login required (). @login required is added before any function definition that requires logging in. I'd say it's simple enough.

Python's sweetness is due to syntactic sugar.

It's not that I'm not critical of Python or that I don't use other languages when necessary. But Python has a significant draw: it's simple to understand, even if you're not a computer scientist by training and just want to get things done.

Python is a pineapple, if C++ is an orange: it's just as nutritious as an orange but three times sweeter. Decorators are only one part of the equation.

But I think you can see why it's such a significant selling point. Syntactic sugar to make your life more enjoyable! Except for having your eyes hooked to a screen, there are no health dangers.


About the Author

Tech Blogger.

Post a Comment

Enter Your Comment Below!
Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.