### Install EnvYAML Source: https://github.com/thesimj/envyaml/blob/main/README.md Install the envyaml package using pip. ```bash pip install envyaml ``` -------------------------------- ### Retrieve Values with Default Fallback using get() Source: https://context7.com/thesimj/envyaml/llms.txt Use the `get()` method to safely retrieve configuration values, providing an optional default value if the key is missing. Returns `None` if the key is missing and no default is specified. ```python from envyaml import EnvYAML env = EnvYAML('env.yaml', env_file='.env') # Get value with default if key doesn't exist timeout = env.get('connection.timeout', 30) print(timeout) # Output: 30 (default value) # Get existing value port = env.get('database.port', 5432) print(port) # Output: 3301 (actual value from config) # Get returns None when no default specified and key missing result = env.get('nonexistent.key') print(result) # Output: None # Handle empty environment variables empty_value = env.get('empty.config', 'fallback') print(empty_value) # Output: fallback (if empty or undefined) ``` -------------------------------- ### Export() - Export Configuration as Dictionary Source: https://context7.com/thesimj/envyaml/llms.txt Use export() to get a complete copy of all configuration values as a Python dictionary. This allows integration with other libraries that expect dictionary inputs. ```python from envyaml import EnvYAML env = EnvYAML('env.yaml', env_file='.env') # Export entire configuration config = env.export() print(type(config)) # Output: # Use exported config with other libraries import json json_config = json.dumps(config, indent=2) # Pass to functions expecting dict def setup_database(config): return f"Connecting to {config['database.host']}:{config['database.port']}" result = setup_database(config) print(result) # Output: Connecting to localhost:3301 ``` -------------------------------- ### EnvYAML Get with Default Value Source: https://github.com/thesimj/envyaml/blob/main/README.md Safely access configuration values using the `get` method, providing a default value if the key does not exist or the environment variable is not set. ```python print(env.get('not.exist.value', 'default')) # >> default print(env.get('empty_env', 'default')) # >> default print(env['empty_env']) # >> None ``` -------------------------------- ### Accessing Nested Data with EnvYAML Source: https://context7.com/thesimj/envyaml/llms.txt Provides examples of accessing elements within lists and deeply nested dictionaries using a combination of index and dot notation. This allows for granular retrieval of configuration values. ```python from envyaml import EnvYAML env = EnvYAML('env.yaml') # Access list items by index print(env['servers'][0]) # Output: {'host': 'server1.example.com', 'port': 8080} # Access nested list items with dot notation print(env['servers.0.host']) # Output: server1.example.com print(env['servers.1.port']) # Output: 8081 # Deep nested access print(env['nested.items.0.config.enabled']) # Output: True # Get entire list servers = env['servers'] for i, server in enumerate(servers): print(f"Server {i}: {server['host']}:{server['port']}") ``` -------------------------------- ### Configure File Paths via Environment Variables Source: https://context7.com/thesimj/envyaml/llms.txt Set file paths for `EnvYAML` and `.env` files using environment variables (`ENV_YAML_FILE`, `ENV_FILE`) instead of hardcoding them. This enhances flexibility in deployment scenarios. ```python from envyaml import EnvYAML import os # Set config paths via environment variables os.environ['ENV_YAML_FILE'] = 'config/production.yaml' os.environ['ENV_FILE'] = 'config/production.env' # EnvYAML uses these paths automatically env = EnvYAML() print(env['database.host']) # Output: (value from production.yaml) # Clean up del os.environ['ENV_YAML_FILE'] del os.environ['ENV_FILE'] ``` -------------------------------- ### Keys() - List All Configuration Keys Source: https://context7.com/thesimj/envyaml/llms.txt Use keys() to retrieve all available configuration keys, including flattened nested paths. This is useful for introspection and debugging. ```python from envyaml import EnvYAML env = EnvYAML('env.yaml') # Get all keys all_keys = env.keys() print(list(all_keys)[:10]) # Output: ['project', 'project.name', 'database', 'database.host', 'database.port', ...] # Check key count print(len(list(env.keys()))) # Output: 25 (varies by config) # Iterate over keys for key in env.keys(): if key.startswith('database.'): print(f"{key}: {env[key]}") ``` -------------------------------- ### Format() - String Interpolation Source: https://context7.com/thesimj/envyaml/llms.txt Use the format() method to apply Python string formatting to configuration values containing placeholders. This is useful for dynamic string generation. ```yaml # env.yaml templates: insert_query: INSERT INTO "{table}" (user, login) VALUES ($1, $2) greeting: "Hello {name}, welcome to {app}!" path: "{base}/{version}/{resource}" ``` ```python from envyaml import EnvYAML env = EnvYAML('env.yaml') # Format SQL query with table name query = env.format('templates.insert_query', table='users') print(query) # Output: INSERT INTO "users" (user, login) VALUES ($1, $2) # Format greeting message message = env.format('templates.greeting', name='John', app='MyApp') print(message) # Output: Hello John, welcome to MyApp! # Format URL path url = env.format('templates.path', base='/api', version='v2', resource='users') print(url) # Output: /api/v2/users ``` -------------------------------- ### Basic EnvYAML Initialization Source: https://context7.com/thesimj/envyaml/llms.txt Initialize EnvYAML by specifying the path to your YAML configuration file. You can also specify an optional .env file for environment variables and enable features like including OS environment variables, strict mode, and flattening. ```python from envyaml import EnvYAML # Load default env.yaml from current directory env = EnvYAML() # Load specific YAML file env = EnvYAML('config/env.yaml') # Load YAML with .env file for environment variables env = EnvYAML('config/env.yaml', env_file='config/.env') # Full initialization with all options env = EnvYAML( yaml_file='config/env.yaml', env_file='config/.env', include_environment=True, # Include OS environment variables strict=True, # Raise error for undefined variables flatten=True # Enable dot-notation access ) ``` -------------------------------- ### YAML Configuration with Environment Variables Source: https://context7.com/thesimj/envyaml/llms.txt Define your YAML configuration file using $VAR or ${VAR} syntax for environment variable substitution. This allows for dynamic configuration based on the environment. ```yaml # env.yaml project: name: "${PROJECT_NAME}-${PROJECT_ID}" database: host: $DATABASE_HOST port: 3301 username: username password: $DATABASE_PASSWORD database: test table: user: table_user blog: table_blog query: |- SELECT * FROM "users" WHERE "user" = $1 AND "login" = $2 AND "pwd" = $3 redis: host: $REDIS_HOST|127.0.0.1 port: 5040 db: $REDIS_DB|3 list_items: - one - two - three escaped: $$.extra ``` -------------------------------- ### Basic EnvYAML Usage Source: https://github.com/thesimj/envyaml/blob/main/README.md Read a YAML file and access configuration values using dictionary-like syntax. Supports nested keys and environment variable substitution. ```python from envyaml import EnvYAML # read file env.yaml and parse config env = EnvYAML('env.yaml') # access project name print(env['project.name']) # >> simple-hello-42 # access whole database section print(env['database']) # { # 'database': 'test', # 'host': 'xxx.xxx.xxx.xxx', # 'password': 'super-secret-password', # 'port': 3301, # 'table': # { # 'blog': 'table_blog', # 'user': 'table_user' # }, # 'username': 'username' # } # access database host value as key item print(env['database.host']) # >> xxx.xxx.xxx.xxx # access database user table value as key item print(env['database.table.user']) # >> table_user # get sql query with $1,$2,$3 variables print(env['database.query']) # >> SELECT * FROM "users" WHERE "user" = $1 AND "login" = $2 AND "pwd" = $3 # using default values if variable not defined # one example is redis host and redis port, when $REDIS_HOST not set then default value will be used print(env['redis.host']) # >> 127.0.0.1 # one example is redis host and redis port, when $REDIS_DB not set then default value will be used print(env['redis.db']) # >> 3 # access list items by number print(env['list_test'][0]) # >> one # access list items by number as key print(env['list_test.1']) # >> two # test if you have key print('redis.port' in env) # >> True ``` -------------------------------- ### Accessing Lists and Complex Structures in YAML Source: https://context7.com/thesimj/envyaml/llms.txt Demonstrates how to access list items and nested structures within YAML configuration files using index and dot notation with EnvYAML. ```yaml # env.yaml servers: - host: server1.example.com port: 8080 - host: server2.example.com port: 8081 nested: items: - name: first config: enabled: true - name: second config: enabled: false ``` -------------------------------- ### Override Configuration with Keyword Arguments Source: https://context7.com/thesimj/envyaml/llms.txt Configuration values can be overridden or added at initialization time by passing keyword arguments to the `EnvYAML` constructor. This allows for dynamic configuration adjustments. ```python from envyaml import EnvYAML # Override values via kwargs env = EnvYAML( 'env.yaml', env_file='.env', PROJECT_NAME='overridden-project', CUSTOM_VALUE='new-value' ) print(env['PROJECT_NAME']) # Output: overridden-project print(env['CUSTOM_VALUE']) # Output: new-value ``` -------------------------------- ### Using Default Values in YAML Source: https://context7.com/thesimj/envyaml/llms.txt Demonstrates how default values specified in the YAML file are used when environment variables are not set. Setting an environment variable overrides the default. ```python from envyaml import EnvYAML # Load without setting environment variables env = EnvYAML('env.yaml') # Default values are used when env vars not set print(env['redis.host']) # Output: 127.0.0.1 print(env['redis.db']) # Output: 0 print(env['project.name']) # Output: my-app-1 # Set environment variable to override default import os os.environ['REDIS_HOST'] = 'redis.example.com' env2 = EnvYAML('env.yaml') print(env2['redis.host']) # Output: redis.example.com ``` -------------------------------- ### Load YAML with .env File Source: https://context7.com/thesimj/envyaml/llms.txt Load environment variables from a .env file alongside your YAML configuration. Ensure the .env file is in the same directory or specify its path. ```bash # .env file PROJECT_NAME=production-app PROJECT_ID=100 DATABASE_HOST=db.example.com DATABASE_PASSWORD=super-secret USERNAME=admin PASSWORD="secure-password" ``` ```yaml # env.yaml project: name: "${PROJECT_NAME}-${PROJECT_ID}" database: host: $DATABASE_HOST password: $DATABASE_PASSWORD credentials: user: $USERNAME pass: $PASSWORD ``` ```python from envyaml import EnvYAML # Load YAML with .env file env = EnvYAML('env.yaml', env_file='.env') print(env['project.name']) # Output: production-app-100 print(env['database.host']) # Output: db.example.com print(env['credentials.user']) # Output: admin print(env['credentials.pass']) # Output: secure-password ``` -------------------------------- ### EnvYAML Format Function Source: https://github.com/thesimj/envyaml/blob/main/README.md Use the `format` function to update placeholders within configuration values, similar to string formatting. ```python print(env.format('database.insert', table="users")) # >> INSERT INTO "users" (user, login) VALUES ($1, $2) ``` -------------------------------- ### Accessing Configuration Values with Bracket Notation Source: https://context7.com/thesimj/envyaml/llms.txt Access configuration values using dictionary-style bracket notation with dot-separated keys for nested values. Supports accessing list items by index and checking for key existence. ```python from envyaml import EnvYAML import os # Set environment variables os.environ['DATABASE_HOST'] = 'localhost' os.environ['DATABASE_PASSWORD'] = 'secret123' env = EnvYAML('env.yaml') # Access top-level values print(env['project.name']) # Output: myproject-42 # Access nested values with dot notation print(env['database.host']) # Output: localhost print(env['database.table.user']) # Output: table_user # Access entire sections as dictionaries print(env['database']) # Output: {'host': 'localhost', 'port': 3301, 'username': 'username', ...} # Access list items by index print(env['list_items'][0]) # Output: one # Access list items using dot notation print(env['list_items.1']) # Output: two # Check if key exists print('database.port' in env) # Output: True # Access SQL queries with positional parameters (not substituted) print(env['database.query']) # Output: SELECT * FROM "users" WHERE "user" = $1 AND "login" = $2 AND "pwd" = $3 ``` -------------------------------- ### Environ() - Access OS Environment Variables Source: https://context7.com/thesimj/envyaml/llms.txt Use the static environ() method to access the underlying OS environment variables. This provides a convenient way to interact with the operating system's environment. ```python from envyaml import EnvYAML import os os.environ['MY_VAR'] = 'test-value' env = EnvYAML('env.yaml') # Access os.environ through EnvYAML print(env.environ()['MY_VAR']) # Output: test-value # Same as os.environ print(env.environ() == os.environ) # Output: True # Use for environment checks if 'DEBUG' in env.environ(): print('Debug mode enabled') ``` -------------------------------- ### Strict Mode - Undefined Variables Source: https://context7.com/thesimj/envyaml/llms.txt Enable strict mode (default) to raise exceptions when undefined environment variables are referenced. Disable strict mode to allow undefined variables to remain as literals. ```yaml # env.yaml api: key: $UNDEFINED_API_KEY secret: $UNDEFINED_SECRET ``` ```python from envyaml import EnvYAML # Strict mode enabled by default - raises ValueError try: env = EnvYAML('env.yaml', strict=True) except ValueError as e: print(f"Error: {e}") # Output: Error: Strict mode enabled, variables $UNDEFINED_API_KEY, $UNDEFINED_SECRET are not defined! # Disable strict mode - undefined variables remain as literals env = EnvYAML('env.yaml', strict=False) print(env['api.key']) # Output: $UNDEFINED_API_KEY # Disable strict mode globally via environment variable import os os.environ['ENVYAML_STRICT_DISABLE'] = '' env = EnvYAML('env.yaml') # No exception even with strict=True ``` -------------------------------- ### Exclude OS Environment Variables Source: https://context7.com/thesimj/envyaml/llms.txt Use `include_environment=False` to load only YAML and .env file values, excluding OS environment variables. This is useful when you want to ensure a clean configuration without external system interference. ```python from envyaml import EnvYAML import os os.environ['PATH'] = '/usr/bin' os.environ['HOME'] = '/home/user' # Include OS environment (default) env_with_os = EnvYAML('env.yaml', include_environment=True) print('PATH' in env_with_os) # Output: True # Exclude OS environment env_without_os = EnvYAML('env.yaml', include_environment=False) print('PATH' in env_without_os) # Output: False # Only YAML and .env values available print(env_without_os['database.host']) # Output: localhost (from YAML) ``` -------------------------------- ### Accessing Escaped Dollar Signs Source: https://context7.com/thesimj/envyaml/llms.txt Demonstrates how to access values with escaped dollar signs using EnvYAML. Literal dollar signs are preserved in the output. ```python from envyaml import EnvYAML env = EnvYAML('env.yaml') print(env['escaped.price']) # Output: $99.99 print(env['escaped.variable']) # Output: $.extra print(env['escaped.password']) # Output: SomePa$$word print(env['escaped.template']) # Output: ${NOT_A_VARIABLE} ``` -------------------------------- ### Default Values in YAML Configuration Source: https://context7.com/thesimj/envyaml/llms.txt Specify default values directly in the YAML file using the pipe `|` syntax. These defaults are used when the corresponding environment variables are undefined. ```yaml # env.yaml with defaults redis: host: $REDIS_HOST|127.0.0.1 port: $REDIS_PORT|6379 db: $REDIS_DB|0 api: key: ${API_KEY|default-dev-key} timeout: ${TIMEOUT|30} project: name: "${PROJECT_NAME|my-app}-${PROJECT_ID|1}" ``` -------------------------------- ### EnvYAML Escaped Variables Source: https://github.com/thesimj/envyaml/blob/main/README.md Use double dollar signs (`$$`) to escape literal dollar signs in configuration values when environment variable substitution is not intended. ```python print(env['escaped']) # >> $.extra ``` -------------------------------- ### Escaping Dollar Signs in YAML Source: https://context7.com/thesimj/envyaml/llms.txt To include literal dollar signs (`$`) in your configuration values, use double dollar signs (`$$`). This prevents them from being interpreted as variable placeholders. ```yaml # env.yaml escaped: price: $$99.99 variable: $$.extra regex: $$[0-9]+ password: SomePa$$$word template: "$${NOT_A_VARIABLE}" ``` -------------------------------- ### Disable Flattening - Nested Structure Source: https://context7.com/thesimj/envyaml/llms.txt Disable the flatten option to preserve the original nested dictionary structure without dot-notation access. This is useful when you need to maintain the exact structure of your YAML. ```yaml # env.yaml config: database: host: localhost port: 5432 cache: enabled: true ``` ```python from envyaml import EnvYAML # With flatten=True (default) env_flat = EnvYAML('env.yaml', flatten=True) print(env_flat['config.database.host']) # Output: localhost # With flatten=False env_nested = EnvYAML('env.yaml', flatten=False) print(env_nested['config']['database']['host']) # Output: localhost # Dot notation not available when flatten=False print('config.database.host' in env_nested) # Output: False print('config' in env_nested) # Output: True ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.