Richard Foo Richard Foo - 4 years ago 207
Python Question

Borg Design Pattern

I am trying to learn design patterns in Python. The recommended approach for implementing global variables is through the Borg pattern.

class Borg:
__shared_state = {}
def __init__(self):
self.__dict__ = self.__shared_state

This seems to be a dictionary. How would I store more complicated data structures, say a Pandas dataframe or a custom class, to be used by globally?

Answer Source

Actually, this is not the recommended approach, and I have never seen it used in real code.

The recommended approach is to use a module as a module already has a "global" namespace (see this answer for more info on globals(), locals(), and vars()).

However, in the interests of understanding:

What you have so far is only a basic framework for shared state at the instance level. What you need now is the rest of the state you want to track:

class Config(Borg):

    def __init__(self, config_file):
        super(Config, self).__init__()
        # load and parse file, saving settings to `self`

One disadvantage to this method is that you can have several instances consuming memory that all know the same thing. (Not much memory, true.)

Another method of accomplishing "shared state" is to only create one instance, and then have the class always return that same instance -- otherwise known as a singleton.

class Config(object):

    the_one = None

    def __new__(cls, config):
        if cls.the_one is None:
            cls.the_one = Super(Config, cls).__new__(cls)
            # load and parse file, saving settings to `cls.the_one`
        return cls.the_one

Either method would result in the following:

>>> config = Config('my_config_file.cfg')
>>> config.screen_size
# whatever was saved during the loading and parsing of the config file
# for 'screen_size'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download