🔍 Code Extractor

function get_env_value

Maturity: 45

Retrieves an environment variable value by key and automatically strips surrounding single or double quotes if present.

File:
/tf/active/vicechatdev/email-forwarder/src/config/settings.py
Lines:
7 - 14
Complexity:
simple

Purpose

This utility function safely retrieves environment variables while handling a common issue where values may be wrapped in quotes (either single or double). This is particularly useful when reading configuration from .env files or shell environments where values might be quoted. The function provides a default value fallback and ensures the returned string is clean of surrounding quotes.

Source Code

def get_env_value(key: str, default: str = "") -> str:
    """Get environment variable value and strip quotes if present"""
    value = os.environ.get(key, default)
    # Strip surrounding quotes if they exist
    if len(value) >= 2 and ((value.startswith('"') and value.endswith('"')) or 
                           (value.startswith("'") and value.endswith("'"))):
        value = value[1:-1]
    return value

Parameters

Name Type Default Kind
key str - positional_or_keyword
default str '' positional_or_keyword

Parameter Details

key: The name of the environment variable to retrieve. This should be a string matching the exact name of the environment variable (case-sensitive on most systems).

default: The default value to return if the environment variable is not found. Defaults to an empty string if not specified. This allows graceful handling of missing environment variables.

Return Value

Type: str

Returns a string containing the value of the environment variable with any surrounding quotes removed. If the variable doesn't exist, returns the default value (empty string by default). The quote stripping only occurs if the value has at least 2 characters and both starts and ends with matching quotes (either both single or both double quotes).

Required Imports

import os

Usage Example

import os

def get_env_value(key: str, default: str = "") -> str:
    """Get environment variable value and strip quotes if present"""
    value = os.environ.get(key, default)
    if len(value) >= 2 and ((value.startswith('"') and value.endswith('"')) or 
                           (value.startswith("'") and value.endswith("'"))):
        value = value[1:-1]
    return value

# Example usage
os.environ['DATABASE_URL'] = '"postgresql://localhost/mydb"'
db_url = get_env_value('DATABASE_URL')
print(db_url)  # Output: postgresql://localhost/mydb

# With default value
api_key = get_env_value('API_KEY', 'default_key')
print(api_key)  # Output: default_key (if API_KEY not set)

# Without quotes
os.environ['PORT'] = '8080'
port = get_env_value('PORT')
print(port)  # Output: 8080

Best Practices

  • Use this function when reading environment variables that may come from .env files or shell scripts where values might be quoted
  • Always provide meaningful default values for non-critical configuration to prevent application crashes
  • Be aware that this function only strips matching quotes from both ends - it won't handle mismatched quotes or quotes in the middle of values
  • The function only strips quotes if the value has at least 2 characters, so single-character values are safe
  • Consider using this function consistently across your application for all environment variable access to ensure uniform quote handling

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function load_env_file 55.4% similar

    Reads and parses environment variables from a .env file in the current directory, returning them as a dictionary.

    From: /tf/active/vicechatdev/SPFCsync/validate_config.py
  • function load_config_v1 54.8% 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
  • function check_configuration_v1 47.5% similar

    Validates the presence of a .env configuration file and checks that all required environment variables (TENANT_ID, CLIENT_ID, CLIENT_SECRET, FROM_EMAIL) are defined.

    From: /tf/active/vicechatdev/email-forwarder/run_service.py
  • function get_system_configuration 47.3% similar

    Retrieves system configuration settings from environment variables for display in an admin panel, including database connections, authentication settings, and operational parameters.

    From: /tf/active/vicechatdev/CDocs/controllers/admin_controller.py
  • function save_config_to_file 46.9% 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
← Back to Browse