Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python functools cache() Function



The Python cache() function specifies the application performance by storing the results determined by the program. Similarly, caching involves storing values computed during function calls for future reuse, this is known as memorization.

We can perform repetitive operations on large datasets. By using caching results, we can minimize the time and cost of executing the calculations repeatedly on the datasets.

Syntax

Following is the syntax for the cache() function.

@functools.cache()

Parameters

The cache() decorator doesn't accept any parameters.

Return Value

This function returns the cached version of the decorated function.

Example 1

In the example below, the factorial function calculates the factorial of a number using cache() function and results the cached value.

import functools
@functools.cache
def fact(x):
    if x == 0:
        return 1
    else:
        return x * fact(x - 1)
print(fact(29))  
print(fact(6)) 

Output

The result is generated as follows −

8841761993739701954543616000000
720

Example 2

We are now using the square function, which calculates the square of a number using the cache() function. If the function is called with the same argument again, it returns the cached result instead of recalculating the program.

import functools
@functools.cache
def fact(x):
    return x * fact(x-1) if x else 1
print(fact(20))
print(fact(20)) #stored result, no need for recalculation 

Output

The code is generated as follows −

2432902008176640000
2432902008176640000

Example 3

Here, we are finding the fibonacci function, which calculates the Fibonacci number for a given input using the cache() function.

import functools
@functools.cache
def fib(x):
    if x <= 1:
        return x
    return fib(x - 1) + fib(x - 2)
print(fib(20))  
print(fib(10)) 

Output

The output is obtained as follows −

6765
55
python_modules.htm
Advertisements