Bird
0
0

You want to safely read an environment variable 'TIMEOUT' as an integer with a default of 30 if not set or invalid. Which code snippet correctly does this?

hard📝 Application Q8 of 15
Python - Standard Library Usage
You want to safely read an environment variable 'TIMEOUT' as an integer with a default of 30 if not set or invalid. Which code snippet correctly does this?
Atimeout = int(os.getenv('TIMEOUT', '30'))
Btry:\n timeout = int(os.getenv('TIMEOUT'))\nexcept (TypeError, ValueError):\n timeout = 30
Ctimeout = int(os.getenv('TIMEOUT')) if os.getenv('TIMEOUT') else 30
Dtimeout = int(os.environ['TIMEOUT']) or 30
Step-by-Step Solution
Solution:
  1. Step 1: Analyze each option for safety

    timeout = int(os.getenv('TIMEOUT', '30')) converts default string '30' but fails if TIMEOUT is set to invalid string. timeout = int(os.environ['TIMEOUT']) or 30 raises KeyError if missing. timeout = int(os.getenv('TIMEOUT')) if os.getenv('TIMEOUT') else 30 fails if TIMEOUT is invalid string. try:\n timeout = int(os.getenv('TIMEOUT'))\nexcept (TypeError, ValueError):\n timeout = 30 uses try-except to catch missing or invalid values safely.
  2. Step 2: Choose the safest approach

    try:\n timeout = int(os.getenv('TIMEOUT'))\nexcept (TypeError, ValueError):\n timeout = 30 handles missing and invalid values gracefully by catching exceptions and setting default.
  3. Final Answer:

    try:\n timeout = int(os.getenv('TIMEOUT'))\nexcept (TypeError, ValueError):\n timeout = 30 -> Option B
  4. Quick Check:

    Safe int read with default = try-except [OK]
Quick Trick: Use try-except to handle invalid or missing env vars safely [OK]
Common Mistakes:
  • Assuming default in getenv handles invalid strings
  • Using or 30 which doesn't catch exceptions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes