I want to keep track of the current max of a calculated cosine similarity score. However, I keep getting the error UnboundLocalError: cannot access local variable 'current_max_cosine_similarity_score' where it is not associated with a value
In Javascript, I can typically do this without a problem using the let
keyword when working with a variable outside of a function scope. However, in Python that doesn't seem to be the case.
What would be the pythonic way of going about this?
current_max_cosine_similarity_score = -math.inf
def func(acc, v):
calculated_cosine_similarity_score = ...
if calculated_cosine_similarity_score > current_max_cosine_similarity_score:
current_max_cosine_similarity_score = max([current_max_cosine_similarity_score, calculated_cosine_similarity_score])
acc['cosineSimilarityScore'] = calculated_cosine_similarity_score
return acc
print(reduce(func, [...], {}))
CodePudding user response:
You have to declare current_max_cosine_similarity_score
as global
(or nonlocal
) in func()
.
But that's nevertheless a bad idea. The "pythonic" way would be to use a generator, closure or a class with a get_current_maximum()
.
Probably the most "pythonic" closure solves your problem:
from functools import reduce
def calc_closure():
def _calc(value, element):
# do calculations on element here
if element > value:
_calc.current_max_value = element
return _calc.current_max_value
# using an attribute makes current_max_value accessible from outer
_calc.current_max_value = -np.math.inf
return _calc
closure_1 = calc_closure()
closure_2 = calc_closure()
print(reduce(closure_1, [1, 2, 3, 4, 1]))
print(closure_1.current_max_value )
print(closure_2.current_max_value )
Output:
4
4
-inf