Skip to content

Instantly share code, notes, and snippets.

@clairem-sl
Created December 12, 2024 12:17
Show Gist options
  • Select an option

  • Save clairem-sl/04225860acf90ca16f7bfcb8d9310c9f to your computer and use it in GitHub Desktop.

Select an option

Save clairem-sl/04225860acf90ca16f7bfcb8d9310c9f to your computer and use it in GitHub Desktop.
Demo of Singleton in Python
from __future__ import annotations
from typing import reveal_type
class MetaSingleton(type):
cached = None
def __call__(cls, *args, **kwargs):
if cls.cached is None:
cls.cached = super().__call__(*args, **kwargs)
return cls.cached
class Singleton(metaclass=MetaSingleton):
def __init__(self):
print("Instantiated")
ONE_TRUE_INSTANCE = Singleton()
def foo(a: int | type(ONE_TRUE_INSTANCE)) -> None:
reveal_type(a)
if isinstance(a, Singleton):
print("a is of type Singleton")
if a is ONE_TRUE_INSTANCE:
print("it is the ONE_TRUE_INSTANCE")
else:
print("a is an int (probably)")
foo(15)
CertainSingleton = Singleton()
OtherSingleton = Singleton()
foo(CertainSingleton)
foo(OtherSingleton)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment