Bashir Abdelwahed
Bashir Abdelwahed

Reputation: 512

Optimize redundant calculations inside a function in Python

Is there a way to perform a block of code only once inside a function (say when you define it) and then every time you call the function the interpreter simply ignores it and uses the results directly?

for example:

import time as t
def foo():
    ### redundant code execution
    t0 = t.time()
    arr = ('Apples ' * 10000000).split()
    print(t.time() - t0)
    ###

    print(arr[0])

This would be a great feature since the variable is only used inside the function and I don't want it to be accessible from the outside.

Thanks,

Upvotes: 0

Views: 83

Answers (2)

Diptangsu Goswami
Diptangsu Goswami

Reputation: 5965

Yes. It can be done using something known as a closure.

def foo():
    result = None
    def inner():
        nonlocal result
        if result is None:
            result = ...  # do your calculation here
        
        return result
    return inner
foo = foo()

A few more points based on the code in the question.

  • time.perf_counter is a bit more accurate than time.time
  • ('Apples ' * 10000000).split() is the same as ['Apples'] * 10000000

Upvotes: 1

0neir0s
0neir0s

Reputation: 46

Here, one idea would be to memoize it. Essentially, if a function is pure ( always gives the same output for a set of inputs ), you can save a mapping of input to output, the first time you compute it.

For this, you can implement your own memoizer like the below example from Geeks 4 Geeks. Original link: https://www.geeksforgeeks.org/memoization-using-decorators-in-python/

def memoize_factorial(f): 
    memory = {} 
  
    # This inner function has access to memory 
    # and 'f' 
    def inner(num): 
        if num not in memory:          
            memory[num] = f(num) 
        return memory[num] 
  
    return inner 
      
@memoize_factorial
def facto(num): 
    if num == 1: 
        return 1
    else: 
        return num * facto(num-1) 
  
print(facto(5)) 

Or you can use existing decorator libraries like the one in the link below.

https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize

Upvotes: 1

Related Questions