0

I'm reading the documentation for Paho MQTT's Publish module, and thinking of my application in which I might have to publish many single messages, each with similar keyword arguments. The calls look similar to the following:

paho.mqtt.publish.single('dummy_topic', payload=dummy_payload, qos=0, retain=False,
       auth={'username': "dummy_username", 'password': "dummy_password"},
       hostname=config['mqtt_host'], port=int(config['mqtt_port']), tls=dummy_tls)

In order to keep my code DRY, I'm trying to think of a way to persist the keyword arguments across different single commands.

For HTTP requests, Python's requests module has the Sessions object which allows one to do this. Is there something similar for Paho MQTT, or shall I instead use something like partial from the functools module?

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526

1 Answers1

1

You've already identified the solution, I think. The functools.partial function should give you whaat you want. For example, the following code:

from functools import partial

def myfunc(arg, kw1='foo', kw2='bar'):
    print 'arg:', arg
    print 'kw1:', kw1
    print 'kw2:', kw2

newfunc = partial(myfunc, kw1='hello', kw2='world')

newfunc('somearg')

Produces this output:

arg: somearg
kw1: hello
kw2: world

Applying that to your example, you would do something like:

publish_single = partial(payload=dummy_payload, qos=0, retain=False,
   auth={'username': "dummy_username", 'password': "dummy_password"},
   hostname=config['mqtt_host'], port=int(config['mqtt_port']), tls=dummy_tls)

And call it like:

publish_single('some_topic')
publish_single('another_topic')
larsks
  • 277,717
  • 41
  • 399
  • 399