Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 Trouble with global variables
#1
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()
Quote
#2
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).
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Please help me understand how to use global variables joew 6 239 Jan-05-2020, 06:03 PM
Last Post: joew
  Global Variables - Some Points Needing Clarification. adt 4 261 Nov-30-2019, 01:23 PM
Last Post: adt
  modifying variables in local or global space Skaperen 2 210 Aug-14-2019, 07:13 AM
Last Post: Skaperen
  Global variable does not seem to be global. Columbo 6 457 Jul-15-2019, 11:00 PM
Last Post: Columbo
  Global variables not changing ThemePark 3 466 Mar-02-2019, 11:24 AM
Last Post: Larz60+
  help with threading module and passing global variables ricardons 1 1,094 Feb-21-2019, 12:48 PM
Last Post: stullis
  Use of global variables from several modules. Jstechg 3 552 Jan-03-2019, 03:39 AM
Last Post: scidam
  Resetting Global Variables? WuchaDoin 11 1,273 Sep-28-2018, 08:41 PM
Last Post: WuchaDoin
  Is This Code Ok? How Can I Avoid Using Global Variables? digitalmatic7 9 1,691 Feb-15-2018, 09:32 AM
Last Post: DeaD_EyE
  [split] Problem using global variables RedSkeleton007 1 874 Nov-10-2017, 09:13 PM
Last Post: sparkz_alot

Forum Jump:


Users browsing this thread: 1 Guest(s)