Search code examples
pythonglobal-variablespublish-subscribe

Python avoid global variable while polling data


I am writing an mqtt client, which is looping forever while collecting message data.

The array is currently global, but since this is considered bad practice I want to avoid that. However I am not sure how to call on_message with another parameter.

How can I avoid using array as a global variable?

   def on_message(client, userdata, msg):
        global array
        array.append(msg.payload)

   array = []
   client = mqtt.Client()
   client.on_connect = on_connect
   client.on_message = on_message
   client.connect("JOHN", 1883, 60)
   client.loop_forever()

EDIT: I followed CarloLobranos advice and am using userdata now as an input (as the API supports that). Thanks for all answers!


Solution

  • You can wrap everything in a function:

    def mqtt_wrapper():
        array = []
        def on_message(client, userdata, msg):
            array.append(msg.payload)
        client = mqtt.Client()
        client.on_connect = on_connect
        client.on_message = on_message
        client.connect("JOHN", 1883, 60)
        client.loop_forever()
    
    mqtt_wrapper()