The borg module

The borg module contains the Borg class which provides an implementation of the Borg design pattern, which is a Singleton like pattern for Python.

The Borg class

Inheritance diagram of pyamp.patterns.borg.Borg

class pyamp.patterns.borg.Borg(*args, **kwargs)[source]

The Borg class implements the Borg design pattern which provides a singleton like pattern for Python.

A Borg object can be accessed by calling the getInstance() function. This functions returns an instance of the Borg class which stores its state between successive calls to get the Borg object.

Instances of the Borg class can implement the init() function which is called when the Borg class is first created and initialized. This allows the concrete Borg classes to set up the initial state for their object.

Example:

class Example(Borg):
    def init(self, *args, **kwargs):
        self.x = kwargs['x']

class First:
    def __init__(self):
        # An example of passing a value to the Borg instance
        b = Example(x=200)
        print "First, b.x:", b.x

class Second:
    def __init__(self):
        # Optionally could use Borg.getInstance()
        b = Example.getInstance()
        print "Second, b.x:", b.x
        b.x = 500

if __name__ == '__main__':
    First()
    Second()

    b = Example.getInstance()
    print "Third, b.x:", b.x

    # Prints:
    #    First, b.x: 200
    #    Second, b.x: 200
    #    Third, b.x: 500
  • args – The arguments
  • kwargs – The keyword arguments
classmethod getInstance()[source]

Get an instance of the Borg object.

getPrivateAttr(name, default=None)[source]

Return the value of a private class attribute.

  • name – The name of the private attribute
  • default – The value returned if the attribute does not exist
init(*args, **kwargs)[source]

This function is called the first time the class is initialized, and should be overridden by concrete subclasses.

  • args – The arguments
  • kwargs – The keyword arguments
setPrivateAttr(name, value)[source]

Set the value of a private class attribute.

  • name – The name of the private attribute
  • value – The value to set the attribute to

Table Of Contents

Previous topic

The interface module

Next topic

The decorators module

This Page