File: observable.py

package info (click to toggle)
git-cola 2.10-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 4,444 kB
  • ctags: 3,201
  • sloc: python: 20,539; sh: 311; makefile: 310; tcl: 48; xml: 27
file content (30 lines) | stat: -rw-r--r-- 1,098 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# Copyright (c) 2008 David Aguilar
"""This module provides the Observable class"""
from __future__ import division, absolute_import, unicode_literals


class Observable(object):
    """Handles subject/observer notifications."""
    def __init__(self):
        self.notification_enabled = True
        self.observers = {}

    def add_observer(self, message, observer):
        """Add an observer for a specific message."""
        observers = self.observers.setdefault(message, set())
        observers.add(observer)

    def remove_observer(self, observer):
        """Remove an observer."""
        for message, observers in self.observers.items():
            if observer in observers:
                observers.remove(observer)

    def notify_observers(self, message, *args, **opts):
        """Pythonic signals and slots."""
        if not self.notification_enabled:
            return
        # observers can remove themselves during their callback so grab a copy
        observers = set(self.observers.get(message, set()))
        for method in observers:
            method(*args, **opts)