coding >> python singleton (75 views)

A version of python singleton pattern, it is not very pretty and breaks a bunch of pep 20, but in some cases is useful.

Singleton Pattern

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Singleton(object):
    __instance = {}
 
    def __new__(cls, *args, **kwargs):
        if cls.__name__ not in cls.__instance:
            cls.__instance[cls.__name__] = super(cls.__class__, cls).__new__(cls, *args, **kwargs)
            setattr(cls.__instance[cls.__name__], '__init', True)
        else:
            setattr(cls.__instance[cls.__name__], '__init', False)
        return cls.__instance[cls.__name__]
 
    def __init__(self, *args, **kwargs):
        if getattr(self, '__init', False):
            # do initialization here
            pass

Alternatively consider the Borg Pattern below.

Borg Pattern

1
2
3
4
5
6
7
8
class Borg(object):
    __state = {}
 
    def __init__(self):
        self.__dict__ = self.__state
        if 'my_data' not in self.__dict__:
            # do initialization here, i.e.:
            self.my_data = 'initialize your data'

 

Leave a Comment or Trackback from your own site.

2 Responses to “python singleton”

  1. Spam engine says:

    Thanks to my father who informed me regarding this web
    site, this website is truly remarkable.

  2. Once the card reaches your hand down the line, you will then have the option of playing the zombie at any given time in order to create problems for your opponent(s). After all, the object of the game is to be the LONE survivor.

Leave a Reply