libb.singleton
- singleton(cls)[source]
Decorator that enforces singleton pattern on a class.
Ensures only one instance of the decorated class can exist. All calls to the class return the same instance.
- Parameters:
cls (type) – The class to convert to a singleton.
- Return type:
- Returns:
The single instance of the class.
Basic Usage:
>>> @singleton ... class Foo: ... _x = 100 ... _y = 'y' ... attrs('x', 'y') >>> F = Foo >>> F() is F() is F True >>> id(F()) == id(F()) True
Shared State:
>>> f = F() >>> f.x == F().x == f.x == 100 True >>> F.x = 50 >>> f.x == F().x == F.x == 50 True
Deep Copy Behavior:
>>> import copy >>> fc = copy.deepcopy(f) >>> FC = copy.deepcopy(F) >>> fc.y==f.y==F.y==FC.y=='y' True