Singleton Pattern in Python

Level 5235 keystrokes

This implements the singleton pattern using __new__. Only one instance exists and all calls return the same object.

Python code

# Define singleton class
1class Singleton:
# Class variable to store the single instance
2 _instance = None
3
# __new__ controls instance creation
4 def __new__(cls):
# Check if instance already exists
5 if cls._instance is None:
# Create new instance using parent __new__
6 cls._instance = super().__new__(cls)
# Initialize instance attribute
7 cls._instance.value = 0
# Return the single instance
8 return cls._instance
9
# Create first reference to singleton
10a = Singleton()
# Create second reference - same object
11b = Singleton()
# Modify value through first reference
12a.value = 42
# Print value through second reference - same value
13print(b.value)
# Verify both references point to same object
14print(a is b)

Output

42
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.

  • _× 13
  • .× 8
  • (× 7
  • )× 7
  • =× 6
  • :× 3

More Python examples at level 5

← Python typing practice