Skip to content

Instantly share code, notes, and snippets.

@tsonglew
Last active July 31, 2018 03:20
Show Gist options
  • Save tsonglew/5014b1266b1bedabbdf4eeb3f4cf9366 to your computer and use it in GitHub Desktop.
Save tsonglew/5014b1266b1bedabbdf4eeb3f4cf9366 to your computer and use it in GitHub Desktop.
python3 singleton
# Method 1. with __new__ magic method
class Singleton:
def __new__(cls):
if not hasattr(cls, 'instance'):
cls.instance = super().__new__(cls)
return cls.instance
class TestSingletonNew(Singleton):
pass
# Method 2. with decorator
def singleton(cls, *args, **kwargs):
instances = {}
def _singleton():
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return _singleton
@singleton
class TestSingletonDeco:
pass
# Run Test
tsn1 = TestSingletonNew()
tsn2 = TestSingletonNew()
assert id(tsn1) == id(tsn2)
tsd1 = TestSingletonDeco()
tsd2 = TestSingletonDeco()
assert id(tsd1) == id(tsd2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment