Skip to content

The subject / observer pattern

Documentation on how to use this can be found here

Module observer.

The MIT License

Copyright 2022 Thomas Lehmann.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

DefaultObserver (Observer)

A simple observer class.

Source code in responsive/observer.py
class DefaultObserver(Observer):
    """A simple observer class."""

    def __init__(self):
        """Initializing empty list of reveived updates."""
        super().__init__()
        self.__updates = []
        self.__interests = {}

    def update(self, subject: object, *args: Any, **kwargs: Any) -> None:
        """Called when the subject has been changed.

        Args:
            subject (object): the one who does the notification.
            *args (Any): optional positional arguments
            **kwargs (Any): optional key/value arguments
        """
        self.__updates.append((subject, args, kwargs))

    def set_interests(self, interests: dict[str, Callable[[Any], bool]]) -> None:
        """Change interests.

        Args:
            interests (dict[str, Callable[[Any], bool]]): new interests.
        """
        self.__interests = interests

    def get_interests(self) -> dict[str, Callable[[Any], bool]]:
        """Telling a subject the interests.

        Returns:
            dictionary with names and functions (idea: `is_relevant(value)`)
        """
        return self.__interests

    def __iter__(self):
        """Allows iterating over the updates of this observer."""
        return iter(self.__updates)

    def clear(self):
        """Delete all recently updated."""
        self.__updates.clear()

    def get_count_updates(self):
        """Provide number of updates."""
        return len(self.__updates)

__init__(self) special

Initializing empty list of reveived updates.

Source code in responsive/observer.py
def __init__(self):
    """Initializing empty list of reveived updates."""
    super().__init__()
    self.__updates = []
    self.__interests = {}

__iter__(self) special

Allows iterating over the updates of this observer.

Source code in responsive/observer.py
def __iter__(self):
    """Allows iterating over the updates of this observer."""
    return iter(self.__updates)

clear(self)

Delete all recently updated.

Source code in responsive/observer.py
def clear(self):
    """Delete all recently updated."""
    self.__updates.clear()

get_count_updates(self)

Provide number of updates.

Source code in responsive/observer.py
def get_count_updates(self):
    """Provide number of updates."""
    return len(self.__updates)

get_interests(self)

Telling a subject the interests.

Returns:

Type Description
dictionary with names and functions (idea

is_relevant(value))

Source code in responsive/observer.py
def get_interests(self) -> dict[str, Callable[[Any], bool]]:
    """Telling a subject the interests.

    Returns:
        dictionary with names and functions (idea: `is_relevant(value)`)
    """
    return self.__interests

set_interests(self, interests)

Change interests.

Parameters:

Name Type Description Default
interests dict[str, Callable[[Any], bool]]

new interests.

required
Source code in responsive/observer.py
def set_interests(self, interests: dict[str, Callable[[Any], bool]]) -> None:
    """Change interests.

    Args:
        interests (dict[str, Callable[[Any], bool]]): new interests.
    """
    self.__interests = interests

update(self, subject, *args, **kwargs)

Called when the subject has been changed.

Parameters:

Name Type Description Default
subject object

the one who does the notification.

required
*args Any

optional positional arguments

()
**kwargs Any

optional key/value arguments

{}
Source code in responsive/observer.py
def update(self, subject: object, *args: Any, **kwargs: Any) -> None:
    """Called when the subject has been changed.

    Args:
        subject (object): the one who does the notification.
        *args (Any): optional positional arguments
        **kwargs (Any): optional key/value arguments
    """
    self.__updates.append((subject, args, kwargs))

DoNothingObserver (Observer)

Does nothing (more of a test).

Source code in responsive/observer.py
class DoNothingObserver(Observer):
    """Does nothing (more of a test)."""

    def update(self, subject: object, *args: Any, **kwargs: Any) -> None:
        """Called when the subject has been changed.

        Args:
            subject (object): the one who does the notification.
            *args (Any): optional positional arguments
            **kwargs (Any): optional key/value arguments
        """

update(self, subject, *args, **kwargs)

Called when the subject has been changed.

Parameters:

Name Type Description Default
subject object

the one who does the notification.

required
*args Any

optional positional arguments

()
**kwargs Any

optional key/value arguments

{}
Source code in responsive/observer.py
def update(self, subject: object, *args: Any, **kwargs: Any) -> None:
    """Called when the subject has been changed.

    Args:
        subject (object): the one who does the notification.
        *args (Any): optional positional arguments
        **kwargs (Any): optional key/value arguments
    """

Observer

Observer from the subject/observer pattern.

Source code in responsive/observer.py
class Observer:
    """Observer from the subject/observer pattern."""

    def update(self, subject: object, *args: Any, **kwargs: Any):
        """Called when related subject has changed.

        Args:
            subject (object): the one who does the notification.
            *args (Any): optional positional arguments
            **kwargs (Any): optional key/value arguments
        """
        raise NotImplementedError()

    def get_interests(self) -> dict[str, Callable[[Any], bool]]:  # pylint: disable=no-self-use
        """Telling a subject the interest. When providing {} then all changes
        are of interest (default) otherwise the interest is related to a name
        and a function for the value telling - when the name is related to the
        change - whether the value is of interest. If not interest does not
        match the notification (updated) is not done.

        Returns:
            dictionary with names and functions (idea: `is_relevant(value)`)
        """
        return {}

get_interests(self)

Telling a subject the interest. When providing {} then all changes are of interest (default) otherwise the interest is related to a name and a function for the value telling - when the name is related to the change - whether the value is of interest. If not interest does not match the notification (updated) is not done.

