![]() |
Trouble with global variables - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Trouble with global variables (/thread-9244.html) |
Trouble with global variables - maymac789 - Mar-29-2018 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() RE: Trouble with global variables - Mekire - Mar-29-2018 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).
|