Skip to main content

Simple Observer Pattern implementation

Project description

observer-pattern

Simple Observer Pattern Implementation

from observer_pattern import Observable

counter = 0

def plus_n(n):
    global counter
    counter += n

def plus_2n(n):
    global counter
    counter += 2*n

def plus_3n(n):
    global counter
    counter += 3*n

observable = Observable()
observable.subscribe(plus_n)
observable.subscribe(plus_2n)
observable.subscribe(plus_3n)
observable.notify(2)
observable.unsubscribe(plus_3n)
observable.notify(5)

print(counter) # 27
print(len(observable)) # 2

You can pass any number of args and kwargs

def print_product(a, b):
    print(a * b)

observable = Observable()
observable.subscribe(print_product)
observable.notify(3, b=5) # 15
print(print_product in observable) # True

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

observer_pattern-1.0.0.tar.gz (14.2 kB view hashes)

Uploaded Source

Built Distribution

observer_pattern-1.0.0-py3-none-any.whl (14.3 kB view hashes)

Uploaded Python 3

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page