SS Shah
SS Shah

Reputation: 137

Pass argument through a class to a callback function

Let's say I have a websocket client and I want to update a variable when it opens the connection.

def on_open(ws):
    x += 1

def main():
    x = 0
    ws = websocket.WebSocketApp('wss://api2.poloniex.com/', on_message=on_message, on_error=on_error,on_close=on_close,on_open=on_open)
    ws.run_forever()

if __name__ == '__main__':
    main()

The relevant code in the websocket library is as follows:

Class WebSocketApp(object):
    def __init__(self, url, header=None,
             on_open=None, on_message=None, on_error=None,
             on_close=None, on_ping=None, on_pong=None,
             on_cont_message=None,
             keep_running=True, get_mask_key=None, cookie=None,
             subprotocols=None,
             on_data=None):

        ...
        self.on_open = on_open
        ...

    def run_forever(self, sockopt=None, sslopt=None,
                ping_interval=0, ping_timeout=None,
                http_proxy_host=None, http_proxy_port=None,
                http_no_proxy=None, http_proxy_auth=None,
                skip_utf8_validation=False,
                host=None, origin=None):
        ... code to open socket ...

        self._callback(self.on_open)
        ...

    def _callback(self, callback, *args):
        if callback:
            callback(self, *args)

I'm having trouble figuring out how to pass "x" through to my defined on_open function. I figure it's not good practice to modify my local version of the library for my use. Here's the link to the websocket library - https://github.com/websocket-client/websocket-client/tree/master/websocket , the class is in the _app.py file

EDIT: looking for a solution without using global variables

Upvotes: 1

Views: 2416

Answers (1)

ingvar
ingvar

Reputation: 4377

class Counter:

    def __init__(self):
        self._value = 0

    def get_value(self):
        return self._value

    def inc_value(self):
        self._value += 1


def main():
    counter = Counter()

    def on_open(ws, x=counter):
        x.inc_value()

    ws = websocket.WebSocketApp('wss://api2.poloniex.com/', on_message=on_message, on_error=on_error,on_close=on_close,on_open=on_open)
    ws.run_forever()

if __name__ == '__main__':
    main()

Upvotes: 3

Related Questions