---
title: Module Singletons Pattern
category: patterns
---
# Module Singletons Pattern

## Rules

- Module-level singletons (e.g., db = MotionDatabase()) are acceptable but should be created carefully:
  - Avoid expensive initialization at import time.
  - Provide a way to construct with a test DB path or to reinitialize in tests.
- If a singleton holds resources (DB connections, sessions), ensure safe shutdown on program exit.

## Examples

### database.py - Safe class initialization

```python
class MotionDatabase:
    def __init__(self, db_path: str = config.DATABASE_PATH):
        self.db_path = db_path
        # If duckdb is not available, operate in lightweight file-backed mode
        self._file_mode = duckdb is None
        self._init_database()
```

### similarity/lookup.py - Local instances

```python
db = MotionDatabase(db_path=db_path) if db_path else MotionDatabase()
if hasattr(db, "get_cached_similarities"):
    rows = db.get_cached_similarities(...)
```

## Anti-Patterns

### Bad: Heavy initialization at import time

**Problem**: Creating connections and performing heavy schema migrations during import.

**Remediation**: Move heavy init to an explicit initialize() method and keep import fast.
