I have the following situation in Python:
def func_0(x):
'''takes x as a numpy array'''
# connects to a third party software
val_1, val_2 = output_extracted_from_a_third_party_software
return [val_1, val_2]
def func_1(x):
return func_0()[0]
def func_2(x):
return func_0()[1]
another_third_party_func(func_1, func_2) # this is a function that I cannot modify
Facts:
- It is not possible for me to modify func_0 because it just extracts the output of a third party software (a computationally expensive process).
- As a part of an algorithm, I have to pass func_1 and func_2 as 2 separate arguments into another third party library.
I'm looking for a more efficient way to define func_1 and func_2, so that I avoid calling func_0 twice.
Thank you in advance.
EDIT: Memorization doesn't work in this case because x has to be a numpy array.
CodePudding user response:
you can use memoization to solve this ... i think just the builtin LRU cache would work
@functools.lru_cache
def func_0(x):
do something using x
return [val_1, val_2]
of coarse this only works if x
is the same in both calls ...
you can see it work as follows
import functools
@functools.lru_cache
def func_0(x):
print("do something using x")
return [x,x 1]
print(func_0(5)) # see print 'about do something using x'
print(func_0(6)) # see print 'about do something using x'
print(func_0(5)) # DO NOT see print 'about do something using x'
CodePudding user response:
Could you be looking for Tuple unpacking?