A clean collection of Python Singleton implementations — from basics to thread-safe and async-compatible versions.
Singleton is a classic design pattern that ensures a class has only one instance, providing a global point of access.
In this repository, you'll find multiple real-world Singleton implementations in Python — including solutions for inheritance, multithreading, and asynchronous environments.
✅ Simple and intuitive examples
✅ Supports inheritance via metaclass
✅ Thread-safe implementation
✅ Fully async-compatible Singleton
✅ Easy to test and extend
python-singleton-patterns/
├── singleton_basic.py # Classic Singleton using __new__
├── singleton_inheritance.py # Inheritable Singleton using Metaclass
├── singleton_threadsafe.py # Thread-safe Singleton with Lock
├── singleton_async.py # Async Singleton for asyncio
├── singleton_test.py # Unified test runner for all versions
├── requirements.txt # (Optional) Dependencies if needed
└── README.md # You're here.
Clone the repo and run the tests:
git clone https://github.com/your-username/python-singleton-patterns.git
cd python-singleton-patterns
python singleton_test.py
from singleton_basic import Singleton
a = Singleton()
b = Singleton()
print(a is b) # True
from singleton_inheritance import Singleton
class Service(Singleclass):
pass
s1 = Service()
s2 = Service()
print(s1 is s2) # True
from singleton_threadsafe import Singleton
s1 = Singleton()
s2 = Singleton()
print(s1 is s2) # Always True (even in threads)
from singleton_async import AsyncSingleton
import asyncio
async def run():
a = await AsyncSingleton()
b = await AsyncSingleton()
print(a is b) # True
asyncio.run(run())
Sample from singleton_test.py
:
🔹 Testing Basic Singleton
[Basic] a is b: True
🔹 Testing Inheritance-Safe Singleton (Metaclass)
[Inheritance] a is b: True
🔹 Testing Thread-Safe Singleton
[Thread-safe] Unique instance count: 1
[Thread-safe] All instances are the same: True
🔹 Testing Async Singleton
[Async] Unique instance count: 1
[Async] All async instances are the same: True
__new__()
vs__call__()
in metaclasses- Python
metaclass
mechanics threading.Lock
for thread-safetyasyncio.Lock
for async contexts- Singleton-friendly inheritance
Pull requests and forks are welcome!
If you find a new use-case or edge-case Singleton, feel free to add it.
This project is licensed under the MIT License.
Use freely, modify boldly.
Don’t forget to Star 🌟 the repository to help others find it.