Python coding
53 subscribers
24 files
11 links
​A technical hub dedicated to Python programming, web development, and software engineering. Learn core syntax, build full-stack projects, and master backend development.
Download Telegram
Python coding
🐍 Python Tip #89: types.SimpleNamespace Sometimes you have a few related values and want to access them with dot notation instead of dictionary brackets. SimpleNamespace from Python's types module gives you a simple object for storing attributes. --- Importing…
🐍 Python Tip #90: functools.cache()

If a function keeps receiving the same arguments and doing the same expensive calculation again and again, caching can save a lot of work.

Python's functools.cache() automatically remembers previous results and reuses them when the same arguments appear again.

---

Importing cache

from functools import cache

---

Basic Example

from functools import cache

@cache
def square(number):
print("Calculating...")
return number ** 2

print(square(5))
print(square(5))
print(square(10))

Output:

Calculating...
25
25
Calculating...
100

Notice that "Calculating..." only appears once for 5.

The second square(5) gets the stored result instead of running the function again.

---

A More Useful Example

from functools import cache

@cache
def fibonacci(n):
if n < 2:
return n

return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(10))

Output:

55

Without caching, recursive Fibonacci calculations repeat many of the same calculations.

With @cache, previously calculated results are reused.

---

Checking the Cache

You can inspect the cache with:

fibonacci.cache_info()

For example, you might see:

CacheInfo(hits=8, misses=11, maxsize=None, currsize=11)

hits = results retrieved from the cache.

misses = calculations that had to actually run.

currsize = number of stored results.

---

Clearing the Cache

If you want to remove all stored results:

fibonacci.cache_clear()

After that, the function will calculate the results again when called.

---

Important Note

@cache is basically an unlimited cache.

That means stored results can continue growing as new arguments are used.

If you need a limited cache size, functools.lru_cache() is usually more appropriate.

---

Why use cache()?

βœ“ Avoids repeating expensive calculations
βœ“ Extremely useful with recursive functions
βœ“ Simple to add with @cache
βœ“ Can make repeated function calls much faster
βœ“ Part of Python's standard library

---

Challenge:

Create a cached function:

@cache
def factorial(n):

It should calculate:

5! = 120

Then call:

factorial(5)
factorial(5)
factorial(6)

Finally, use:

factorial.cache_info()

and check how many cache hits you get.