Decorator in Python

How To Simplifying Your Code And Boost Your Function — #PurePythonSeries — Episode #08

J3
Jungletronics
3 min readDec 21, 2021

--

See this scenario:

Let´s simulate some method to simplifing your task, and brings the point home: Decorator!

Image from this link

Suppose you have this legacy code:

This function is desperately in need of an upgrade. Let´s suppose it needs some code before and after its actual output.

There is no reimplementation options. The system must not stop.

This code must always run even after your implementation:

Here comes the Python’s decorator patterns to rescue us:

Now, 🎉 Feel The Magic ✨

There you have it!

Wait…Let’s make in the pythonic way (it reads: code that is readable and beautiful)!

Decorate your methods like this:

Now type:

This code is Beautful, isn’t it?

Decorators can be extremely useful as they allow the extension of an existing function, without any modification to the original function source code.

That’s all, folks!

See you soon o/

Bye!

👉Jupiter notebook link :)

👉git

👉replit

Credits And References

Jose Portilla Python for Data Science and Machine Learning Bootcamp — Learn how to use NumPy, Pandas, Seaborn, Matplotlib, Plotly, Scikit-Learn, Machine Learning, Tensorflow, and more!

Python Decorators I: Introduction to Python Decorators by Bruce Eckel

Python Decorators II: Decorator Arguments by Bruce Eckel

Related Posts

00#Episode#PurePythonSeries — Lambda in Python — Python Lambda Desmistification

01#Episode#PurePythonSeries — Send Email in Python — Using Jupyter Notebook — How To Send Gmail In Python

02#Episode#PurePythonSeries — Automate Your Email With Python & Outlook — How To Create An Email Trigger System in Python

03#Episode#PurePythonSeries — Manipulating Files With Python — Manage Your Lovely Photos With Python!

04#Episode#PurePythonSeries — Pandas DataFrame Advanced — A Complete Notebook Review

05#Episode#PurePythonSeries — Is This Leap Year? Python Calendar — How To Calculate If The Year Is Leap Year and How Many Days Are In The Month

06#Episode#PurePythonSeries — List Comprehension In Python — Locked-in Secrets About List Comprehension

07#Episode#PurePythonSeries — Graphs — In Python — Extremely Simple Algorithms in Python

08#Episode#PurePythonSeries — Decorator in Python — How To Simplifying Your Code And Boost Your Function (this one)

edited: Nov, 2022 — add replit link ;)

--

--

J3
Jungletronics

😎 Gilberto Oliveira Jr | 🖥️ Computer Engineer | 🐍 Python | 🧩 C | 💎 Rails | 🤖 AI & IoT | ✍️