Asyncevents: a small library to help developers perform asynchronous event handling in Python

Overview

asyncevents - Asynchronous event handling for modern Python

asyncevents is a small library to help developers perform asynchronous event handling in modern Python code.

Features

  • Priority queueing to allow for deterministic event triggering (with a catch, see below)
  • Built-in exception handling (optional)
  • The public API is fully type hinted for those sweet, sweet editor suggestions
  • Public API is fully documented (and some private stuff too): you could write this from scratch in a couple of hours (like I did)
  • Very small (~200 CLOC), although it can't fit on a postcard

Note: Deterministic event handling can only occur in blocking mode, i.e. when a call to emit() blocks until all event handlers have run. If the non-blocking mode is used, handlers are started according to their priority, but there's no telling on how they will be further scheduled to run and that depends entirely on the underlying asyncio event loop

Limitations

  • Only compatible with asyncio due to the fact that other libraries such as trio and curio have wildly different design goals (structured concurrency, separation of environments, etc.), which makes implementing some functionality (i.e. the wait() method) tricky, if not outright impossible. Also those libraries, especially trio, already have decent machinery to perform roughly what asyncevent does
  • Does not support using any other loop than the currently running one because of some subtleties of modern asyncio wrappers like asyncio.run() which creates its own event loop internally (Thanks, asyncio)
  • Exceptions are kinda finicky in non-blocking mode due to how asyncio.gather works: only the first exception in a group of handlers is properly raised and log messages might get doubled. Also, exception logging and propagation is delayed until you await wait("some_event") so be careful

Why?

This library exists because the current alternatives either suck, lack features or are inspired by other languages' implementations of events like C# and Node.js: asyncevents aims to be a fully Pythonic library that provides just the features you need and nothing more (nor nothing less).

Cool! How do I use it?

Like this

import time
import asyncio
from asyncevents import on_event, emit, wait


@on_event("hello")
async def hello(_, event: str):
    print(f"Hello {event!r}!")


@on_event("hi")
async def hi(_, event: str):
    print(f"Hi {event!r}! I'm going to sleep for 5 seconds")
    await asyncio.sleep(5)  # Simulates some work


async def main():
    print("Firing blocking event 'hello'")
    await emit("hello")  # This call blocks until hello() terminates
    print("Handlers for event 'hello' have exited")
    # Notice how, until here, the output is in order: this is on purpose!
    # When using blocking mode, asyncevents even guarantees that handlers
    # with different priorities will be executed in order
    print("Firing non-blocking event 'hi'")
    await emit("hi", block=False)  # This one spawns hi() and returns immediately
    print("Non-blocking event 'hi' fired")
    await emit("event3")  # Does nothing: No handlers registered for event3!
    # We wait now for the the handler of the "hi" event to complete
    t = time.time()
    print("Waiting on event 'hi'")
    await wait("hi")  # Waits until all the handlers triggered by the "hi" event exit
    print(f"Waited for {time.time() - t:.2f} seconds")  # Should print roughly 5 seconds


if __name__ == "__main__":
    asyncio.run(main())

Note: This example showed that the event names match the functions' names: this is just for explanatory purposes! It's not compulsory for your event and their respective handlers' names to match. You can also register as many functions you want for the same or multiple events and asyncevents will call them all when one of them is fired. For more usage examples (until the documentation is done), check out the tests directory or read the source code: it's pretty straightforward, I promise.

TODOs

  • Documentation
  • More tests
  • Trio/curio backend (maybe)
Owner
Mattia
A fan of the FOSS philosophy, *nix systems and Python. Occasionally a freelance Software Developer
Mattia
→ Comando Básico para Python Discord

Discord.py · Código @client.event async def on_ready(): print('He iniciado sessión en: {0.user}'.format(client)) @client.event async def on_messa

Panda.xyz 4 Mar 12, 2022
Repositorio dedicado a contener los archivos fuentes del bot de discord "Lector de Ejercicios".

Lector de Ejercicios Este bot de discord está pensado para usarse únicamente en el discord de la materia Algoritmos y Programación I, de la Facultad d

Franco Lighterman Reismann 3 Sep 17, 2022
Widevine CDM API

wvproxy Widevine CDM API Setup Install Python 3.6 or newer and Poetry Install Python package dependencies using poetry install Activate the virtual en

24 Dec 09, 2022
A module grouping multiple translation APIs

translatepy (originally: translate) An aggregation of multiple translation API Translate, transliterate, get the language of texts in no time with the

