Created
December 12, 2024 12:17
-
-
Save clairem-sl/04225860acf90ca16f7bfcb8d9310c9f to your computer and use it in GitHub Desktop.
Demo of Singleton in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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