I've been exploring how async works in Python. So far, I've made a few simple MQTT-based async mini-services (get a message, do something, maybe retrieve something, send a message).
For my next mini-project, I'm trying to tie Discord and MQTT together. The goal is to have discord messages appear over MQTT, and mqtt messages on discord. I've got an async discord-client object, and an async mqtt-client object. Both work fine, but connecting them is a bit of an issue.
My current approach is to have the Discord object be 'leading', while I put the MQTT object in the Discord object (discord-client.mqtt-client = mqtt-client, meaning I can do things like await self.mqtt-client.publish(). This appears to work, so far.
My problem is that this approach feels a bit wrong. Is this a normal approach? Are there other approaches?
Answering my own question, with help.
Having nested async objects works, but 'smells wrong'. It also makes for odd looking (and therefore difficult to maintain) code, and likely introduces weird bugs and such later on.
A better approach is to make use of asyncio.Queue, where each of the two client-objects has one queue to write to, and one to read from. Like this:
discord-client -> discord-to-mqtt-queue -> mqtt-client
mqtt-client -> mqtt-to-discord-queue -> discord-client
(Not the actual naming of the objects)
This works, makes sense, and the resulting code is readable.
Two async objects interacting