Skip to content

Instantly share code, notes, and snippets.

@jnalley
Created February 1, 2020 01:10
Show Gist options
  • Save jnalley/61e99a08be341707bd2266d6f1fb74a1 to your computer and use it in GitHub Desktop.
Save jnalley/61e99a08be341707bd2266d6f1fb74a1 to your computer and use it in GitHub Desktop.
A singleton "like" Python snippet using lru_cache
#!/usr/bin/env python3
from functools import lru_cache
class Singleton:
@lru_cache
def __new__(cls, *args, **kwargs):
return super().__new__(cls)
def __init__(self, *args, **kwargs):
pass
if __name__ == "__main__":
s1 = Singleton(foo="bar")
s2 = Singleton(foo="bar")
assert s1 is s2
# A single instance of the class is returned as long as the class is
# instantiated with the same arguments.
print(f"{id(s1)} is {id(s2)}")
# But, if different arguments are passed a new instance is created.
s3 = Singleton(baz="bam")
assert s1 is not s3
print(f"{id(s1)} is not {id(s3)}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment