Pyeventbus: a publish/subscribe event bus

Overview

pyeventbus

https://travis-ci.org/n89nanda/pyeventbus.svg?branch=master

pyeventbus is a publish/subscribe event bus for Python 2.7.

  • simplifies the communication between python classes
  • decouples event senders and receivers
  • performs well threads, greenlets, queues and concurrent processes
  • avoids complex and error-prone dependencies and life cycle issues
  • makes code simpler
  • has advanced features like delivery threads, workers and spawning different processes, etc.
  • is tiny (3KB archive)

pyeventbus in 3 steps:

  1. Define events:

    class MessageEvent:
        # Additional fields and methods if needed
        def __init__(self):
            pass
    
  2. Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

    from pyeventbus import *
    
    @subscribe(onEvent=MessageEvent)
    def func(self, event):
        # Do something
        pass
    

    Register your subscriber. For example, if you want to register a class in Python:

    from pyeventbus import *
    
    class MyClass:
        def __init__(self):
            pass
    
        def register(self, myclass):
            PyBus.Instance().register(myclass, self.__class__.__name__)
    
    # then during initilization
    
    myclass = MyClass()
    myclass.register(myclass)
    
  3. Post events:

    from pyeventbus import *
    
    class MyClass:
        def __init__(self):
            pass
    
        def register(self, myclass):
            PyBus.Instance().register(myclass, self.__class__.__name__)
    
        def postingAnEvent(self):
            PyBus.Instance().post(MessageEvent())
    
     myclass = MyClass()
     myclass.register(myclass)
     myclass.postingAnEvent()
    

Modes: pyeventbus can run the subscribing methods in 5 different modes

  1. POSTING:

    Runs the method in the same thread as posted. For example, if an event is posted from main thread, the subscribing method also runs in the main thread. If an event is posted in a seperate thread, the subscribing method runs in the same seperate method
    
    This is the default mode, if no mode has been provided::
    
    @subscribe(threadMode = Mode.POSTING, onEvent=MessageEvent)
    def func(self, event):
        # Do something
        pass
    
  2. PARALLEL:

    Runs the method in a seperate python thread::
    
    @subscribe(threadMode = Mode.PARALLEL, onEvent=MessageEvent)
    def func(self, event):
        # Do something
        pass
    
  3. GREENLET:

    Runs the method in a greenlet using gevent library::
    
    @subscribe(threadMode = Mode.GREENLET, onEvent=MessageEvent)
    def func(self, event):
        # Do something
        pass
    
  4. BACKGROUND:

    Adds the subscribing methods to a queue which is executed by workers::
    
    @subscribe(threadMode = Mode.BACKGROUND, onEvent=MessageEvent)
    def func(self, event):
        # Do something
        pass
    
  1. CONCURRENT:

    Runs the method in a seperate python process::
    
    @subscribe(threadMode = Mode.CONCURRENT, onEvent=MessageEvent)
    def func(self, event):
        # Do something
        pass
    

Adding pyeventbus to your project:

pip install pyeventbus

Example:

git clone https://github.com/n89nanda/pyeventbus.git

cd pyeventbus

virtualenv venv

source venv/bin/activate

pip install pyeventbus

python example.py

Benchmarks and Performance:

Refer /pyeventbus/tests/benchmarks.txt for performance benchmarks on CPU, I/O and networks heavy tasks.

Run /pyeventbus/tests/test.sh to generate the same benchmarks.

Performance comparison between all the modes with Python and Cython

alternate text

Inspiration

Inspired by Eventbus from greenrobot: https://github.com/greenrobot/EventBus
You might also like...
Code for the paper
Code for the paper "Unsupervised Contrastive Learning of Sound Event Representations", ICASSP 2021.

Unsupervised Contrastive Learning of Sound Event Representations This repository contains the code for the following paper. If you use this code or pa

Repo for "Event-Stream Representation for Human Gaits Identification Using Deep Neural Networks"

