Borg or just a module with features

I was thinking about using the Singleton template in my project, so I searched StackOverflow to find a Python way to implement it. I found this question with the accepted answer, which said that "a module with functions (not a class) will serve as a singleton." On the other hand, the second answer suggested using the Borg template . For me, using a module is a simple and straightforward solution, so I would like to understand when it is best to use Borg.

+4
source share
4 answers

One singleton and module represent only one instance for the entire lifetime of the application. This instance is stored in the instance, even if it is not needed.

The borg pattern is a general condition. Each client class will create a new borg instance, but this instance will be deleted when it is no longer needed - this is a much more elegant approach.

It is also much easier to subclass or mock borg.

+3
source

The difference is that in the Borg template you will have different objects whose attributes are the same when using the module version, you will get one object (module).

Also, the object and the module are slightly different: you cannot parse modules, but you can parse classes. In addition, you can have operations on objects (>, <, +, -, etc.)

To be a little off topic: with some modification, the Borg template can be used as a very simple Multiton:

class Multiton(object): __shared_states = {} def __init__(self, name): if not self.__shared_states.has_key(name): self.__shared_states[name] = {} self.__dict__ = self.__shared_states[name] 
+3
source

Can you use a static class instead? SO Question

ie

 class Test(object): i = 3 # class (or static) variable @classmethod def g(cls, arg): # here we can use 'cls' instead of the class name (Test) if arg > cls.i: cls.i = arg # would the the same as Test.i = arg1 
+1
source

I have one use case where the borg pattern shines:

you cannot define a function at the module level as @property. If you want some common data (e.g. config) to return dynamic properties, you can get them from Borg and then write property methods.

+1
source

All Articles