0

Using a socket programming library am creating a function and validating the same in every tick of the callback. so i declared a global variable initial in the top and checking that variable in the tick but am getting the below error:

ERROR:websocket:error from callback >: local variable 'initial' referenced before assignment

Seems on every call back the python global scope not getting initialized

(zeroconnecty.py)

from kiteconnect import WebSocket

kws = WebSocket("xxxx", "xxxx", "USERNAME")

initial=True
print "initial",initial

#Callback for tick reception.
def on_tick(tick, ws):

    if(initial):
        print "only execute if it called first time callback"
        initial=False
    else:
        print "all times except initial callback"


#Callback for successful connection.
def on_connect(ws):

    ws.subscribe([738561])
    ws.set_mode(ws.MODE_FULL, [738561])

#Assign the callbacks.
kws.on_tick = on_tick 
kws.on_connect = on_connect

#Infinite loop on the main thread. Nothing after this will run.
#You have to use the pre-defined callbacks to manage subscriptions.
kws.connect() 
user3296639
  • 21
  • 2
  • 5
  • If you're going to assign a global variable `initial` inside a function, put `global initial` at the top of the function. That tells the interpreter that you're trying to refer to a global variable, not a local one. – khelwood Dec 08 '16 at 08:23
  • Possible duplicate of [Local variable referenced before assignment in Python?](http://stackoverflow.com/questions/18002794/local-variable-referenced-before-assignment-in-python) – khelwood Dec 08 '16 at 08:25

1 Answers1

0

Try referencing global in your on_tick() function:

global initial
initial=True

def on_tick(tick, ws):
    global initial
    if(initial):
        print "only execute if it called first time callback"
        initial=False
    else:
        print "all times except initial callback"

RobC
  • 22,977
  • 20
  • 73
  • 80
Bluebot
  • 166
  • 15