Reputation: 364
So I'm making a python program to track mqtt connections on topics so that I can have a dashboard of connections. I have a variable that I want to pass into the on_message
function so that I can modify it, and print it out.
I already know I can make the variable global
by just declaring it to be so, but from my experience declaring things to be global
is to be avoided at all costs, so I'm wondering if there's another way.
(code is abridged for readability's sake)
def process_message(client, userdata, message):
global connected_list
# mess around with it and exit the callback
if __name__ == "__main__":
connected_list = []
# set up the mosquitto client and then
client.on_message = process_message
# tell it to subscribe and connect and then
client.loop_forever()
Basically I know that it can be done with global
but I'd quite like to avoid it if possible. Does anyone have any ideas?
Thanks!
EDIT
Thanks for the help guys, I did a mix of both suggestions and now have a class that contains both the list and also the lock, so I can easily lock and unlock the list when I'm operating on it.
Upvotes: 0
Views: 1571
Reputation: 1227
You could try putting all the callbacks as methods in a class. The state could then be variables initialized in __init__
instead of global variables. This greatly improves the reusability of your code.
class Handler:
def __init__(self):
self.connected_list = []
def process_message(self, client, userdata, message):
connected_list = self.connected_list
# mess around with it and exit the callback
if __name__ == "__main__":
handler = Handler()
client.on_message = handler.process_message
# tell it to subscribe and connect and then
client.loop_forever()
Upvotes: 2