Summary This is the code for the paper Event-Stream Representation for Human Gaits Identification Using Deep Neural Networks by Yanxiang Wang, Xian Zh

Cross-media Structured Common Space for Multimedia Event Extraction (ACL2020)
Cross-media Structured Common Space for Multimedia Event Extraction (ACL2020)

Cross-media Structured Common Space for Multimedia Event Extraction Table of Contents Overview Requirements Data Quickstart Citation Overview The code

CVPRW 2021: How to calibrate your event camera
CVPRW 2021: How to calibrate your event camera

E2Calib: How to Calibrate Your Event Camera This repository contains code that implements video reconstruction from event data for calibration as desc

Repository relating to the CVPR21 paper TimeLens: Event-based Video Frame Interpolation
Repository relating to the CVPR21 paper TimeLens: Event-based Video Frame Interpolation

TimeLens: Event-based Video Frame Interpolation This repository is about the High Speed Event and RGB (HS-ERGB) dataset, used in the 2021 CVPR paper T

An implementation for `Text2Event: Controllable Sequence-to-Structure Generation for End-to-end Event Extraction`

Text2Event An implementation for Text2Event: Controllable Sequence-to-Structure Generation for End-to-end Event Extraction Please contact Yaojie Lu (@

Official PyTorch implementation of N-ImageNet: Towards Robust, Fine-Grained Object Recognition with Event Cameras (ICCV 2021)
Official PyTorch implementation of N-ImageNet: Towards Robust, Fine-Grained Object Recognition with Event Cameras (ICCV 2021)

N-ImageNet: Towards Robust, Fine-Grained Object Recognition with Event Cameras Official PyTorch implementation of N-ImageNet: Towards Robust, Fine-Gra

SurvITE: Learning Heterogeneous Treatment Effects from Time-to-Event Data

SurvITE: Learning Heterogeneous Treatment Effects from Time-to-Event Data SurvITE: Learning Heterogeneous Treatment Effects from Time-to-Event Data Au

Weakly Supervised Dense Event Captioning in Videos, i.e. generating multiple sentence descriptions for a video in a weakly-supervised manner.
Weakly Supervised Dense Event Captioning in Videos, i.e. generating multiple sentence descriptions for a video in a weakly-supervised manner.

WSDEC This is the official repo for our NeurIPS paper Weakly Supervised Dense Event Captioning in Videos. Description Repo directories ./: global conf

Comments
  • Same method name for multiple subscribers bug

    Same method name for multiple subscribers bug

    Please see the code below. To summarize:

    • Define one event
    • Define two subscriber listening for the event above. Each subscriber has a listener method with the name on_event
    • Each of the subscriber classes above defines an instance field, but with unique name (self.something in the first class, self.something2 in the second class)
    • Define another class that posts an event

    Run this scenario and get the error below:

    Exception in thread thread-on_event:
    Traceback (most recent call last):
      File "C:\Anaconda2\envs\python\lib\threading.py", line 801, in __bootstrap_inner
        self.run()
      File "C:\Anaconda2\envs\python\lib\site-packages\pyeventbus\pyeventbus.py", line 112, in run
        self.method(self.subscriber, self.event)
      File "C:/FractureID/projects/python/ui/spectraqc/PyEventBusBug.py", line 16, in on_event
        print (self.something)
    AttributeError: Subscriber2 instance has no attribute 'something'
    
    Exception in thread thread-on_event:
    Traceback (most recent call last):
      File "C:\Anaconda2\envs\python\lib\threading.py", line 801, in __bootstrap_inner
        self.run()
      File "C:\Anaconda2\envs\python\lib\site-packages\pyeventbus\pyeventbus.py", line 112, in run
        self.method(self.subscriber, self.event)
      File "C:/FractureID/projects/python/ui/spectraqc/PyEventBusBug.py", line 26, in on_event
        print (self.something_else)
    AttributeError: Subscriber1 instance has no attribute 'something_else'
    
    

    It complains about the variable in class two not having the attribute in the first class and the other way around.

    If I change on of the on_event to something else like on_event2 then the issue is gone.

    from pyeventbus import *
    
    
    class SomeEvent:
        def __init__(self):
            pass
    
    
    class Subscriber1:
        def __init__(self):
            self.something = 'First subscriber'
            PyBus.Instance().register(self, self.__class__.__name__)
    
        @subscribe(threadMode=Mode.PARALLEL, onEvent=SomeEvent)
        def on_event(self, event):
            print (self.something)
    
    
    class Subscriber2:
        def __init__(self):
            self.something_else = 'Second subscriber'
            PyBus.Instance().register(self, self.__class__.__name__)
    
        @subscribe(threadMode=Mode.PARALLEL, onEvent=SomeEvent)
        def on_event(self, event):
            print (self.something_else)
    
    
    class PyEventBusBug:
    
        def __init__(self):
            Subscriber1()
            Subscriber2()
            PyBus.Instance().post(SomeEvent())
    
    
    if __name__ == "__main__":
        PyEventBusBug()
    
    
    bug 
    opened by ddanny 0
  • Doesn't even start on Windows because 2000 threads is apparently too much

    Doesn't even start on Windows because 2000 threads is apparently too much

      File "C:\Python27\lib\site-packages\pyeventbus\pyeventbus.py", line 116, in subscribe
        bus = PyBus.Instance()
      File "C:\Python27\lib\site-packages\pyeventbus\Singleton.py", line 30, in Instance
        self._instance = self._decorated()
      File "C:\Python27\lib\site-packages\pyeventbus\pyeventbus.py", line 24, in __init__
        for worker in [lambda: self.startWorkers() for i in range(self.num_threads)]: worker()
      File "C:\Python27\lib\site-packages\pyeventbus\pyeventbus.py", line 24, in <lambda>
        for worker in [lambda: self.startWorkers() for i in range(self.num_threads)]: worker()
      File "C:\Python27\lib\site-packages\pyeventbus\pyeventbus.py", line 30, in startWorkers
        worker.start()
      File "C:\Python27\lib\threading.py", line 736, in start
        _start_new_thread(self.__bootstrap, ())
    thread.error: can't start new thread
    

    See also: https://stackoverflow.com/a/1835043/2583080

    bug 
    opened by PawelTroka 4
Releases(0.2)
Framework web SnakeServer.

SnakeServer - Framework Web 🐍 Documentação oficial do framework SnakeServer. Conteúdo Sobre Como contribuir Enviar relatórios de segurança Pull reque

Jaedson Silva 0 Jul 21, 2022
Learning Tracking Representations via Dual-Branch Fully Transformer Networks

Learning Tracking Representations via Dual-Branch Fully Transformer Networks DualTFR ⭐ We achieves the runner-ups for both VOT2021ST (short-term) and

phiphi 19 May 04, 2022
git《USD-Seg:Learning Universal Shape Dictionary for Realtime Instance Segmentation》(2020) GitHub: [fig2]

USD-Seg This project is an implement of paper USD-Seg:Learning Universal Shape Dictionary for Realtime Instance Segmentation, based on FCOS detector f

Ruolin Ye 80 Nov 28, 2022
Data and analysis code for an MS on SK VOC genomes phenotyping/neutralisation assays

Description Summary of phylogenomic methods and analyses used in "Immunogenicity of convalescent and vaccinated sera against clinical isolates of ance

Finlay Maguire 1 Jan 06, 2022
A Pytorch Implementation of [Source data‐free domain adaptation of object detector through domain

A Pytorch Implementation of Source data‐free domain adaptation of object detector through domain‐specific perturbation Please follow Faster R-CNN and

1 Dec 25, 2021
Use graph-based analysis to re-classify stocks and to improve Markowitz portfolio optimization

Dynamic Stock Industrial Classification Use graph-based analysis to re-classify stocks and experiment different re-classification methodologies to imp

Sheng Yang 10 Dec 05, 2022
Code for the paper "Location-aware Single Image Reflection Removal"

Location-aware Single Image Reflection Removal The shown images are provided by the datasets from IBCLN, ERRNet, SIR2 and the Internet images. The cod

72 Dec 08, 2022
The Deep Learning with Julia book, using Flux.jl.

Deep Learning with Julia DL with Julia is a book about how to do various deep learning tasks using the Julia programming language and specifically the

Logan Kilpatrick 67 Dec 25, 2022
Self-Guided Contrastive Learning for BERT Sentence Representations

Self-Guided Contrastive Learning for BERT Sentence Representations This repository is dedicated for releasing the implementation of the models utilize

Taeuk Kim 16 Dec 04, 2022
An OpenAI-Gym Package for Training and Testing Reinforcement Learning algorithms with OpenSim Models

Authors: Utkarsh A. Mishra and Dr. Dimitar Stanev Advisors: Dr. Dimitar Stanev and Prof. Auke Ijspeert, Biorobotics Laboratory (BioRob), EPFL Video Pl

Utkarsh Mishra 16 Dec 13, 2022
Automatic Number Plate Recognition using Contours and Convolution Neural Networks (CNN)

Cite our paper if you find this project useful https://www.ijariit.com/manuscripts/v7i4/V7I4-1139.pdf Abstract Image processing technology is used in

Adithya M 2 Jun 28, 2022
Official implementation of Self-supervised Image-to-text and Text-to-image Synthesis

Self-supervised Image-to-text and Text-to-image Synthesis This is the official implementation of Self-supervised Image-to-text and Text-to-image Synth

6 Jul 31, 2022
AtlasNet: A Papier-Mâché Approach to Learning 3D Surface Generation

AtlasNet [Project Page] [Paper] [Talk] AtlasNet: A Papier-Mâché Approach to Learning 3D Surface Generation Thibault Groueix, Matthew Fisher, Vladimir

577 Dec 17, 2022
Code for DisCo: Remedy Self-supervised Learning on Lightweight Models with Distilled Contrastive Learning

DisCo: Remedy Self-supervised Learning on Lightweight Models with Distilled Contrastive Learning Pytorch Implementation for DisCo: Remedy Self-supervi

79 Jan 06, 2023
social humanoid robots with GPGPU and IoT

Social humanoid robots with GPGPU and IoT Social humanoid robots with GPGPU and IoT Paper Authors Mohsen Jafarzadeh, Stephen Brooks, Shimeng Yu, Balak

0 Jan 07, 2022
NuPIC Studio is an all­-in-­one tool that allows users create a HTM neural network from scratch

NuPIC Studio is an all­-in-­one tool that allows users create a HTM neural network from scratch, train it, collect statistics, and share it among the members of the community. It is not just a visual

HTM Community 93 Sep 30, 2022
[CVPR2022] Bridge-Prompt: Towards Ordinal Action Understanding in Instructional Videos

Bridge-Prompt: Towards Ordinal Action Understanding in Instructional Videos Created by Muheng Li, Lei Chen, Yueqi Duan, Zhilan Hu, Jianjiang Feng, Jie

58 Dec 23, 2022
Kaggle Ultrasound Nerve Segmentation competition [Keras]

Ultrasound nerve segmentation using Keras (1.0.7) Kaggle Ultrasound Nerve Segmentation competition [Keras] #Install (Ubuntu {14,16}, GPU) cuDNN requir

179 Dec 28, 2022
YolactEdge: Real-time Instance Segmentation on the Edge

YolactEdge, the first competitive instance segmentation approach that runs on small edge devices at real-time speeds. Specifically, YolactEdge runs at up to 30.8 FPS on a Jetson AGX Xavier (and 172.7

Haotian Liu 1.1k Jan 06, 2023
This repository contains a pytorch implementation of "StereoPIFu: Depth Aware Clothed Human Digitization via Stereo Vision".

StereoPIFu: Depth Aware Clothed Human Digitization via Stereo Vision | Project Page | Paper | This repository contains a pytorch implementation of "St

87 Dec 09, 2022