🔍 Code Extractor

class Config_v7

Maturity: 38

A persistent configuration dictionary that automatically saves changes to a JSON file whenever the dictionary is modified.

File:
/tf/active/vicechatdev/rmcl/config.py
Lines:
10 - 32
Complexity:
simple

Purpose

This class extends Python's built-in dict to provide automatic persistence of configuration data. It loads configuration from a JSON file on initialization and automatically saves any modifications (additions, updates, deletions) back to the file. The configuration file location is determined by CONFIG_FILE (likely using XDG base directory specification). This is useful for applications that need to maintain user settings or configuration state across sessions without manual save operations.

Source Code

class Config(dict):

    def __init__(self):
        super().__init__()
        if CONFIG_FILE.exists():
            super().update(json.load(CONFIG_FILE.open('r')))
        else:
            CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)

    def _save(self):
        json.dump(self, CONFIG_FILE.open('w'), indent=2)

    def __setitem__(self, key, value):
        super().__setitem__(key, value)
        self._save()

    def update(self, other):
        super().update(other)
        self._save()

    def __delitem__(self, key):
        super().__delitem__(key)
        self._save()

Parameters

Name Type Default Kind
bases dict -

Parameter Details

__init__: No parameters required. The constructor initializes an empty dictionary and attempts to load existing configuration from CONFIG_FILE if it exists. If the file doesn't exist, it creates the necessary parent directories.

Return Value

Instantiation returns a Config object that behaves like a dictionary but with automatic persistence. Methods return standard dictionary operation results: __setitem__ and __delitem__ return None, update returns None. All dictionary access methods (get, keys, values, items, etc.) inherited from dict work as expected.

Class Interface

Methods

__init__(self) -> None

Purpose: Initializes the Config object by loading existing configuration from CONFIG_FILE or creating the necessary directory structure if the file doesn't exist

Returns: None (constructor)

_save(self) -> None

Purpose: Private method that saves the current state of the configuration dictionary to CONFIG_FILE as formatted JSON

Returns: None

__setitem__(self, key, value) -> None

Purpose: Sets a key-value pair in the configuration and automatically saves to file

Parameters:

  • key: The configuration key (must be JSON-serializable, typically a string)
  • value: The configuration value (must be JSON-serializable)

Returns: None

update(self, other) -> None

Purpose: Updates the configuration with key-value pairs from another dictionary or iterable and automatically saves to file

Parameters:

  • other: A dictionary or iterable of key-value pairs to merge into the configuration

Returns: None

__delitem__(self, key) -> None

Purpose: Deletes a key from the configuration and automatically saves to file

Parameters:

  • key: The configuration key to delete

Returns: None

Attributes

Name Type Description Scope
CONFIG_FILE Path (module-level variable, not instance attribute) Path object pointing to the JSON file where configuration is persisted. Must be defined at module level before Config is instantiated. instance

Dependencies

  • json
  • xdg

Required Imports

import json
from xdg import xdg_config_home

Usage Example

# Assuming CONFIG_FILE is defined as:
# from pathlib import Path
# CONFIG_FILE = xdg_config_home() / 'myapp' / 'config.json'

# Create or load configuration
config = Config()

# Set a value (automatically saved to file)
config['api_key'] = 'my-secret-key'
config['theme'] = 'dark'

# Update multiple values at once (automatically saved)
config.update({'language': 'en', 'debug': True})

# Access values like a normal dictionary
api_key = config['api_key']
theme = config.get('theme', 'light')

# Delete a value (automatically saved)
del config['api_key']

# Check if key exists
if 'theme' in config:
    print(f"Current theme: {config['theme']}")

# Iterate over configuration
for key, value in config.items():
    print(f"{key}: {value}")

Best Practices

  • The Config object automatically saves on every modification, which may cause performance issues if making many rapid changes. Consider batching updates using the update() method instead of individual assignments.
  • Ensure CONFIG_FILE is properly defined before instantiating Config, typically as a Path object pointing to a location within XDG config directories.
  • The class stores all data as JSON, so only JSON-serializable types (str, int, float, bool, list, dict, None) should be used as values.
  • File I/O errors during save operations are not caught, so ensure proper error handling in production code.
  • The configuration file is created with default permissions; consider security implications for sensitive data.
  • Since this inherits from dict, all standard dictionary methods work but only __setitem__, update, and __delitem__ trigger automatic saves.
  • The class creates parent directories automatically on first instantiation if they don't exist.
  • Each Config instance operates independently on the same file, so multiple instances may lead to race conditions or overwrites.

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class Config_v5 58.2% similar

    A hierarchical configuration manager that loads and manages settings from multiple sources (defaults, files, environment variables) with support for nested structures and dynamic updates.

    From: /tf/active/vicechatdev/invoice_extraction/config.py
  • function save_config_to_file 54.3% similar

    Persists current application configuration values from the config module to a .env file, maintaining existing entries and formatting multi-value fields appropriately.

    From: /tf/active/vicechatdev/docchat/app.py
  • function save_session_to_disk_v1 52.4% similar

    Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings for storage.

    From: /tf/active/vicechatdev/docchat/blueprint.py
  • class Config_v3 51.9% similar

    Configuration manager class that loads, manages, and persists configuration settings for a contract validity analyzer application, supporting YAML files and environment variable overrides.

    From: /tf/active/vicechatdev/contract_validity_analyzer/config/config.py
  • class Config 51.2% similar

    Configuration class that manages application-wide settings, directory structures, API keys, and operational parameters for a statistical analysis application.

    From: /tf/active/vicechatdev/vice_ai/smartstat_config.py
← Back to Browse