The Single Most Useful Decorator in Python

preview_player
Показать описание
The most useful decorator in Python is @cache.

It's from the functools library (and a similar variant called @lru_cache too). This decorator was introduced in Python 3.9, but lru_cache has been available since 3.2. Often times, the cache decorator can be used to automatically do dynamic programming algorithms.

SUPPORT ME ⭐
---------------------------------------------------

BE ACTIVE IN MY COMMUNITY 😄
---------------------------------------------------
Рекомендации по теме
Комментарии
Автор

You're telling me I've been manually coding caches unnecessarily? That's what you get by relying on your decade old knowledge of C in Python.

GuilhermeFArantesSouza
Автор

There is one BIG WARNING: Use this only on pure functions (without side effects)!

@cache does not run the function but only returns its value so if you for example write to a file in that function, the file write will not happen if the cache is evoked.

Автор

I did not know python had automatic memoization. Thank you for this knowledge.

TheZethera
Автор

Another very useful related decorator is "cached_property", which lets you compute a property just once when needed, and remember it as long as the object exists.

Soul-Burn
Автор

If anyone was wondering; if you'd like to invalidate the cache you could do (for this example) `fib.cache_clear()`.

evanchong
Автор

I'm amazed, when I saw this my first thought was THERE'S NO WAY. Such a big improvement with so little effort is rare to see! Thanks a lot for sharing!

StarNova
Автор

It's rare that video whose title contains a superlative actually lives up to the expectations. Great job!

phillec
Автор

Wanted to add that if your function returns a mutable object (eg list) and you then modify that value, you are modifying the return value of the cache, making all future calls return the modified object. You need to make a copy of the object before using it (or do not modify it in the first place).

asad-ullahkhan
Автор

This is in fact an incredible tip!
4 minutes of video, direct to the point and a life saver =)

FallinPython
Автор

Audio tip for the future: Boost the high frequencies (+18 dB) with a high shelf at starting around >3 kHz, or low Q (0.5) bell at 7.5 kHz to make your voice a lot more clear. Big difference. You can probably do this in any video editing software.

PS: loved this vid

jonasls
Автор

Built-in memoization, that's so cool! Thanks for sharing!

Caspitein
Автор

I literally jumped from my chair when I saw how fast cache made the function.

Thank you for sharing such a useful knowledge.

maheenmashrur
Автор

I can't believe I manually coded a cache just a few weeks back when this was a thing in python the whole time.

normalmighty
Автор

I knew from the thumbnail of this video (seeing the fib function), that you were going to go over the cache decorator. It is also my favorite decorator! Although, I never really get to use it in production code, as I mostly use it with recursive functions and we try to avoid recursion in our codebase.

josephlyons
Автор

This video is going to blow up. It is super useful, time-saving, short and "yt algo friendly".

ElSenorEls
Автор

I would just like to say that I discovered this channel a couple of days ago.

Your videos are incredibly helpful... thank you for the uploads, you have a new subscriber (and I will be binge watching your videos this weekend).

fakename
Автор

I find it so interesting how we approach coding differently. Whilst I've used the @cache decorator, this isn't somewhere I've ever thought to use it. My immediate thought would have been to create a generator function. Now that I think about it, though, this is much more concise. If you wrote this as a generator then each time you computed fib(n-1) you would have to store it in some variable ( for the sake of providing a concrete example, call that variable "last_fib" and assume that it is only declared within the scope of the generator function). Then the next time the generator is called, it substitutes "last_fib" for fib(n-2) ... This is much simpler.

SorFig
Автор

I can see someone using this cache decorator in a real product, forgetting that it does not evict cached items from memory, then they start running out of memory and wondering why.
You are better off using lru_cache with a size limit and only do it if your function is actually called with values that can be reused in the next calls to the function

chigozie
Автор

Note: the act of equating a function's output with its input arguments is called memoization. It of course depends on the function being pure (always returning the same result for the same arguments), which is why in languages where functions are pure by default it's often done by default without any need for decorators etc. It's one of the optimization techniques that make functional languages much more performant than they may at first seem.

DeuxisWasTaken
Автор

Okay, the cache thing was known to me and is just a time vs memory tradeoff, but the LRU cache is fucking genius

BosonCollider