0

Sleep without sleep

python3 --version
Python 3.7.3
import time
    
last_millis = 0
time_period = 1000 # 1 = 1 millsec , 1000 = 1 sec

def do_somthing():
  print(last_millis)

while True:
  this_millis = int(time.time()*1000.0) # nanosec to millsec

  if this_millis - last_millis >= time_period:
    last_millis = this_millis
    do_somthing()

prints every 1 second as expected


1648794877918
1648794878918
1648794879918
1648794880918
...

Changing while True: to a so-called function def no_sleep():

import time

    
last_millis = 0
time_period = 1000 # 1 = 1 millsec , 1000 = 1 sec


def do_somthing():
  print(last_millis)

    
def no_sleep():
  this_millis = int(time.time()*1000.0) # nanosec to millsec

  if this_millis - last_millis >= time_period:
    last_millis = this_millis    
    do_somthing()

while True:
  do_somthing()
  

results in error

UnboundLocalError: local variable 'last_millis' referenced before assignment

Any help on why this might be happening?

1 Answer 1

1

Your function treats last_millis as a local variable, because last_millis is redefined in no_sleep().

Try adding:

global last_millis

as the first line of function no_sleep and see what happens.

2
  • The solution to the script was not required. my gist is one way to solve it. The understanding why, as you say."Your function treats last_millis as a local variable." Mind elaberating just a little so I can accept as solution.
    – Tearran
    Commented Apr 1, 2022 at 18:45
  • It is the way variables are scoped in Python, your last_millis variable declared in the main application is not seen by functions unless you indicate to them that a specific variable is declared in the main body, the global declaration does that with the last_millis variable. There are better ways to code which avoid this, maybe pass the variable into the Method. If the variable is updated in a method then return the updated value from the function etc... Hope this is helpful Commented Apr 4, 2022 at 10:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.