Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does python cache items in the same line and use again later

With this line:

print(sum(tuple), len(tuple), sum(tuple)/len(tuple))

Will python cache sum(tuple) in the 0 index and use it in the average calculation (2 index)?

Or will with calculate sum(tuple) again?

like image 908
Xanthan Avatar asked Jul 16 '26 07:07

Xanthan


1 Answers

Python won't perform this optimization for you. You can see this by defining your own function instead of sum and observing the side effect:

import functools

def my_sum(x):
    print('my sum')
    return functools.reduce(lambda a, b: a + b, x)

tup = (1, 2, 3)
print(my_sum(tup), len(tup), my_sum(tup)/len(tup))

If you run this snippet, you'll see the phrase "my sum" printed twice, proving the call to my_sum isn't optimized out.

Having said that, you could implement this optimization yourself by using functools' cache:

import functools

@functools.cache
def my_sum(x):
    print('my sum')
    return functools.reduce(lambda a, b: a + b, x)

tup = (1, 2, 3)
print(my_sum(tup), len(tup), my_sum(tup)/len(tup))

(or by using the := operator as Andrej Kesely suggests in the comments)

like image 172
Mureinik Avatar answered Jul 18 '26 22:07

Mureinik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!