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
un outil pour bypasser les code d'états HTTP négatif coté client ( 4xx )

4xxBypasser un outil pour bypasser les code d'états HTTP négatif coté client ( 4xx ) Liscence : MIT license Creator Installation : git clone https://g

21 Dec 25, 2022
Indian Space Research Organisation API With Python

ISRO Indian Space Research Organisation API Installation pip install ISRO Usage import isro isro.spacecrafts() # returns spacecrafts data isro.lau

Fayas Noushad 5 Aug 11, 2022
Bitcoin tracker hecho con python.

Bitcoin Tracker Precio del Bitcoin en tiempo real. Script simple hecho con python. Rollercoin RollerCoin es un juego en el que puedes ganar bitcoin (y

biyivi 3 Jan 04, 2022
A bot written in Python to automate attending classes on MyClass (Codetantra).

codetantrabot This is python program to attend class on myclass(codetantra) Prerequisites You should have Python3 and Pip installed on your system Run

Aniket Kumar 1 Feb 08, 2022
An API wrapper around Discord API written in Python

Diskord This library is a maintained fork of now archived library, discord.py. A modern and easy to use API wrapper around Discord API written in Pyth

Diskord 36 Aug 22, 2022
NFT which pays royalties to its creator each time it is sold.

Chialisp NFT with Perpetual Creator Royalties This is a chialisp NFT in which the creator/minter defines a puzzle hash which will capture a fixed perc

Geoff Walmsley 20 Jun 28, 2022
Repository containing the project files for CEN4020's Team Utah.

inCollege-Team-Utah Repository containing the project files for CEN4020's Team Utah. Contributors: Deepak Putta Jose Ramirez Fuentes Jaason Raudales C

Keylin Sanchez 3 Jul 12, 2022
Project made to analyse movie trends

MovieTrends Project to analyse the daily movie trends from the website The Movie DataBase. The main idea is upload the results to a PostgreSQL server

Jazmín López Chacón 0 Feb 15, 2022
Ridogram is an advanced multi-featured Telegram UserBot.

Ridogram Ridogram is an advanced multi-featured Telegram UserBot. String Session Collect String Session by running python3 stringsession.py locally or

Md. Ridwanul Islam Muntakim 134 Dec 29, 2022
I-Spy is a discord and twitter bot 🤖 that keeps a check on usage foul language, hate-speech and NSFW contents

I-Spy is a discord and twitter bot 🤖 that keeps a check on usage foul language, hate-speech and NSFW contents. It is the one stop solution to monitor your discord servers and twitter handles against

Tia Saxena 5 Nov 16, 2022
Deep reinforcement learning library built on top of Neural Network Libraries

Deep Reinforcement Learning Library built on top of Neural Network Libraries NNablaRL is a deep reinforcement learning library built on top of Neural

Sony 100 Dec 14, 2022
Asynchronous Guilded API wrapper for Python

Welcome to guilded.py, a discord.py-esque asynchronous Python wrapper for the Guilded API. If you know discord.py, you know guilded.py. Documentation

shay 115 Dec 30, 2022
Download apps and remove icloud

Download apps and remove icloud

A Telegram Bin Checker Bot made with python for check Bin valid or Invalid. 💳

Bin Checker Bot A Telegram Bin Checker Bot made with python for check Bin valid or Invalid. 📌 Deploy On Heroku 🏷 Environment Variables API_ID - Your

Chamindu Denuwan 20 Dec 10, 2022
Freqtrade 3commas wrapper for python

Freqtrade 3commas wrapper The aim of this project is to provide an easy way to integrate freqtrade with 3commas. The main reason someone would want to

Alex Babescu 43 Dec 17, 2022
Whatsapp-APi Wrapper From rzawapi.my.id

Whatsapp-APi Wrapper From rzawapi.my.id

Rezza Priatna 2 Apr 19, 2022
Telegram bot to stream videos in telegram voicechat for both groups and channels

Telegram bot to stream videos in telegram voicechat for both groups and channels. Supports live streams, YouTube videos and telegram media. With record stream support, Schedule streams, and many more

ALBY 9 Feb 20, 2022
Acid's Utilities is a bot for my Discord server that alerts when I go live, welcomes new users, has some awesome games and so much more!

Acid's Utilities Acid's Utilities is a bot for my Discord server that alerts when I go live, welcomes new users, has some awesome games and so much mo

AcidFilms (Fin Stuart) 3 Nov 19, 2021
Role Discord Members (by username) from File

Role Discord Members (by username) from File Bot Setup Navigate to https://discord.com/developers/applications Create a new application Navigate to th

Dylan Orrell 3 Jan 06, 2022
Changes the Telegram bio, profile picture, first and last name to the song that the user is currently listening to.

TGBIOFY - Telegram & Spotify integration Changes the Telegram bio, profile picture, first and last name to the song that the user is currently listeni

elpideus 26 Dec 07, 2022