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
Fast and multi-threaded script to automatically claim targeted username including 14 day bypass

Instagram Username Auto Claimer Fast and multi-threaded script to automatically claim targeted username. Click here to report bugs. Usage Download ZIP

265 Dec 28, 2022
New discord token grabber, password and general information

New discord token grabber, password and general information

Monstered 6 Nov 09, 2022
Twitter bot to know the number of dislikes of a YouTube video

YT_dislikes is a twitter bot that allows you to know the number of dislikes (and likes) of a YouTube video. Now it is not possible to see the number o

1 Jan 08, 2022
A Discord Self-Bot in Python

👨‍💻 Discord Self Bot 👨‍💻 A Discord Self-Bot in Python by natrix Installation Run: selfbot.bat Python: version : 3.8 Modules

natrix_dev 3 Oct 02, 2022
Simple VK API wrapper for Python

VK Admier: documentation VK Admier is simple VK API wrapper for community bot development. Authorization You should create bot object from Client clas

Egor Light 2 Nov 10, 2022
Wedding website for July 2022.

Capstone Project: a real wedding website! User Stories A user should be able to signup for the website A user should be able to login to the website i

1 Nov 04, 2021
“ Hey there 👋 I'm Daisy „ AI based Advanced Group Management Bot Suit For All Your Needs ❤️.. Source Code of @Daisyxbot

Project still under heavy development Everything will be changed in the release “ Hey there 👋 I'm Daisy „ AI based Advanced telegram Group Management

TeamDaisyX 43 Nov 12, 2022
A simple url uploader bot with permenent thumbnail support

URL-Uploader A simple url uploader bot with permenent thumbnail support Scrapped some code from @SpEcHIDe's AnyDLBot Repository Please fork this repos

Fayas Noushad 40 Nov 29, 2021
The best Discord bot, created for r/Jailbreak

Bloo Setup instructions These instructions assume you are on macOS or Linux. Windows users, good luck. With Docker (recommended!) You will need the fo

GIR 33 Dec 16, 2022
A small discord bot to interface with python-discord's snekbox.

A small discord bot to interface with python-discord's snekbox.

Hassan Abouelela 0 Oct 05, 2021
A discord token creator that uses the service capmonster for captcha solving!

Discord Token Creator A discord token creator that uses the service capmonster for captcha solving! Report Bug · Request Feature Features Autojoin dis

dropout 41 Oct 25, 2021
PS4RemotePKGSender - Use with Remote PKG Installer

PS4_Remote_PKG_Sender Used with the remote PKG installer on PS4 Thanks to the au

Teri 4 Sep 23, 2022
Verkehrsunfälle in Deutschland, aufgeschlüsselt nach Verkehrsmittel des Hauptverursachers und Nebenverursachers

How-To Einfach ./main.py ausführen mit der Statistik-Datei aus dem Ordner "Unfälle_mit_mehreren_Beteiligten" als erstem Argument. Requirements python,

4 Oct 12, 2022
Support for Competitive Coding badges to add in Github readme or portfolio websites.

Support for Competitive Coding badges to add in Github readme or portfolio websites.

Akshat Aggarwal 2 Feb 14, 2022
This is a discord bot, which tells you food recipes.

Discord Chef Bot You have a friend, familiy or other group / channel where the topic is the food? You cannot really decide what's for Saturday lunch?

2 Apr 25, 2022
Flask-SQLAlchemy API for daisuki-web

💟 Anime Daisuki! API API de animes com cadastro de usuários. O usuário autenticado pode avaliar e favoritar animes, comentar episódios e verificar o

Paulo Thor 1 Nov 04, 2021
A library that allows you to easily mock out tests based on AWS infrastructure.

Moto - Mock AWS Services Install $ pip install moto[ec2,s3,all] In a nutshell Moto is a library that allows your tests to easily mock out AWS Services

Steve Pulec 6.5k Jan 02, 2023
🐍 The official Python client library for Google's discovery based APIs.

Google API Client This is the Python client library for Google's discovery based APIs. To get started, please see the docs folder. These client librar

Google APIs 6.2k Dec 31, 2022
:electric_plug: Generating short urls with python has never been easier

pyshorteners A simple URL shortening API wrapper Python library. Installing pip install pyshorteners Documentation https://pyshorteners.readthedocs.i

Ellison 351 Jan 03, 2023
A Dm Bot, also knows as Mass DM bot which can send one message to All of the Users in a Specific Server!

Discord DM Bot discord.py 1.7.2 python 3.9.5 asyncio 3.4.3 Installation Cloud Host Tutorial uploaded in YouTube, watch it by clicking here. Local Host

hpriyam8 7 Mar 24, 2022