### Setup Development Environment with Tox Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Instructions for setting up the development environment, including cloning the repository, creating a virtual environment, installing dependencies, and running tests with tox. ```console git clone git@github.com:henriquebastos/python-decouple.git cd python-decouple python -m venv .venv source .venv/bin/activate pip install -r requirements.txt tox ``` -------------------------------- ### Config Get Method Examples Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/config.md Demonstrates retrieving configuration values with different options: simple string retrieval, using default values, and applying type casting. ```python secret = config('SECRET_KEY') debug = config('DEBUG', default=False, cast=bool) port = config('DATABASE_PORT', default=5432, cast=int) allowed = config('ALLOWED_HOSTS', default='localhost', cast=lambda v: [h.strip() for h in v.split(',')]) ``` -------------------------------- ### Env File Configuration Example Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Example structure for a .env file. Comments are supported. ```console DEBUG=True TEMPLATE_DEBUG=True SECRET_KEY=ARANDOMSECRETKEY DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase PERCENTILE=90% #COMMENTED=42 ``` -------------------------------- ### Ini File Configuration Example Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Example structure for a settings.ini file. Note that '%' characters must be escaped as '%%'. ```ini [settings] DEBUG=True TEMPLATE_DEBUG=%(DEBUG)s SECRET_KEY=ARANDOMSECRETKEY DATABASE_URL=mysql://myuser:mypassword@myhost/mydatabase PERCENTILE=90%% #COMMENTED=42 ``` -------------------------------- ### Example Usage Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Demonstrates how to use RepositoryEnv with the Config class to load settings and handle environment variable precedence. ```APIDOC ### Example ```python from decouple import Config, RepositoryEnv config = Config(RepositoryEnv('/path/to/.env')) # With .env containing: DEBUG=true debug = config('DEBUG', cast=bool) # Returns True # Environment variables have precedence import os os.environ['DEBUG'] = 'false' debug = config('DEBUG', cast=bool) # Returns False (from os.environ) ``` ``` -------------------------------- ### Example .env File Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Demonstrates the KEY=VALUE format for .env files, including comments and various data types. ```env # Database Configuration DATABASE_HOST=localhost DATABASE_PORT=5432 DATABASE_NAME=myapp DATABASE_USER=postgres DATABASE_PASSWORD=secret123 # Application Settings DEBUG=True SECRET_KEY=changeme ALLOWED_HOSTS=localhost,127.0.0.1,.example.com # Feature Flags CACHE_ENABLED=True AUTH_REQUIRED=False # Services API_KEY=abc123def456 ``` -------------------------------- ### Config __call__ Method vs get() Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/config.md Shows the equivalent usage of the __call__ method and the get() method for retrieving configuration values. ```python config = Config(RepositoryEnv('.env')) # These are equivalent: value1 = config.get('KEY', default='default_value') value2 = config('KEY', default='default_value') ``` -------------------------------- ### Read Configuration with Custom Encoding Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Example of setting a custom encoding and then reading a configuration value. ```python from decouple import config # Set encoding early config.encoding = 'cp1251' # Now read configuration secret = config('SECRET_KEY') ``` -------------------------------- ### Example settings.ini File Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Shows the INI file format with a [settings] section, comments, interpolation, and escaped percent signs. ```ini [settings] # Database Configuration DATABASE_HOST=localhost DATABASE_PORT=5432 DATABASE_NAME=myapp DATABASE_USER=postgres DATABASE_PASSWORD=secret123 # Application Settings DEBUG=True SECRET_KEY=changeme ALLOWED_HOSTS=localhost,127.0.0.1,.example.com # Interpolation example BASE_URL=http://localhost:8000 API_BASE=%(BASE_URL)s/api # Percent sign requires escaping PERCENTAGE=99%% ``` -------------------------------- ### Basic Usage Examples Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/strtobool.md Provides examples of using strtobool with various string inputs that represent true and false values, including case-insensitivity. ```APIDOC ### Basic Usage ```python from decouple import strtobool # True values strtobool('yes') # Returns: True strtobool('YES') # Returns: True (case-insensitive) strtobool('true') # Returns: True strtobool('TRUE') # Returns: True strtobool('on') # Returns: True strtobool('1') # Returns: True strtobool('y') # Returns: True strtobool('t') # Returns: True # False values strtobool('no') # Returns: False strtobool('NO') # Returns: False (case-insensitive) strtobool('false') # Returns: False strtobool('FALSE') # Returns: False strtobool('off') # Returns: False strtobool('0') # Returns: False strtobool('n') # Returns: False strtobool('f') # Returns: False # Boolean input strtobool(True) # Returns: True strtobool(False) # Returns: False ``` ``` -------------------------------- ### RepositoryIni Example Usage Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Demonstrates how to use RepositoryIni with the Config class to load settings from an INI file. ```APIDOC ### Example ```python from decouple import Config, RepositoryIni config = Config(RepositoryIni('settings.ini')) # With settings.ini containing: # [settings] # DEBUG=False # DATABASE_URL=postgres://localhost/db debug = config('DEBUG', cast=bool) # Returns False db_url = config('DATABASE_URL') # Returns postgres://localhost/db ``` ``` -------------------------------- ### Install Python Decouple Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Install the python-decouple package using pip. ```console pip install python-decouple ``` -------------------------------- ### RepositorySecret Usage Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Demonstrates how to instantiate Config with RepositorySecret and access configuration values. ```APIDOC ## Usage Example ### Description This example shows how to use `RepositorySecret` with `Config` to load environment variables and secrets from files. ### Code ```python from decouple import Config, RepositorySecret # Initialize Config with RepositorySecret pointing to the secrets directory config = Config(RepositorySecret('/run/secrets/')) # Accessing a secret value username = config('db_user') # Example: Returns 'postgres' password = config('db_password') # Example: Returns 'secret123' # Environment variables take precedence import os os.environ['db_user'] = 'admin' username = config('db_user') # Returns: 'admin' ``` ``` -------------------------------- ### .env File Format Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Illustrates the expected format for .env files, including comments, key-value pairs, quoted values, and whitespace handling. ```plaintext # Comments ignored KEY=value DATABASE_URL=postgres://user:pass@host/db DEBUG=True ALLOWED_HOSTS=localhost,127.0.0.1 # Quoted values strip outer quotes API_KEY='secret123' # Stores: secret123 API_SECRET="another" # Stores: another # Unquoted trailing spaces stripped NAME=John # Stores: John # Leading/trailing spaces around = stripped SPACE_KEY = value # Stores: value ``` -------------------------------- ### Basic Configuration Usage Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md Demonstrates immediate usage of the global `config` object. It works without any setup, automatically finding configuration files. Specify default values and casting types as needed. ```python from decouple import config # Works immediately without any setup SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ``` -------------------------------- ### Custom Transformation Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Shows how to apply custom transformation functions to each element and combine with post-processing. ```APIDOC ## Example: Custom Transformation ```python from decouple import Csv # Apply transformation function csv = Csv(cast=lambda s: s.upper()) result = csv('hello, world, python') # Returns: ['HELLO', 'WORLD', 'PYTHON'] # Combine transformation with post-processing csv = Csv(cast=int, post_process=set) result = csv('1, 2, 3, 1, 2') # Returns: {1, 2, 3} ``` ``` -------------------------------- ### Django Settings with Python Decouple Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Example of a Django settings.py file using python-decouple, pathlib, and dj-database-url for configuration management. ```python # coding: utf-8 from decouple import config from unipath import Path from dj_database_url import parse as db_url BASE_DIR = Path(__file__).parent DEBUG = config('DEBUG', default=False, cast=bool) TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': config( 'DATABASE_URL', default='sqlite:///' + BASE_DIR.child('db.sqlite3'), cast=db_url ) } TIME_ZONE = 'America/Sao_ Paulo' USE_L10N = True USE_TZ = True SECRET_KEY = config('SECRET_KEY') ``` -------------------------------- ### INI File Format Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Illustrates the required format for INI configuration files, including the [settings] section, comments, string interpolation, and whitespace handling. ```ini [settings] DEBUG=True SECRET_KEY=mysecret DATABASE_PORT=5432 # Comments with # or ; # COMMENTED_KEY=value # Percent signs escaped with %% PERCENTAGE=99%% # String interpolation with %(key)s syntax BASE_URL=http://localhost FULL_URL=%(BASE_URL)s/api # Whitespace handling KEY_WITH_SPACES = value ``` -------------------------------- ### Using RepositoryEmpty with Config Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Demonstrates how to use `RepositoryEmpty` with the `Config` class. This setup ensures that only environment variables are checked, and any key not found in the environment will fall back to the default value. ```python from decouple import Config, RepositoryEmpty # Only checks os.environ, always returns None from repository config = Config(RepositoryEmpty()) value = config('KEY', default='fallback') # Returns 'fallback' ``` -------------------------------- ### Integer Elements Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Shows how to parse delimited strings into a list or tuple of integers. ```APIDOC ## Example: Integer Elements ```python from decouple import Csv csv = Csv(int) numbers = csv('1, 2, 3, 4, 5') # Returns: [1, 2, 3, 4, 5] numbers_tuple = Csv(int, post_process=tuple) result = numbers_tuple('10, 20, 30') # Returns: (10, 20, 30) ``` ``` -------------------------------- ### Config.get() Parameters Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Overview of the parameters available for the `get()` method in python-decouple's configuration. ```python get(option, default=undefined, cast=undefined) ``` -------------------------------- ### Basic CSV Parsing Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Demonstrates basic parsing of a comma-separated string into a list of strings. ```APIDOC ## Example: Basic CSV Parsing ```python from decouple import Csv, config # Parse comma-separated string to list of strings csv = Csv() hosts = csv('localhost, 127.0.0.1, example.com') # Returns: ['localhost', '127.0.0.1', 'example.com'] # With config config('ALLOWED_HOSTS', default='localhost', cast=Csv()) # Returns: ['localhost'] ``` ``` -------------------------------- ### .env Configuration File Format Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md An example of the `.env` file format. It uses a simple `KEY=VALUE` format, ignores comments, preserves quotes, and strips trailing spaces unless quoted. ```bash DEBUG=True SECRET_KEY=mysecret DATABASE_PORT=5432 ALLOWED_HOSTS=localhost,127.0.0.1 # Commented lines ignored ``` -------------------------------- ### Using Choices with Config Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/choices.md Example of integrating the Choices helper with the `config` function to validate environment variables. ```APIDOC ### With Config ```python from decouple import Choices, config # Environment variable validation db_driver = config('DATABASE_DRIVER', cast=Choices(['mysql', 'postgresql', 'sqlite'])) # Error if DATABASE_DRIVER not in choices # Usage: DATABASE_DRIVER=postgresql python app.py ``` ``` -------------------------------- ### settings.ini Configuration File Format Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md An example of the `settings.ini` file format. It uses a `[settings]` section and supports ConfigParser string interpolation. Percent signs must be escaped as `%%`. ```ini [settings] DEBUG=True SECRET_KEY=mysecret DATABASE_PORT=5432 ALLOWED_HOSTS=localhost,127.0.0.1 ``` -------------------------------- ### Basic Flat List Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/choices.md Demonstrates using Choices with a simple list of string values. Invalid choices will raise a ValueError. ```APIDOC ## Flat List Choices ### Basic Example ```python from decouple import Choices, config choices = Choices(['eth', 'usb', 'bluetooth']) result = choices('usb') # Returns: 'usb' # Invalid choice raises ValueError try: result = choices('serial') except ValueError as e: print(e) # Output: Value not in list: 'serial'; valid values are ['eth', 'usb', 'bluetooth'] ``` ``` -------------------------------- ### Flask Integration with Configuration Classes Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Set up Flask applications using python-decouple by defining configuration classes. This example shows how to create separate configurations for development and production environments. ```python # config.py from decouple import config class Config: SECRET_KEY = config('SECRET_KEY') DEBUG = config('DEBUG', default=False, cast=bool) TESTING = config('TESTING', default=False, cast=bool) class DevelopmentConfig(Config): DEBUG = True class ProductionConfig(Config): DEBUG = False # app.py from flask import Flask from config import DevelopmentConfig app = Flask(__name__) app.config.from_object(DevelopmentConfig) ``` -------------------------------- ### AutoConfig _find_file Method Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md Recursively searches for supported configuration files (settings.ini, .env) starting from a given path. ```APIDOC ## _find_file Method ### Description Recursively searches for supported configuration files starting from the specified path. ### Parameters - **path** (str) - Starting directory path for the search. ### Returns - **str** - Absolute path to the found configuration file, or an empty string if not found. ``` -------------------------------- ### Custom Delimiter Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Illustrates parsing strings with custom delimiters, including tabs and multi-character delimiters. ```APIDOC ## Example: Custom Delimiter ```python from decouple import Csv # Tab-delimited csv = Csv(delimiter='\t') values = csv('field1\tfield2\tfield3') # Returns: ['field1', 'field2', 'field3'] # Multi-character delimiter csv = Csv(delimiter='||') values = csv('part1||part2||part3') # Returns: ['part1', 'part2', 'part3'] ``` ``` -------------------------------- ### AutoConfig Constructor Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md Initializes AutoConfig. The `search_path` parameter specifies the starting directory for file discovery. If `None`, it defaults to the caller's module path. ```APIDOC ## AutoConfig Constructor ### Description Initializes AutoConfig with an optional search path for configuration files. ### Parameters #### Path Parameters - **search_path** (str or None) - Optional - Starting directory for file search. If None, uses caller's module path. ``` -------------------------------- ### Error Handling Examples Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/strtobool.md Demonstrates the `ValueError` raised by strtobool for a list of invalid string inputs. ```APIDOC ### Error Handling ```python from decouple import strtobool invalid_values = ['maybe', 'nope', 'somewhat', '2', 'enabled'] for value in invalid_values: try: result = strtobool(value) except ValueError as e: print(f"'{value}': {e}") # Output: # 'maybe': Invalid truth value: maybe # 'nope': Invalid truth value: nope # 'somewhat': Invalid truth value: somewhat # '2': Invalid truth value: 2 # 'enabled': Invalid truth value: enabled ``` ``` -------------------------------- ### Example Error Messages for UndefinedValueError Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/errors.md Illustrates the format of error messages generated by `UndefinedValueError` when a configuration key is not found and no default is specified. ```text SECRET_KEY not found. Declare it as envvar or define a default value. DATABASE_URL not found. Declare it as envvar or define a default value. API_TOKEN not found. Declare it as envvar or define a default value. ``` -------------------------------- ### Common Type Casting Examples in Python Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Demonstrates casting configuration values to various Python types including primitives, collections, and custom types. Use Csv for list-like values and Choices for enumerated options. ```python from decouple import config, Csv, Choices # Primitives bool_val = config('KEY', cast=bool) int_val = config('KEY', cast=int) float_val = config('KEY', cast=float) # Collections list_val = config('KEY', cast=Csv()) # List of strings int_list = config('KEY', cast=Csv(int)) # List of ints tuple_val = config('KEY', cast=Csv(post_process=tuple)) # Tuple # Validation choice_val = config('KEY', cast=Choices(['a', 'b'])) # Custom custom = config('KEY', cast=lambda v: v.upper().split(',')) ``` -------------------------------- ### Casting Configuration Values to List of Strings Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Example of casting a comma-separated string to a list of strings. Each item is stripped of leading/trailing whitespace. ```python os.environ['ALLOWED_HOSTS'] = '.localhost, .herokuapp.com' config('ALLOWED_HOSTS', cast=lambda v: [s.strip() for s in v.split(',')]) ``` -------------------------------- ### Boolean Casting Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/config.md Illustrates how boolean values are cast using the cast=bool option, showing the result when the .env file contains 'DEBUG=false'. ```python config = Config(RepositoryEnv('.env')) # With .env containing: DEBUG=false debug = config('DEBUG', cast=bool) # Returns False ``` -------------------------------- ### Simple .env Configuration Format Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Use this format for simple key-value pairs. Comments start with '#'. Quotes are removed from values. No string interpolation is supported. ```env DEBUG=True SECRET_KEY=mysecret123 DATABASE_URL=postgres://user:pass@localhost/db ALLOWED_HOSTS=localhost,127.0.0.1,.example.com API_KEY='secret-with-spaces' ``` -------------------------------- ### Configuration at Startup Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Configures the application at startup by loading required settings and raising an error if any are missing. ```python def configure_app(): """Configure application at startup.""" from decouple import config, UndefinedValueError settings = {} required_keys = ['SECRET_KEY', 'DATABASE_URL'] for key in required_keys: try: settings[key] = config(key) except UndefinedValueError: raise RuntimeError(f"Required setting not found: {key}") return settings settings = configure_app() ``` -------------------------------- ### Complex Processing Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md An example demonstrating complex CSV parsing with custom transformations, delimiters, stripping, and post-processing, including usage with the `config` function. ```APIDOC ## Example: Complex Processing ```python from decouple import Csv, config # Parse CSV with special characters and transformations csv = Csv( cast=lambda s: s.upper().strip(), delimiter=',', strip=' \t', post_process=tuple ) result = csv(' api_key , database_url , secret_token ') # Returns: ('API_KEY', 'DATABASE_URL', 'SECRET_TOKEN') # Use with config for environment variables config('INTERNAL_SERVICES', default='auth, db, cache', cast=Csv(cast=str.lower, post_process=set)) ``` ``` -------------------------------- ### Create Custom Config Instances with python-decouple Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Shows how to create custom configuration instances using different repository types like .env files, .ini files, or custom file paths. ```python from decouple import Config, RepositoryEnv, RepositoryIni # From .env file config = Config(RepositoryEnv('.env')) # From settings.ini config = Config(RepositoryIni('settings.ini')) # Custom path config = Config(RepositoryEnv('/etc/app/.env')) ``` -------------------------------- ### Using RepositoryIni with Config Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Demonstrates how to initialize a Config object with RepositoryIni to read settings from an 'settings.ini' file and access configuration values. ```python from decouple import Config, RepositoryIni config = Config(RepositoryIni('settings.ini')) # With settings.ini containing: # [settings] # DEBUG=False # DATABASE_URL=postgres://localhost/db debug = config('DEBUG', cast=bool) # Returns False db_url = config('DATABASE_URL') # Returns postgres://localhost/db ``` -------------------------------- ### Custom Strip Characters Example Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Demonstrates stripping specific characters from each element after splitting. ```APIDOC ## Example: Custom Strip Characters ```python from decouple import Csv # Strip specific characters csv = Csv(strip=' %*') values = csv('%value1%\t *value2*\t value3 ') # Returns: ['value1', 'value2', 'value3'] ``` ``` -------------------------------- ### AutoConfig _load Method Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md Finds and loads the configuration file, instantiating the appropriate repository. Falls back to `RepositoryEmpty` if errors occur during file loading. ```APIDOC ## _load Method ### Description Finds and loads the configuration file, instantiating the appropriate repository. Handles errors by falling back to `RepositoryEmpty`. ### Parameters - **path** (str) - Starting directory for the search. ### Side Effects Initializes `self.config` with the appropriate `Config` and repository instance. ### Error Handling Catches exceptions during file finding and loading, falling back to `RepositoryEmpty`. ``` -------------------------------- ### Basic Usage with Global Instance Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md Shows how to use the global `config` object to retrieve settings. It automatically searches for `.env` or `settings.ini` in the current directory or its parents. Default values and type casting can be specified. ```python from decouple import config # Automatically finds .env or settings.ini in current directory or parents API_KEY = config('API_KEY') DEBUG = config('DEBUG', default=False, cast=bool) ``` -------------------------------- ### Create Custom Config Instance Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Shows how to create custom `Config` instances with different repository types like `.env` files or `.ini` files, and how to specify custom paths for these files. ```APIDOC ## Create Custom Config Instance ### Description Create custom `Config` instances to manage settings from various sources. ### Usage ```python from decouple import Config, RepositoryEnv, RepositoryIni # From .env file in the current directory config_env = Config(RepositoryEnv('.env')) # From settings.ini file in the current directory config_ini = Config(RepositoryIni('settings.ini')) # From a custom path for .env file config_custom_path = Config(RepositoryEnv('/etc/app/.env')) ``` ``` -------------------------------- ### Using Default Parameter in Config.get() Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Demonstrates how to provide default values for configuration options when they are not found. If no default is specified and the option is missing, `UndefinedValueError` is raised. ```python from decouple import config # No default - raises error if missing secret = config('SECRET_KEY') # String default host = config('DATABASE_HOST', default='localhost') # None default optional = config('OPTIONAL_KEY', default=None) # Integer default port = config('PORT', default=5432) # Boolean default debug = config('DEBUG', default=False) ``` -------------------------------- ### Early Loading Configuration Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Loads configuration immediately at startup using Config with RepositoryEnv, avoiding lazy loading delays. ```python from decouple import Config, RepositoryEnv # Load immediately at startup config = Config(RepositoryEnv('.env')) # Avoids lazy loading delay ``` -------------------------------- ### Reusing Config Instances Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Demonstrates efficient reuse of config instances, which are singleton-like after their first use. ```python from decouple import config # Efficient: config is singleton-like after first use value1 = config('KEY1') value2 = config('KEY2') # Reuses same instance ``` -------------------------------- ### Config.__call__() Method Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/config.md A convenience method that acts as a shortcut to the `get()` method, allowing direct invocation of the Config instance. ```APIDOC ## Config.__call__() ### Description Convenience shortcut to `get()` method. Allows `Config` instances to be called directly. ### Parameters Same as `get()` ### Returns Same as `get()` ### Example ```python config = Config(RepositoryEnv('.env')) # These are equivalent: value1 = config.get('KEY', default='default_value') value2 = config('KEY', default='default_value') ``` ``` -------------------------------- ### Handle Configuration File Permission Issues Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/errors.md If the .env file lacks read permissions, exceptions will occur during configuration loading. Implement general exception handling to catch and report these issues. ```python from decouple import AutoConfig # .env file has no read permissions config = AutoConfig() try: value = config('SOME_KEY') except Exception as e: print(f"Error reading config: {type(e).__name__}: {e}") # Error handling depends on specific exception ``` -------------------------------- ### Retrieve Configuration Values with python-decouple Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Demonstrates basic usage, providing default values, casting to specific types, validating choices, and parsing delimited strings for configuration values. ```python from decouple import config # Basic usage secret = config('SECRET_KEY') # With default debug = config('DEBUG', default=False, cast=bool) # Type casting port = config('PORT', default=8000, cast=int) # Validation env = config('ENVIRONMENT', default='dev', cast=Choices(['dev', 'staging', 'prod'])) # Delimited values hosts = config('ALLOWED_HOSTS', default='localhost', cast=Csv()) ``` -------------------------------- ### Default Configuration Lists with Csv Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Shows how to provide default CSV-formatted lists for configuration values using the default parameter with the Csv cast. ```python from decouple import Csv, config # Middleware list middleware = config('MIDDLEWARE', default='auth.middleware.AuthMiddleware', cast=Csv()) # Database hosts for replication db_hosts = config('DATABASE_REPLICAS', default='db1.example.com,db2.example.com', cast=Csv()) ``` -------------------------------- ### Validate Required Settings at Startup Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/errors.md Implement a startup validation function to check for all necessary configuration keys. Raises a custom ConfigError if any required setting is missing, preventing application startup with incomplete configuration. ```python from decouple import config, UndefinedValueError import sys class ConfigError(Exception): pass def validate_config(): """Validate all required settings at startup.""" required = ['SECRET_KEY', 'DATABASE_URL', 'DEBUG'] for key in required: try: config(key) except UndefinedValueError: raise ConfigError(f"Required setting missing: {key}") try: validate_config() except ConfigError as e: print(f"Configuration error: {e}", file=sys.stderr) sys.exit(1) ``` -------------------------------- ### Casting Configuration Values to Integer Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Example of casting an environment variable to an integer type. The '42' string is converted to the integer 42. ```python os.environ['EMAIL_PORT'] = '42' config('EMAIL_PORT', cast=int) ``` -------------------------------- ### Config Constructor Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/config.md Initializes the Config class with a specified repository. ```APIDOC ## Config Constructor ### Description Initializes the Config class with a specified repository. ### Parameters #### Path Parameters - **repository** (Repository object) - Required - Backend repository implementing `__contains__` and `__getitem__` (e.g., `RepositoryEnv`, `RepositoryIni`, `RepositorySecret`) ``` -------------------------------- ### Casting Configuration Values to Boolean Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Example of casting an environment variable to a boolean type. The 'False' string is correctly interpreted as the boolean False. ```python os.environ['DEBUG'] = 'False' config('DEBUG', cast=bool) ``` -------------------------------- ### Config Usage with RepositoryEnv Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Demonstrates how to use RepositoryEnv with the Config class to read settings. Environment variables take precedence over .env file values. ```python from decouple import Config, RepositoryEnv config = Config(RepositoryEnv('/path/to/.env')) # With .env containing: DEBUG=true debug = config('DEBUG', cast=bool) # Returns True # Environment variables have precedence import os os.environ['DEBUG'] = 'false' debug = config('DEBUG', cast=bool) # Returns False (from os.environ) ``` -------------------------------- ### Example Usage of Csv with text_type Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/types.md Shows how the Csv class utilizes text_type for its default casting behavior, defaulting to str in Python 3. ```python from decouple import Csv # Uses text_type as default cast csv = Csv() # Equivalent to Csv(cast=str) in Python 3 ``` -------------------------------- ### Undefined Sentinel Logic in get Method Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/types.md Shows the internal logic where the Undefined sentinel is used to determine if a default value was explicitly provided. ```python def get(self, option, default=undefined, cast=undefined): if isinstance(default, Undefined): raise UndefinedValueError(...) # else use default ``` -------------------------------- ### UTF-8 BOM Handling Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Specify 'utf-8-sig' encoding to correctly handle configuration files that start with a UTF-8 Byte Order Mark (BOM). ```python from decouple import config # For files with UTF-8 BOM config.encoding = 'utf-8-sig' ``` -------------------------------- ### Use and Check DEFAULT_ENCODING Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/types.md Shows how to instantiate `Config` with different encodings and how to print the value of the `DEFAULT_ENCODING` constant. It highlights the default UTF-8 encoding. ```python from decouple import Config, RepositoryEnv, DEFAULT_ENCODING # Use default encoding config1 = Config(RepositoryEnv('.env')) # Uses UTF-8 # Use custom encoding config2 = Config(RepositoryEnv('.env', encoding='cp1251')) # Check what the default is print(DEFAULT_ENCODING) # Output: UTF-8 ``` -------------------------------- ### Handle Errors Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Provides examples of how to handle potential errors during configuration retrieval, such as `UndefinedValueError` when a required setting is missing, and `ValueError` when type casting fails. ```APIDOC ## Handle Errors ### Description Handle exceptions that may occur during configuration retrieval or type casting. ### Usage ```python from decouple import config, UndefinedValueError # Handling missing required configuration value try: api_key = config('API_KEY') except UndefinedValueError: print("API_KEY is required") # Handling type casting errors try: port = config('PORT', cast=int) except ValueError: print("PORT must be an integer") ``` ``` -------------------------------- ### Explicit Search Path for Configuration Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md Demonstrates how to specify an explicit directory for `AutoConfig` to search for configuration files. This is useful when configuration files are not in the project root. ```python from decouple import AutoConfig # Search starts in specific directory config = AutoConfig('/etc/myapp') db_host = config('DB_HOST', default='localhost') ``` -------------------------------- ### Fail Fast on Missing Required Settings Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Ensures that all critical settings are present at startup. Raises a RuntimeError if any required setting is undefined. ```python from decouple import config, UndefinedValueError def load_config(): required = ['SECRET_KEY', 'DATABASE_URL', 'API_KEY'] for key in required: try: config(key) except UndefinedValueError: raise RuntimeError(f"Missing required setting: {key}") load_config() ``` -------------------------------- ### Csv Helper Post-processing to Tuple Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Use the `post_process` argument with the Csv helper to change the output type, for example, to a tuple. This is useful for ordered data. ```python >>> os.environ['SECURE_PROXY_SSL_HEADER'] = 'HTTP_X_FORWARDED_PROTO, https' >>> config('SECURE_PROXY_SSL_HEADER', cast=Csv(post_process=tuple)) ('HTTP_X_FORWARDED_PROTO', 'https') ``` -------------------------------- ### RepositoryEnv Constructor Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Initializes the RepositoryEnv with a source file path and optional encoding. ```APIDOC ## Constructor ```python RepositoryEnv(source, encoding=DEFAULT_ENCODING) ``` | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | source | str | Yes | — | Path to `.env` file (e.g., `.env`, `config/.env`) | | encoding | str | No | `DEFAULT_ENCODING` | File encoding (default: `UTF-8`) | **Raises:** `FileNotFoundError` if source file does not exist ``` -------------------------------- ### Example Usage of strtobool() Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/types.md Demonstrates how to use the strtobool() function with various inputs, including case-insensitive and numeric representations, to parse boolean values from strings. ```python from decouple import strtobool # All of these return True strtobool('yes') # in TRUE_VALUES strtobool('TRUE') # case-insensitive strtobool('1') # numeric representation # All of these return False strtobool('no') # in FALSE_VALUES strtobool('FALSE') # case-insensitive strtobool('0') # numeric representation ``` -------------------------------- ### Graceful Handling of Missing Configuration Files Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/errors.md Provides alternative methods for handling missing configuration files, including using AutoConfig for fallback values and checking file existence before creating a repository instance. ```python from decouple import Config, RepositoryEnv, AutoConfig import os # Option 1: Use AutoConfig (handles missing files gracefully) from decouple import config setting = config('SOME_KEY', default='fallback') # Option 2: Check file existence before creating repository if os.path.isfile('.env'): config = Config(RepositoryEnv('.env')) else: config = Config(RepositoryEnv('.env.example')) ``` -------------------------------- ### Config Constructor Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/config.md Initializes the Config class with a repository object. The repository must implement __contains__ and __getitem__. ```python from decouple import Config, RepositoryEnv config = Config(RepositoryEnv('.env')) ``` -------------------------------- ### Casting Configuration Values to Tuple Source: https://github.com/hbnetwork/python-decouple/blob/master/README.rst Example of casting a string to a tuple using a custom callable and post-processing. This is useful for structured configuration values like headers. ```python os.environ['SECURE_PROXY_SSL_HEADER'] = 'HTTP_X_FORWARDED_PROTO, https' config('SECURE_PROXY_SSL_HEADER', cast=Csv(post_process=tuple)) ``` -------------------------------- ### Basic CSV Parsing with Csv Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Demonstrates parsing a comma-separated string into a list of strings using the default Csv settings. Also shows how to use Csv with the config function. ```python from decouple import Csv, config # Parse comma-separated string to list of strings csv = Csv() hosts = csv('localhost, 127.0.0.1, example.com') # Returns: ['localhost', '127.0.0.1', 'example.com'] # With config config('ALLOWED_HOSTS', default='localhost', cast=Csv()) # Returns: ['localhost'] ``` -------------------------------- ### Enable Verbose Logging for Debugging Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/errors.md Set the logging level to DEBUG to get detailed output from python-decouple. This helps in diagnosing issues by showing which configuration sources are being checked. ```python import logging from decouple import config, UndefinedValueError logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) try: value = config('IMPORTANT_KEY') except UndefinedValueError as e: logger.error(f"Config error: {e}") logger.debug("Check the following:") logger.debug("1. Is the key in environment variables?") logger.debug("2. Is the key in .env or settings.ini?") logger.debug("3. Is the config file in the expected location?") ``` -------------------------------- ### Handle Missing Config File Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Shows how to catch a FileNotFoundError when the specified configuration file does not exist. Use this to provide fallback behavior or inform the user. ```python from decouple import Config, RepositoryEnv try: config = Config(RepositoryEnv('/nonexistent/.env')) except FileNotFoundError: print("Config file not found") ``` -------------------------------- ### Complex CSV Parsing and Configuration Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Provides an example of complex CSV parsing with custom transformations, delimiters, stripping, and post-processing, including its use with the `config` function for environment variables. ```python from decouple import Csv, config # Parse CSV with special characters and transformations csv = Csv( cast=lambda s: s.upper().strip(), delimiter=',', strip=' \t', post_process=tuple ) result = csv(' api_key , database_url , secret_token ') # Returns: ('API_KEY', 'DATABASE_URL', 'SECRET_TOKEN') # Use with config for environment variables config('INTERNAL_SERVICES', default='auth, db, cache', cast=Csv(cast=str.lower, post_process=set)) ``` -------------------------------- ### Override Multiple Settings with Environment Variables Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Shows how to override multiple configuration settings simultaneously by defining several environment variables before the command. ```bash # Override multiple settings DATABASE_HOST=prod.db.example.com DATABASE_PORT=5432 python app.py ``` -------------------------------- ### Handling Missing Configuration Files Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md Shows how `decouple` gracefully handles missing configuration files by falling back to `os.environ`. This ensures that settings can still be provided through environment variables. ```python from decouple import config, RepositoryEmpty # If no config file found, config still works with os.environ import os os.environ['API_KEY'] = 'secret' api_key = config('API_KEY') # Works even without config file ``` -------------------------------- ### File Structure of python-decouple Documentation Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/MANIFEST.md This snippet shows the directory structure for the technical reference documentation of the python-decouple library. It helps users navigate to specific API references and guides. ```tree output/ ├── README.md # Start here: overview and quick reference ├── api-reference/ │ ├── config.md # Config class: core coordinator │ ├── autoconfig.md # AutoConfig factory and global instance │ ├── repositories.md # All repository types (Env, Ini, Secret) │ ├── csv.md # Csv helper for delimited values │ ├── choices.md # Choices helper for validation │ └── strtobool.md # strtobool function for booleans ├── configuration.md # Configuration guide and patterns ├── types.md # Types, constants, and exceptions ├── errors.md # Error reference and handling └── MANIFEST.md # This file ``` -------------------------------- ### Handle Configuration Errors with Choices and Config Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/choices.md Shows how to integrate `Choices` with `config` and handle potential `ValueError` or `UndefinedValueError` exceptions that may occur during configuration loading. ```python from decouple import Choices, config, UndefinedValueError try: mode = config('MODE', cast=Choices(['fast', 'slow'])) except (ValueError, UndefinedValueError) as e: print(f"Configuration error: {e}") ``` -------------------------------- ### Handling Undefined vs None in python-decouple Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/types.md Demonstrates how `config` behaves with missing keys, `None` defaults, and existing environment variables. Use this to understand error handling and default value assignment. ```python from decouple import config, undefined, UndefinedValueError # Case 1: No default, missing key → Error try: value = config('MISSING_KEY') except UndefinedValueError: print("Key is required") # Case 2: Default is None, missing key → None value = config('MISSING_KEY', default=None) print(value) # Output: None # Case 3: Default is undefined (implicit) config.get('MISSING_KEY', default=undefined) # Same as case 1, raises UndefinedValueError # Case 4: Key exists in environment import os os.environ['DEFINED_KEY'] = 'value' value = config('DEFINED_KEY') # Returns: 'value' ``` -------------------------------- ### Common python-decouple Imports Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/types.md Shows comprehensive import statements for `python-decouple` components. Useful for setting up your project with all necessary tools. Includes examples for checking undefined values and handling `UndefinedValueError`. ```python # Import everything needed from decouple import ( config, Config, AutoConfig, RepositoryEnv, RepositoryIni, RepositorySecret, Csv, Choices, strtobool, UndefinedValueError, undefined, DEFAULT_ENCODING, ) # Check for undefined if isinstance(value, type(undefined)): print("Value was not provided") # Handle undefined errors try: setting = config('REQUIRED_SETTING') except UndefinedValueError as e: print(f"Error: {e}") ``` -------------------------------- ### Config Constructor with RepositoryEnv Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Instantiate Config with a specific repository, such as RepositoryEnv for .env files. Allows custom defaults and type casting. ```python from decouple import Config, RepositoryEnv config = Config(RepositoryEnv('.env')) secret = config('SECRET_KEY') debug = config('DEBUG', default=False, cast=bool) ``` -------------------------------- ### RepositoryIni Constructor Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Initializes RepositoryIni to read configuration from a specified INI file. ```APIDOC ## Constructor ```python RepositoryIni(source, encoding=DEFAULT_ENCODING) ``` | Parameter | Type | Required | Default | |-----------|------|----------|---------| | source | str | Yes | — | | encoding | str | No | `DEFAULT_ENCODING` | **Raises:** `FileNotFoundError` if source file does not exist ``` -------------------------------- ### Handle Missing Key in Repository Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Illustrates how direct access to the repository raises a KeyError if the key is not found. This is useful for strict validation of configuration keys. ```python from decouple import Config, RepositoryEnv config = Config(RepositoryEnv('.env')) # Direct access raises KeyError try: value = config.repository['MISSING_KEY'] except KeyError: print("Key not found in repository") ``` -------------------------------- ### Load Multiple Config Files with Precedence Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/configuration.md Use ChainMap to load multiple .env files, defining a clear order of precedence for your configuration values. Local overrides should have the highest priority. ```python from collections import ChainMap from decouple import Config, RepositoryEnv # Load multiple .env files with precedence config = Config(ChainMap( RepositoryEnv('.env.local'), # Local overrides (highest priority) RepositoryEnv('.env.development'), # Environment-specific RepositoryEnv('.env'), # Base defaults )) ``` -------------------------------- ### Usage of Undefined Sentinel Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/types.md Demonstrates how to use the 'undefined' sentinel to check if a configuration key was provided or if None was explicitly set as the default. ```python from decouple import Config, RepositoryEnv, undefined config = Config(RepositoryEnv('.env')) # Check for undefined marker value = config('SOME_KEY', default=undefined) # If 'SOME_KEY' not found, raises UndefinedValueError # Use None as explicit default value = config('SOME_KEY', default=None) # If 'SOME_KEY' not found, returns None ``` -------------------------------- ### RepositoryEnv Constructor Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/repositories.md Initializes RepositoryEnv with a source .env file path and optional encoding. Raises FileNotFoundError if the source file does not exist. ```python RepositoryEnv(source, encoding=DEFAULT_ENCODING) ``` -------------------------------- ### Integrating Csv with Config for Direct Parsing Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Illustrates how to use the `Csv` parser directly as the `cast` argument in `config.get()` for parsing environment variables into lists. ```python from decouple import config, Csv # Direct with config instance debug_hosts = config('DEBUG_HOSTS', default='127.0.0.1,localhost', cast=Csv()) ``` -------------------------------- ### Initialize Settings with Boolean Environment Variables Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/strtobool.md Initialize class attributes with boolean values derived from environment variables using strtobool. Provide a default value if the environment variable is not set. ```python from decouple import strtobool class Settings: def __init__(self): self.debug = strtobool(os.environ.get('DEBUG', 'false')) self.testing = strtobool(os.environ.get('TESTING', 'false')) self.production = strtobool(os.environ.get('PRODUCTION', 'true')) ``` -------------------------------- ### Reusing Csv Parser Instances for Performance Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/csv.md Shows how to create a `Csv` parser instance once and reuse it multiple times with `config.get()`. This is recommended for performance, as parsing occurs at call time, not instantiation. ```python from decouple import Csv, config # Create reusable parser HOSTS_CSV = Csv() # Use multiple times allowed_hosts = config('ALLOWED_HOSTS', cast=HOSTS_CSV) blocked_hosts = config('BLOCKED_HOSTS', cast=HOSTS_CSV) ``` -------------------------------- ### Handle Errors with python-decouple Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Demonstrates how to handle potential errors like undefined configuration values or type casting failures using try-except blocks. ```python from decouple import config, UndefinedValueError try: api_key = config('API_KEY') except UndefinedValueError: print("API_KEY is required") try: port = config('PORT', cast=int) except ValueError: print("PORT must be an integer") ``` -------------------------------- ### Custom Encoding for Configuration Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/api-reference/autoconfig.md Illustrates how to set a custom encoding for reading configuration files before the first call to `config`. This is important when dealing with non-UTF-8 encoded files. ```python from decouple import config # Set encoding before first call config.encoding = 'cp1251' secret = config('SECRET_KEY') ``` -------------------------------- ### Import python-decouple Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Demonstrates the basic and full import statements for the python-decouple library. Use the basic import for common usage and the full import to access all available components. ```python # Basic import - most common from decouple import config ``` ```python # Full imports from decouple import ( config, Config, AutoConfig, RepositoryEnv, RepositoryIni, RepositorySecret, Csv, Choices, strtobool, UndefinedValueError, undefined, DEFAULT_ENCODING, ) ``` -------------------------------- ### Retrieve Configuration Values Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Demonstrates how to retrieve configuration values using the `config` function, including basic usage, providing default values, type casting, validation with `Choices`, and handling delimited values with `Csv`. ```APIDOC ## Retrieve Configuration Values ### Description Retrieve configuration values from environment variables or .ini files. ### Usage ```python from decouple import config, Csv, Choices # Basic usage secret = config('SECRET_KEY') # With default value debug = config('DEBUG', default=False, cast=bool) # Type casting to integer port = config('PORT', default=8000, cast=int) # Validation with Choices env = config('ENVIRONMENT', default='dev', cast=Choices(['dev', 'staging', 'prod'])) # Handling delimited values (e.g., comma-separated) hosts = config('ALLOWED_HOSTS', default='localhost', cast=Csv()) ``` ``` -------------------------------- ### Handling FileNotFoundError for Missing Configuration Files Source: https://github.com/hbnetwork/python-decouple/blob/master/_autodocs/README.md Demonstrates catching a FileNotFoundError when the specified configuration file (e.g., .env) cannot be found by the repository. ```python # FileNotFoundError - missing config file from decouple import Config, RepositoryEnv try: config = Config(RepositoryEnv('/nonexistent/.env')) except FileNotFoundError as e: print(f"Error: {e}") ```