349 Jan 06, 2023
Python Wrapper for aztro - The Astrology API | Get Daily Horoscope 💫

PyAztro PyAztro is a client library for aztro written in Python. aztro provides horoscope info for sun signs such as Lucky Number, Lucky Color, Mood,

Sameer Kumar 30 Jan 08, 2023
Roaster - this gui app + program bundle roasts.

Roaster - this gui app + program bundle roasts.

Harsh ADV) 1 Jan 04, 2022
𝐀 𝐦𝐨𝐝𝐮𝐥𝐚𝐫 𝐓𝐞𝐥𝐞𝐠𝐫𝐚𝐦 𝐆𝐫𝐨𝐮𝐩 𝐦𝐚𝐧𝐚𝐠𝐞𝐦𝐞𝐧𝐭 𝐛𝐨𝐭 𝐰𝐢𝐭𝐡 𝐮𝐥𝐭𝐢𝐦𝐚𝐭𝐞 𝐟𝐞𝐚𝐭𝐮𝐫𝐞𝐬

𝐇𝐨𝐰 𝐓𝐨 𝐃𝐞𝐩𝐥𝐨𝐲 For easiest way to deploy this Bot click on the below button 𝐌𝐚𝐝𝐞 𝐁𝐲 𝐒𝐮𝐩𝐩𝐨𝐫𝐭 𝐆𝐫𝐨𝐮𝐩 𝐒𝐨𝐮𝐫𝐜𝐞𝐬 𝐆𝐞𝐧𝐞?

Mukesh Solanki 2 Oct 06, 2021
This is a Innexia Chat Bot Open Source Code 🤬

⚡ Innexia ⚡ A Powerful, Smart And Simple Chat Bot ... Written with Python... Available on Telegram as @InnexiaChatBot ❤️ Support ⭐️ Thanks to everyone

Dark Cyber 4 Oct 02, 2022
Template to create a telegram bot in python

Template for Telegram Bot Template to create a telegram bot in python. How to Run Set your telegram bot token as environment variable TELEGRAM_BOT_TOK

PyTopia 10 Mar 07, 2022
Unirest in Python: Simplified, lightweight HTTP client library.

Unirest for Python Unirest is a set of lightweight HTTP libraries available in multiple languages, built and maintained by Mashape, who also maintain

Kong 432 Dec 21, 2022
Simple spam bot made in python

Simple Spam Bot A Simple and easy way to be the most hated person between your friends, All you have to do is spam the group chat using this bot until

Kareem Osama 6 Sep 05, 2022
Add Me To Your Group Enjoy With Me. Pyrogram bot. https://t.me/TamilSupport

SongPlayRoBot 3X Fast Telethon Based Bot ⚜ Open Source Bot 👨🏻‍💻 Demo : SongPlayRoBot 💃🏻 Easy To Deploy 🤗 Click Below Image to Deploy DEPLOY Grou

IMVETRI 850 Dec 30, 2022
Most Powerful Chatbot On Telegram Bot

About Hello, I am Lycia [リュキア], An Intelligent ChatBot. If You Are Feeling Lonely, You can Always Come to me and Chat With Me! How To Host The easiest

RedAura 8 May 26, 2021
Yes, it's true :two_hearts: This repository has 316 stars.

Yes, it's true! Inspired by a similar repository from @RealPeha, but implemented using a webhook on AWS Lambda and API Gateway, so it's serverless! If

510 Dec 28, 2022
Python library for using SMS.ir web services

smsir smsir is a Python library for using SMS web services www.sms.ir Installation Use the package manager pip to install smsir. pip install smsir Usa

mohammad reza 2 Oct 14, 2022
RedFish API Toolkit

RedFish API Toolkit RedFish API Toolkit Build Status GitHub Actions Travis CI Requirements requirements.txt requirements-dev.txt Dependencies Document

Larry Smith Jr. 1 Nov 20, 2021
A Collection Manager for the objkt.com Minting Factory

Objkt Collection Manager A Collection Manager for the objkt.com Minting Factory. This contract can create a collection on objkt.com and mint into it.

Asbjorn Enge 5 Nov 22, 2022
API to retrieve the number of grades on the OGE website (Website listing the grades of students) to know if a new grade is available. If a new grade has been entered, the program sends a notification e-mail with the subject.

OGE-ESIREM-API Introduction API to retrieve the number of grades on the OGE website (Website listing the grades of students) to know if a new grade is

Benjamin Milhet 5 Apr 27, 2022
Davide Gallitelli 3 Dec 21, 2021