Skip to content

pattern.py

This module provides some common used patterns.

__all__ = ['Singleton'] module-attribute

Singleton

Bases: type

Singleton meta class.

Examples:

>>> class Test(object):
>>>     __metaclass__ = Singleton
>>>
>>>     def __init__(self):
>>>         pass
Source code in solnlib/pattern.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class Singleton(type):
    """Singleton meta class.

    Examples:
       >>> class Test(object):
       >>>     __metaclass__ = Singleton
       >>>
       >>>     def __init__(self):
       >>>         pass
    """

    def __init__(cls, name, bases, attrs):
        super().__init__(name, bases, attrs)
        cls._instance = None

    def __call__(cls, *args, **kwargs):
        if cls._instance is None:
            cls._instance = super().__call__(*args, **kwargs)
        return cls._instance

__call__(*args, **kwargs)

Source code in solnlib/pattern.py
37
38
39
40
def __call__(cls, *args, **kwargs):
    if cls._instance is None:
        cls._instance = super().__call__(*args, **kwargs)
    return cls._instance

__init__(name, bases, attrs)

Source code in solnlib/pattern.py
33
34
35
def __init__(cls, name, bases, attrs):
    super().__init__(name, bases, attrs)
    cls._instance = None