Returns:

Type Description
dictionary with names and functions (idea

is_relevant(value))

Source code in responsive/observer.py
def get_interests(self) -> dict[str, Callable[[Any], bool]]:  # pylint: disable=no-self-use
    """Telling a subject the interest. When providing {} then all changes
    are of interest (default) otherwise the interest is related to a name
    and a function for the value telling - when the name is related to the
    change - whether the value is of interest. If not interest does not
    match the notification (updated) is not done.

    Returns:
        dictionary with names and functions (idea: `is_relevant(value)`)
    """
    return {}

update(self, subject, *args, **kwargs)

Called when related subject has changed.

Parameters:

Name Type Description Default
subject object

the one who does the notification.

required
*args Any

optional positional arguments

()
**kwargs Any

optional key/value arguments

{}
Source code in responsive/observer.py
def update(self, subject: object, *args: Any, **kwargs: Any):
    """Called when related subject has changed.

    Args:
        subject (object): the one who does the notification.
        *args (Any): optional positional arguments
        **kwargs (Any): optional key/value arguments
    """
    raise NotImplementedError()

OutputObserver (Observer)

Output a line for each update. Default output function is print.

Source code in responsive/observer.py
class OutputObserver(Observer):
    """Output a line for each update. Default output function is `print`."""

    def __init__(self, output_function=print):
        """Initialize observer with output function."""
        self.__output_function = output_function

    def update(self, subject: object, *args: Any, **kwargs: Any) -> None:
        """Called when the subject has been changed.

        Args:
            subject (object): the one who does the notification.
            *args (Any): optional positional arguments
            **kwargs (Any): optional key/value arguments
        """
        self.__output_function(
            f"subject with id {id(subject)} has notified with {args} and {kwargs}"
        )

__init__(self, output_function=<built-in function print>) special

Initialize observer with output function.

Source code in responsive/observer.py
def __init__(self, output_function=print):
    """Initialize observer with output function."""
    self.__output_function = output_function

update(self, subject, *args, **kwargs)

Called when the subject has been changed.

Parameters:

Name Type Description Default
subject object

the one who does the notification.

required
*args Any

optional positional arguments

()
**kwargs Any

optional key/value arguments

{}
Source code in responsive/observer.py
def update(self, subject: object, *args: Any, **kwargs: Any) -> None:
    """Called when the subject has been changed.

    Args:
        subject (object): the one who does the notification.
        *args (Any): optional positional arguments
        **kwargs (Any): optional key/value arguments
    """
    self.__output_function(
        f"subject with id {id(subject)} has notified with {args} and {kwargs}"
    )

Module subject.

.. The MIT License

Copyright 2022 Thomas Lehmann.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Subject

Subject from the subject/observer pattern.

Source code in responsive/subject.py
class Subject:
    """Subject from the subject/observer pattern."""

    def __init__(self):
        """Initialize empty list of observers."""
        self.__observers: list[Observer] = []

    def notify(self, *args: Any, **kwargs: Any):
        """Updating all observers.

        Args:
            *args (Any): optional positional arguments
            **kwargs (Any): optional key/value arguments
        """
        for observer in self.__observers:
            interests = observer.get_interests()
            if len(interests) == 0:  # pylint: disable=compare-to-zero
                observer.update(self, *args, **kwargs)
            else:
                for key, value in kwargs.items():
                    if key in interests and interests[key](value):
                        observer.update(self, *args, **kwargs)
                        break

    def add_observer(self, observer: Observer) -> None:
        """Adding observer to list.

        Args:
            observer (obj): object that will be notified.
        """
        if observer not in self.__observers:
            self.__observers.append(observer)

    def remove_observer(self, observer: Observer) -> None:
        """Remove observer from list.

        Args:
            observer (obj): object that don't want to get updated anymore.
        """
        self.__observers.remove(observer)

__init__(self) special

Initialize empty list of observers.

Source code in responsive/subject.py
def __init__(self):
    """Initialize empty list of observers."""
    self.__observers: list[Observer] = []

add_observer(self, observer)

Adding observer to list.

Parameters:

Name Type Description Default
observer obj

object that will be notified.

required
Source code in responsive/subject.py
def add_observer(self, observer: Observer) -> None:
    """Adding observer to list.

    Args:
        observer (obj): object that will be notified.
    """
    if observer not in self.__observers:
        self.__observers.append(observer)

notify(self, *args, **kwargs)

Updating all observers.

Parameters:

Name Type Description Default
*args Any

optional positional arguments

()
**kwargs Any

optional key/value arguments

{}
Source code in responsive/subject.py
def notify(self, *args: Any, **kwargs: Any):
    """Updating all observers.

    Args:
        *args (Any): optional positional arguments
        **kwargs (Any): optional key/value arguments
    """
    for observer in self.__observers:
        interests = observer.get_interests()
        if len(interests) == 0:  # pylint: disable=compare-to-zero
            observer.update(self, *args, **kwargs)
        else:
            for key, value in kwargs.items():
                if key in interests and interests[key](value):
                    observer.update(self, *args, **kwargs)
                    break

remove_observer(self, observer)

Remove observer from list.

Parameters:

Name Type Description Default
observer obj

object that don't want to get updated anymore.

required
Source code in responsive/subject.py
def remove_observer(self, observer: Observer) -> None:
    """Remove observer from list.

    Args:
        observer (obj): object that don't want to get updated anymore.
    """
    self.__observers.remove(observer)