Singleton Pattern in Python
Level 5390 keystrokes
This implements the Singleton pattern using __new__ to ensure only one instance exists.
Python code
# Singleton: every call returns the same single instance1class Singleton: # _instance stores the single instance (class variable)2 _instance = None # _initialized tracks if __init__ has run3 _initialized = False4 # __new__ controls instance creation5 def __new__(cls): # Check if instance doesn't exist yet6 if cls._instance is None: # Create the single instance using parent's __new__7 cls._instance = super().__new__(cls) # Return the existing or new instance8 return cls._instance9 # __init__ runs on every Singleton() call, so guard the setup10 def __init__(self): # Only initialize if not already done11 if not Singleton._initialized: # Set initial value12 self.value = 0 # Mark as initialized to prevent re-init13 Singleton._initialized = True14 # Create first instance15s1 = Singleton()# Modify value on s116s1.value = 42# Same instance again; the flag keeps value from resetting to 017s2 = Singleton()# Both have same value since they're the same instance18print(f"s1.value={s1.value}, s2.value={s2.value}")# Verify they are the same object19print(f"Same instance: {s1 is s2}")Output
s1.value=42, s2.value=42 Same instance: True
Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
_× 19.× 12=× 10(× 8)× 8:× 6"× 4{× 3}× 3,× 1