Python Forum

Full Version: Trouble with global variables
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
In the simple code below, schedule_last_update in the function check_schedule_file() is seen as a local variable and generates an error at line 15 claiming it is referenced before being assigned a value. It is assigned a value before the main() function. Why isn't that viewed as a global variable?
import os
schedule_file = "/home/pi/sprinkler/schedule.json"
schedule_last_update = os.path.getmtime(schedule_file)
schedule_current_update = schedule_last_update
 
def main():
  print(check_schedule_file())
 
def check_schedule_file():
  print("check_schedule_file")
  try:
    schedule_current_update = os.path.getmtime("/home/pi/sprinkler/schedule.json")
  except:
    print("check_schedule_file Error")
  if schedule_current_update != schedule_last_update:
    schedule_last_update = schedule_current_update
    print("schedule changed")
    return True
  return False
 
if __name__=="__main__":
  main()
You can't assign to a global name (expecting it to change globally) unless you include a global declaration at the top of the function. The fact that you have to do this is generally indicative of a design flaw though as global variables are bad (constants fine).