Interacting with Environment Variables: os.environ
`os.environ` is a mapping of OS environment variables. Use `os.environ.get('KEY', default)` to read configs and API keys safely without raising `KeyError` 🌍.
import os
db_host = os.environ.get("DB_HOST", "localhost")
print(f"Database host: {db_host} 🌍")
os.environ["APP_STAGE"] = "production"
print(f"Stage: {os.environ.get('APP_STAGE')} 🚀")
# 106. Interacting with Environment Variables: os.environ `os.environ` is a mapping of OS environment variables. Use `os.environ.get('KEY', default)` to read configs and API keys safely without raising `KeyError` 🌍. ```python import os db_host = os.environ.get("DB_HOST", "localhost") print(f"Database host: {db_host} 🌍") os.environ["APP_STAGE"] = "production" print(f"Stage: {os.environ.get('APP_STAGE')} 🚀") ``` Environment variables are always strings! If reading port numbers, remember to cast: `int(os.environ.get('PORT', '8080'))`! 🌍 --- ### Question What happens if you access `os.environ['NON_EXISTENT_VAR']` directly using square brackets? 🧠 - [ ] a. Raises a `KeyError` 🛑 - [ ] b. Returns None silently - [ ] c. Creates an empty variable in the operating system - [ ] d. Returns an empty string `""` --- ### Challenge Import `os`. Set `os.environ['SECRET_MODE'] = 'TRUE'`. Print `os.environ.get('SECRET_MODE')`. 🎯 <details> <summary>Solution</summary> ```python import os os.environ["SECRET_MODE"] = "TRUE" print(os.environ.get("SECRET_MODE")) ``` </details>