What is the mechanism to use synchronous variables with messages from websocket server in Python

Viewed 10

I am using a third party API that provides websocket functionality for continuous stream of messages. I want to use variables that are defined out of the on_message() function. The structure of the code is as below:

soc = WebSocket()

Live_Data = {}
Prev_Data = {}
def on_message(ws, message):
    if <check condition about Prev_Data>:
        <Do something on Prev_Data and Live_Data>
            
def on_open(ws):
    print("on open")

    
def on_error(ws, error):
    print(error)
    
def on_close(ws):
    print("Close")

# Assign the callbacks.
soc._on_open = on_open
soc._on_message = on_message
soc._on_error = on_error
soc._on_close = on_close

soc.connect()

But when I run this, it throws error that

Prev_data is referenced before it is assigned

I think this is because the on_message() method is asynchronous and the next on_message() method tries to access the Prev_Data before the first on_message() has finished writing it.

So what is the mechanism to synchronously access the Prev_Data and some other such variables here?

P.S: When I don't use the Prev_Data at all, the code runs fine.

0 Answers
Related