Python Singleton Pattern
The Singleton Pattern is a commonly used software design pattern that ensures a class has only one instance and provides a global access point to obtain that instance.
Core Concepts
Imagine the CEO position in a company - the entire company can have only one CEO; no matter which department needs to report to the CEO, they all access the same CEO object. The Singleton Pattern is the "CEO position management mechanism" in the programming world.
Why Do We Need the Singleton Pattern?
In real development, sometimes a single instance of an object is enough, for example:
- Configuration manager: The entire application shares one set of configuration
- Database connection pool: Avoid repeatedly creating connections, saving resources
- Logger: Ensure all logs are written to the same file
- Caching system: Manage cached data uniformly
Implementation Methods of the Singleton Pattern
Python provides several ways to implement the Singleton Pattern; let's explore them from simple to complex.
Method 1: Using a Module (the simplest way)
Python modules are naturally singletons. When a module is imported, it is initialized once, and subsequent imports use the same instance.
Example
singleton_module.py
class
DatabaseConnection:
def
init
(
self
)
:
self
.
connection_string
=
"database://localhost:5432/mydb"
(
"Database connection created"
)
def
query
(
self
,
sql
)
:
return
f
"Executing query: {sql}"
Create the singleton instance
db_instance
=
DatabaseConnection
(
)
Use it in other files:
from singleton_module import db_instance
result = db_instance.query("SELECT * FROM users")
Method 2: Using __new__ Method
By overriding __new__ method to control the instance creation process.
Example
class
Singleton:
_instance
=
None
def
new
(
cls
,
*args
,
**kwargs
)
:
If the instance does not exist, create a new one
if
not
cls._instance:
cls._instance
=
super
(
)
.
new
(
cls
)
(
"Creating a new singleton instance"
)
else
:
(
"Returning the existing singleton instance"
)
return
cls._instance
def
init
(
self
,
name
)
:
Note:init Called every time
self
.
name
=
name
(
f
"Initializing instance, name: {name}"
)
Test code
(
"=== Testing the Singleton Pattern ==="
)
s1
=
Singleton
(
"First instance"
)
s2
=
Singleton
(
"Second instance"
)
(
f
"ID of s1: {id(s1)}"
)
(
f
"ID of s2: {id(s2)}"
)
(
f
"Are s1 and s2 the same object? {s1 is s2}"
)
(
f
"s1 name: {s1.name}"
)
(
f
"s2 name: {s2.name}"
)
Note: "Second instance" will be shown here
Output result:
=== 测试单例模式 ===
创建新的单例实例
初始化实例,名称: 第一个实例
返回已存在的单例实例
初始化实例,名称: 第二个实例
s1 的 ID: 140245678945600
s2 的 ID: 140245678945600
s1 和 s2 是同一个对象吗? True
s1 名称: 第二个实例
s2 名称: 第二个实例
Method 3: Using a Decorator
Create a general-purpose singleton decorator that can easily turn any class into a singleton.
Example
def
singleton
(
cls
)
:
"""Singleton decorator"""
instances
=
{
}
def
get_instance
(
*args
,
**kwargs
)
:
If the class has no instance yet, create a new one
if
cls
not
in
instances:
instances
[
cls
]
=
cls
(
*args
,
**kwargs
)
(
f
"Creating {cls.name} new instance"
)
else
:
(
f
"Returning existing {cls.name} instance"
)
return
instances
[
cls
]
return
get_instance
@
singleton
class
ConfigurationManager:
def
init
(
self
)
:
self
.
settings
=
{
}
self
.
load_default_settings
(
)
def
load_default_settings
(
self
)
:
self
.
settings
=
{
"app_name"
:
"My App"
,
"version"
:
"1.0.0"
,
"debug_mode"
:
True
}
def
get_setting
(
self
,
key
)
:
return
self
.
settings
.
get
(
key
)
def
set_setting
(
self
,
key
,
value
)
:
self
.
settings
[
key
]
=
value
Test code
(
"\n=== Testing Decorator Singleton ==="
)
config1
=
ConfigurationManager
(
)
config2
=
ConfigurationManager
(
)
config1.
set_setting
(
"theme"
,
"dark"
)
(
f
"config1 theme: {config1.get_setting('theme')}"
)
(
f
"config2 theme: {config2.get_setting('theme')}"
)
Both instances share the same configuration
Method 4: Using a Metaclass (advanced usage)
A metaclass can control the class creation process and is another powerful way to implement the Singleton Pattern.
Example
class
SingletonMeta
(
type
)
:
"""Singleton metaclass"""
_instances
=
{
}
def
call
(
cls
,
*args
,
**kwargs
)
:
If the class has no instance yet, create a new one
if
cls
not
in
cls._instances:
instance
=
super
(
)
.
call
(
*args
,
**kwargs
)
cls._instances
[
cls
]
=
instance
(
f
"Metaclass: creating {cls.name} new instance"
)
else
:
(
f
"Metaclass: returning existing {cls.name} instance"
)
return
cls._instances
[
cls
]
class
Logger
(
metaclass
=
SingletonMeta
)
:
def
init
(
self
,
log_file
=
"app.log"
)
:
self
.
log_file
=
log_file
self
.
logs
=
[
]
(
f
"Logger initialized, file: {log_file}"
)
def
log
(
self
,
message
)
:
log_entry
=
f
"[{self.get_timestamp()}] {message}"
self
.
logs
.
append
(
log_entry
)
(
f
"Logging: {log_entry}"
)
return
log_entry
def
get_timestamp
(
self
)
:
from
datetime
import
datetime
return
datetime
.
now
(
)
.
strftime
(
"%Y-%m-%d %H:%M:%S"
)
def
get_logs
(
self
)
:
return
self
.
logs
.
copy
(
)
Test code
(
"\n=== Testing Metaclass Singleton ==="
)
logger1
=
Logger
(
"application.log"
)
logger2
=
Logger
(
"different.log"
)
This filename will be ignored
logger1.
log
(
"System startup"
)
logger2.
log
(
"User login"
)
(
f
"logger1 log count: {len(logger1.get_logs())}"
)
(
f
"logger2 log count: {len(logger2.get_logs())}"
)
(
f
"Are they the same logger? {logger1 is logger2}"
)
Application Scenarios of the Singleton Pattern
Let's look at the application of the Singleton Pattern in a real project through a complete example.
Practical Case: Application Configuration Manager
Example
class
AppConfig:
_instance
=
None
def
new
(
cls
)
:
if
cls._instance
is
None
:
cls._instance
=
super
(
)
.
new
(
cls
)
cls._instance._initialized
=
False
return
cls._instance
def
init
(
self
)
:
Prevent repeated initialization
if
not
self
._initialized:
self
.
config_data
=
{
}
self
.
load_config
(
)
self
._initialized
=
True
def
load_config
(
self
)
:
"""Simulate loading configuration from a config file"""
self
.
config_data
=
{
"database"
:
{
"host"
:
"localhost"
,
"port"
:
5432
,
"name"
:
"myapp_db"
}
,
"server"
:
{
"host"
:
"0.0.0.0"
,
"port"
:
8000
}
,
"features"
:
{
"cache_enabled"
:
True
,
"debug_mode"
:
False
}
}
(
"Configuration loaded"
)
def
get
(
self
,
key_path
,
default
=
None
)
:
"""Get a config value by path, e.g. 'database.host'"""
keys
=
key_path.
split
(
'.'
)
value
=
self
.
config_data
try
:
for
key
in
keys:
value
=
value
[
key
]
return
value
except
(
KeyError
,
TypeError
)
:
return
default
def
set
(
self
,
key_path
,
value
)
:
"""Set a config value"""
keys
=
key_path.
split
(
'.'
)
config
=
self
.
config_data
Iterate to the one before the last key
for
key
in
keys
[
:-
1
]
:
if
key
not
in
config:
config
[
key
]
=
{
}
config
=
config
[
key
]
Set the final value
config
[
keys
[
1
]
]
=
value
(
f
"Configuration updated: {key_path} = {value}"
)
Usage examples
def
demonstrate_config_usage
(
)
:
(
"\n=== Configuration Manager Demo ==="
)
Get the configuration manager instance in different places
config1
=
AppConfig
(
)
config2
=
AppConfig
(
)
(
f
"Are they the same configuration manager? {config1 is config2}"
)
Read configuration
db_host
=
config1.
get
(
"database.host"
)
server_port
=
config1.
get
(
"server.port"
)
(
f
"Database host: {db_host}"
)
(
f
"Server port: {server_port}"
)
Update configuration
config2.
set
(
"database.host"
,
"192.168.1.100"
)
config2.
set
(
"features.debug_mode"
,
True
)
Verify configuration synchronization
(
f
"config1 DB host: {config1.get('database.host')}"
)
(
f
"config1 debug mode: {config1.get('features.debug_mode')}"
)
Run the demo
demonstrate_config_usage
(
)
Caveats of the Singleton Pattern
Advantages
- Resource saving: Avoid repeatedly creating objects, saving memory and system resources
- Data consistency: All clients use the same instance, ensuring data consistency
- Global access: Provides a unified access point for easy management
Disadvantages
- Global state: A singleton holds global state, which may cause unexpected side effects
- Difficult testing: Due to global state, unit testing can become complicated
- Violates the Single Responsibility Principle: The singleton class must both manage its own business logic and control instantiation
Best Practices
Example
class
ThreadSafeSingleton:
"""Thread-safe Singleton Pattern"""
_instance
=
None
_lock
=
threading
.
Lock
(
)
def
new
(
cls
)
:
if
cls._instance
is
None
:
with
cls._lock:
Double-checked locking
if
cls._instance
is
None
:
cls._instance
=
super
(
)
.
new
(
cls
)
(
"Creating a thread-safe singleton instance"
)
return
cls._instance
def
init
(
self
)
:
Ensure initialization happens only once
if
not
hasattr
(
self
,
'_initialized'
)
:
self
.
data
=
{
}
self
._initialized
=
True
Exercises and Reflection
Hands-on Exercises
-
Implement a Cache Manager:
-
Improve the Configuration Manager:
Reflection Questions
- In what situations should the Singleton Pattern be avoided?
- How does the Singleton Pattern affect code testability?
- What should you pay attention to when using the Singleton Pattern in a multithreaded environment?
Summary
The Singleton Pattern is a very important design pattern in Python; by ensuring a class has only one instance, it provides unified resource management. Through modules,__new__ methods, decorators, and metaclasses, we can choose the most suitable approach according to specific needs.
Remember, although the Singleton Pattern is practical, use it cautiously and avoid overuse that leads to code coupling and testing difficulties. In real projects, using the Singleton Pattern appropriately can greatly improve code quality and maintainability.