# How to Manage the SQuADDS_DB Instance Using the SingletonMeta Pattern

> Learn to manage your SQuADDS_DB instance with the SingletonMeta pattern. Ensure centralized state and consistent resource use in your lfl-lab/squadds application.

- Repository: [Levenson-Falk Lab/squadds](https://github.com/lfl-lab/squadds)
- Tags: how-to-guide
- Published: 2026-03-06

---

**The SQuADDS_DB class in the lfl-lab/squadds repository uses the SingletonMeta metaclass to enforce a single, application-wide database instance, ensuring centralized state management and consistent resource utilization across all modules.**

When working with the SQuADDS (Superconducting Qubit and Device Design Database System) framework, managing the SQuADDS_DB instance using the SingletonMeta pattern is essential for maintaining coherent state across distributed components. This architectural choice guarantees that every reference to the database shares identical configuration, cached dataframes, and connection parameters.

## Understanding the SingletonMeta Metaclass

The SingletonMeta pattern is implemented in [`squadds/core/design_patterns.py`](https://github.com/lfl-lab/squadds/blob/main/squadds/core/design_patterns.py) as a reusable metaclass that controls instance creation.

### Implementation Details in design_patterns.py

The metaclass overrides `__call__` to intercept standard instantiation:

```python

# Conceptual implementation based on squadds/core/design_patterns.py

class SingletonMeta(type):
    _instances = {}
    
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

```

This mechanism stores created instances in the private `_instances` dictionary keyed by class. When `SQuADDS_DB()` is called, SingletonMeta checks for an existing entry and returns the cached object rather than constructing a new one.

## How SQuADDS_DB Implements the Singleton Pattern

The database class in [`squadds/core/db.py`](https://github.com/lfl-lab/squadds/blob/main/squadds/core/db.py) explicitly declares the metaclass to enroll in singleton behavior.

### Class Declaration and Shared State

```python

# From squadds/core/db.py

class SQuADDS_DB(metaclass=SingletonMeta):
    def __init__(self):
        self.selected_component = None
        self.dataframes = {}
        self.cached_files = []
        # ... additional initialization

```

Because SingletonMeta governs instantiation, every call to `SQuADDS_DB()` returns the identical Python object. This means:

- **State persistence**: Modifications to `selected_component` or `dataframes` in one module are immediately visible to all other modules
- **Resource efficiency**: Only one set of HTTP/Hugging Face client sessions and pandas dataframes exists in memory
- **Configuration consistency**: Database connection parameters set during initial import remain stable throughout the application lifecycle

## Practical Examples for Managing the SQuADDS_DB Singleton

### Verifying Singleton Behavior

Confirm that multiple instantiations reference the same object:

```python
from squadds.core.db import SQuADDS_DB

db_a = SQuADDS_DB()
db_b = SQuADDS_DB()

assert db_a is db_b, "Both variables must reference the identical singleton instance"
print("Singleton verified: shared state confirmed")

```

### Accessing Shared State Across Modules

Demonstrate state persistence between different code locations:

```python

# module_a.py

from squadds.core.db import SQuADDS_DB

db = SQuADDS_DB()
db.select_qubit("transmon")
print(f"Set qubit: {db.selected_qubit}")

# module_b.py (executed later in same process)

from squadds.core.db import SQuADDS_DB

db = SQuADDS_DB()
print(f"Retrieved qubit: {db.selected_qubit}")  # Output: transmon

```

### Resetting the Singleton Instance for Testing

Force re-initialization during unit tests or configuration changes:

```python
from squadds.core.db import SQuADDS_DB

# Create initial instance

original_db = SQuADDS_DB()
original_db.select_qubit("fluxonium")

# Reset the singleton by clearing the metaclass storage

SQuADDS_DB._instances.pop(SQuADDS_DB, None)

# Subsequent instantiation creates fresh object

fresh_db = SQuADDS_DB()
print(f"Fresh instance qubit: {fresh_db.selected_qubit}")  # Output: None

assert fresh_db is not original_db, "Fresh instance must differ from original"

```

## Thread Safety and Limitations

The SingletonMeta implementation in [`squadds/core/design_patterns.py`](https://github.com/lfl-lab/squadds/blob/main/squadds/core/design_patterns.py) provides single-process instance control but **does not include thread-safety mechanisms**. In multi-threaded environments, race conditions during initial instantiation could theoretically create multiple instances.

For thread-safe singleton management, implement external locking:

```python
import threading
from squadds.core.db import SQuADDS_DB

singleton_lock = threading.Lock()

with singleton_lock:
    db = SQuADDS_DB()

```

Additionally, the singleton pattern persists for the lifetime of the Python process. While the `_instances.pop()` technique enables resetting, improper use can lead to state leakage between unrelated application components.

## Summary

- **SingletonMeta** in [`squadds/core/design_patterns.py`](https://github.com/lfl-lab/squadds/blob/main/squadds/core/design_patterns.py) enforces single-instance behavior by overriding `__call__` and caching objects in `_instances`
- **SQuADDS_DB** in [`squadds/core/db.py`](https://github.com/lfl-lab/squadds/blob/main/squadds/core/db.py) uses `metaclass=SingletonMeta` to ensure all references share identical state, including selected components and cached dataframes
- **State management** requires understanding that modifications in one module affect all others; use `SQuADDS_DB._instances.pop(SQuADDS_DB, None)` to reset for testing
- **Thread safety** is not built-in; implement external locking for concurrent environments

## Frequently Asked Questions

### What is the SingletonMeta pattern in SQuADDS?

The SingletonMeta pattern is a metaclass implementation in [`squadds/core/design_patterns.py`](https://github.com/lfl-lab/squadds/blob/main/squadds/core/design_patterns.py) that restricts class instantiation to a single object. It maintains a private `_instances` dictionary that maps classes to their single instantiated objects, returning the cached instance on subsequent constructor calls rather than creating new objects.

### How do I ensure I'm using the same SQuADDS_DB instance across modules?

Simply import and instantiate `SQuADDS_DB` from [`squadds/core/db.py`](https://github.com/lfl-lab/squadds/blob/main/squadds/core/db.py) in each module where you need database access. Because the class declares `metaclass=SingletonMeta`, every call to `SQuADDS_DB()` returns the identical Python object with shared state, eliminating the need to pass instances between modules manually.

### Is the SQuADDS_DB singleton thread-safe?

No, the SingletonMeta implementation in the current SQuADDS codebase does not include thread-synchronization mechanisms. In multi-threaded applications, you should wrap instantiation in a threading lock or use `threading.Lock()` to prevent race conditions during the initial object creation phase.

### How can I reset the SQuADDS_DB singleton for unit testing?

To force creation of a fresh instance during testing, clear the metaclass storage by calling `SQuADDS_DB._instances.pop(SQuADDS_DB, None)`. This removes the cached instance from the SingletonMeta dictionary, causing the next constructor call to generate a new object with reset state.