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)
A visualisation tool for Deep Reinforcement Learning

DRLVIS - Visualising Deep Reinforcement Learning Created by Marios Sirtmatsis with the support of Alex Bäuerle. DRLVis is an application used for visu

Marios Sirtmatsis 1 Nov 04, 2021
NICE-GAN — Official PyTorch Implementation Reusing Discriminators for Encoding: Towards Unsupervised Image-to-Image Translation

NICE-GAN-pytorch - Official PyTorch implementation of NICE-GAN: Reusing Discriminators for Encoding: Towards Unsupervised Image-to-Image Translation

Runfa Chen 208 Nov 25, 2022
A Comprehensive Empirical Study of Vision-Language Pre-trained Model for Supervised Cross-Modal Retrieval

CLIP4CMR A Comprehensive Empirical Study of Vision-Language Pre-trained Model for Supervised Cross-Modal Retrieval The original data and pre-calculate

24 Dec 26, 2022
App for identification of various objects. Based on YOLO v4 tiny architecture

Object_detection Repository containing trained model yolo v4 tiny, which is capable of identification 80 different classes Default feed is set to be a

Mateusz Kurdziel 0 Jun 22, 2022
Adaptive Attention Span for Reinforcement Learning

Adaptive Transformers in RL Official implementation of Adaptive Transformers in RL In this work we replicate several results from Stabilizing Transfor

100 Nov 15, 2022
Implementation of SE3-Transformers for Equivariant Self-Attention, in Pytorch.

SE3 Transformer - Pytorch Implementation of SE3-Transformers for Equivariant Self-Attention, in Pytorch. May be needed for replicating Alphafold2 resu

Phil Wang 207 Dec 23, 2022
The official implementation of Variable-Length Piano Infilling (VLI).

Variable-Length-Piano-Infilling The official implementation of Variable-Length Piano Infilling (VLI). (paper: Variable-Length Music Score Infilling vi

29 Sep 01, 2022
Dynamic vae - Dynamic VAE algorithm is used for anomaly detection of battery data

Dynamic VAE frame Automatic feature extraction can be achieved by probability di

10 Oct 07, 2022
Code for the paper Open Sesame: Getting Inside BERT's Linguistic Knowledge.

Open Sesame This repository contains the code for the paper Open Sesame: Getting Inside BERT's Linguistic Knowledge. Credits We built the project on t

9 Jul 24, 2022
Pytorch code for semantic segmentation using ERFNet

ERFNet (PyTorch version) This code is a toolbox that uses PyTorch for training and evaluating the ERFNet architecture for semantic segmentation. For t

Edu 394 Jan 01, 2023
PyTorch module to use OpenFace's nn4.small2.v1.t7 model

OpenFace for Pytorch Disclaimer: This codes require the input face-images that are aligned and cropped in the same way of the original OpenFace. * I m

Pete Tae-hoon Kim 176 Dec 12, 2022
Rayvens makes it possible for data scientists to access hundreds of data services within Ray with little effort.

Rayvens augments Ray with events. With Rayvens, Ray applications can subscribe to event streams, process and produce events. Rayvens leverages Apache

CodeFlare 32 Dec 25, 2022
Intel® Neural Compressor is an open-source Python library running on Intel CPUs and GPUs

Intel® Neural Compressor targeting to provide unified APIs for network compression technologies, such as low precision quantization, sparsity, pruning, knowledge distillation, across different deep l

Intel Corporation 846 Jan 04, 2023
百度2021年语言与智能技术竞赛机器阅读理解Pytorch版baseline

项目说明: 百度2021年语言与智能技术竞赛机器阅读理解Pytorch版baseline 比赛链接:https://aistudio.baidu.com/aistudio/competition/detail/66?isFromLuge=true 官方的baseline版本是基于paddlepadd

周俊贤 54 Nov 23, 2022
Adversarial Reweighting for Partial Domain Adaptation

Adversarial Reweighting for Partial Domain Adaptation Code for paper "Xiang Gu, Xi Yu, Yan Yang, Jian Sun, Zongben Xu, Adversarial Reweighting for Par

12 Dec 01, 2022
[ICCV 2021] Relaxed Transformer Decoders for Direct Action Proposal Generation

RTD-Net (ICCV 2021) This repo holds the codes of paper: "Relaxed Transformer Decoders for Direct Action Proposal Generation", accepted in ICCV 2021. N

Multimedia Computing Group, Nanjing University 80 Nov 30, 2022
🙄 Difficult algorithm, Simple code.

🎉TensorFlow2.0-Examples🎉! "Talk is cheap, show me the code." ----- Linus Torvalds Created by YunYang1994 This tutorial was designed for easily divin

1.7k Dec 25, 2022
A PyTorch-based library for semi-supervised learning

News If you want to join TorchSSL team, please e-mail Yidong Wang ([email protected]<

1k Jan 06, 2023
GeoTransformer - Geometric Transformer for Fast and Robust Point Cloud Registration

Geometric Transformer for Fast and Robust Point Cloud Registration PyTorch imple

Zheng Qin 220 Jan 05, 2023
Code for CPM-2 Pre-Train

CPM-2 Pre-Train Pre-train CPM-2 此分支为110亿非 MoE 模型的预训练代码,MoE 模型的预训练代码请切换到 moe 分支 CPM-2技术报告请参考link。 0 模型下载 请在智源资源下载页面进行申请,文件介绍如下: 文件名 描述 参数大小 100000.tar

Tsinghua AI 136 Dec 28, 2022