2

I'm trying to run an optimization step and I want to update a global variable from within a function. I'm using an optimization script and I want to save the data when there are any updates but I cannot update the global variable from within a function.

Is there a way to update a global variable from within a function call? I am making sure not to run the optimization step in parallel so this technically should be ok.

global current_minimum
current_minimum = 0

def update():
    current_minimum = -0.1

_ = update()
print(current_minimum)
# 0
O.rka
  • 29,847
  • 68
  • 194
  • 309
  • 1
    `global` goes inside the function, not at top level. (`global` at top level really ought to be a syntax error.) – user2357112 May 29 '18 at 20:49

1 Answers1

3

You need to put global current_minimum within the function where you are updating said variable. Otherwise the function thinks current_minimum is a local variable.

J. Owens
  • 832
  • 7
  • 9