🔍 Code Extractor

function get_config_value

Maturity: 60

Retrieves a configuration value from a nested dictionary structure in the global scope, with fallback to a default value if not found.

File:
/tf/active/vicechatdev/CDocs/settings_prod.py
Lines:
493 - 510
Complexity:
simple

Purpose

This function provides a safe way to access configuration values stored as nested dictionaries in a settings module. It handles missing sections or keys gracefully by returning a default value and logs errors when exceptions occur. It's designed to work with configuration dictionaries defined at the module level (in globals()), making it useful for centralized configuration management in applications.

Source Code

def get_config_value(section: str, key: str, default: Any = None) -> Any:
    """
    Get a configuration value from the settings module.
    
    Args:
        section: The section of the configuration (e.g., 'DOCUMENT_TYPES')
        key: The key within the section
        default: The default value to return if not found
        
    Returns:
        The configuration value or default if not found
    """
    try:
        section_dict = globals().get(section, {})
        return section_dict.get(key, default)
    except Exception as e:
        logger.error(f"Error getting config value {section}.{key}: {e}")
        return default

Parameters

Name Type Default Kind
section str - positional_or_keyword
key str - positional_or_keyword
default Any None positional_or_keyword

Parameter Details

section: The name of the top-level configuration dictionary to access (e.g., 'DOCUMENT_TYPES', 'DATABASE_SETTINGS'). This should match a dictionary variable name defined in the module's global scope.

key: The key within the section dictionary whose value should be retrieved. This is the specific configuration parameter name you want to access.

default: The fallback value to return if either the section doesn't exist, the key is not found within the section, or an exception occurs. Can be any type (None, string, int, dict, etc.). Defaults to None if not specified.

Return Value

Type: Any

Returns the value associated with the specified key in the section dictionary. The return type is Any, meaning it can be any Python object depending on what's stored in the configuration. If the section or key doesn't exist, or if an error occurs during retrieval, returns the default value provided (or None if no default was specified).

Dependencies

  • logging

Required Imports

import logging
from typing import Any

Usage Example

import logging
from typing import Any

# Setup logger
logger = logging.getLogger(__name__)

# Define configuration dictionaries at module level
DOCUMENT_TYPES = {
    "pdf": "application/pdf",
    "docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
}

DATABASE_SETTINGS = {
    "host": "localhost",
    "port": 5432,
    "timeout": 30
}

def get_config_value(section: str, key: str, default: Any = None) -> Any:
    try:
        section_dict = globals().get(section, {})
        return section_dict.get(key, default)
    except Exception as e:
        logger.error(f"Error getting config value {section}.{key}: {e}")
        return default

# Usage examples
pdf_mime = get_config_value("DOCUMENT_TYPES", "pdf")
print(pdf_mime)  # Output: application/pdf

db_port = get_config_value("DATABASE_SETTINGS", "port", 3306)
print(db_port)  # Output: 5432

missing_value = get_config_value("NONEXISTENT_SECTION", "key", "default_value")
print(missing_value)  # Output: default_value

missing_key = get_config_value("DATABASE_SETTINGS", "nonexistent_key", 9999)
print(missing_key)  # Output: 9999

Best Practices

  • Ensure a logger is properly configured before using this function to capture error messages
  • Define configuration dictionaries at the module level (global scope) for this function to access them
  • Always provide meaningful default values that match the expected type of the configuration value
  • Use consistent naming conventions for section names (e.g., UPPER_CASE for configuration dictionaries)
  • Consider using this function as part of a larger configuration management system rather than directly accessing globals() elsewhere in your code
  • Be aware that this function accesses the globals() of the module where it's defined, not the caller's globals
  • For production use, consider validating the retrieved values or using a more robust configuration management library like python-decouple or dynaconf

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function get_system_settings 54.3% similar

    Retrieves system-wide configuration settings from a Neo4j database, returning default values if settings are not found or an error occurs.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function get_default_connection_config 48.9% similar

    Retrieves the default database connection configuration by loading settings from a sql_config.py file located in the same directory as the function.

    From: /tf/active/vicechatdev/full_smartstat/sql_query_generator.py
  • function get_document_type 47.1% similar

    Retrieves configuration details for a specific document type by looking it up in DOCUMENT_CONFIG or DOCUMENT_TYPES, returning a dictionary with document metadata or an empty dict if not found.

    From: /tf/active/vicechatdev/CDocs/settings_prod.py
  • function load_config 45.5% similar

    Loads configuration from multiple fallback locations, returning a Config instance with application settings.

    From: /tf/active/vicechatdev/invoice_extraction/config.py
  • function load_config_v1 44.5% similar

    Parses a .env file and loads key-value pairs into a dictionary, ignoring comments and handling errors gracefully.

    From: /tf/active/vicechatdev/SPFCsync/grant_sharepoint_access.py
← Back to Browse