Python

9 Python Built-In Decorators That Optimize Your Code Significantly

Do more by less: leverage the power of decorators

Yang Zhou
TechToFreedom
Published in
7 min readJan 1, 2023

--

9 Python Built-In Decorators That Optimize Your Code Significantly
Image from Wallhaven

“Simple is better than complex.”

The best Python feature that applies this philosophy from the “zen of Python” is the decorator.

Decorators can help you write less and simpler code to implement complex logic and reuse it everywhere.

More importantly, there are many awesome built-in Python decorators that make our lives much easier, since we can just use one line of code to add complicated functionalities to the existing functions or classes.

Talk is cheap. Let’s see my hand-picked 9 decorators that will show you how elegant Python is.

1. @lru_cache: Speed Up Your Programs by Caching

The simplest way to speed up your Python functions with caching tricks is to use the @lru_cache decorator.

This decorator can be used to cache the results of a function, so that subsequent calls to the function with the same arguments will not be executed again.

It is especially helpful for functions that are computationally expensive or that are called frequently with the same arguments.

--

--