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 instance
1class Singleton:
# _instance stores the single instance (class variable)
2 _instance = None
# _initialized tracks if __init__ has run
3 _initialized = False
4
# __new__ controls instance creation
5 def __new__(cls):
# Check if instance doesn't exist yet
6 if cls._instance is None:
# Create the single instance using parent's __new__
7 cls._instance = super().__new__(cls)
# Return the existing or new instance
8 return cls._instance
9
# __init__ runs on every Singleton() call, so guard the setup
10 def __init__(self):
# Only initialize if not already done
11 if not Singleton._initialized:
# Set initial value
12 self.value = 0
# Mark as initialized to prevent re-init
13 Singleton._initialized = True
14
# Create first instance
15s1 = Singleton()
# Modify value on s1
16s1.value = 42
# Same instance again; the flag keeps value from resetting to 0
17s2 = Singleton()
# Both have same value since they're the same instance
18print(f"s1.value={s1.value}, s2.value={s2.value}")
# Verify they are the same object
19print(f"Same instance: {s1 is s2}")

Output

s1.value=42, s2.value=42
Same instance: True
Practice typing this code

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

More Python examples at level 5

← Python typing practice