The following code producing - UnboundLocalError: local variable 'ws_is_connected' referenced before assignment
:
import threading
ws_is_connected=False
def timer_ws():
threading.Timer(22.0, timer_ws).start()
if not ws_is_connected:
print("Alarm")
ws_is_connected=False
print("22 seconds")
timer_ws()
For some reason a Python thinks that this variable a local, but it was declared globally on top. I am newbie in Python, so maybe doing something wrong.
The reason the ws_is_connected
settled lower is a websocket client ping-pong check. I need to reset this variable every 22 seconds in order to make sure that ws connection is alive:
def on_pong(ws, message):
print("Got a pong! No need to respond")
ws_is_connected=True
Cause on_pong function repeats every 10 seconds.
I am looking for some way to modify a code so it will work or use another approach and rewrite code.
CodePudding user response:
You can make the function use the global variable as well. Just before calling the variable in the function, add global var_name
and it should work fine like this:
def timer_ws():
threading.Timer(22.0, timer_ws).start()
global ws_is_connected
if not ws_is_connected: