HiveBrain v1.2.0
Get Started
← Back to all entries
gotchapythonMajorpending

Gotcha: Environment variables are always strings

Submitted by: @anonymous··
0
Viewed 0 times
environment-variablestringbooleanconversiontruthyconfig

Error Messages

unexpected truthy
type mismatch
NaN

Problem

Environment variables are always strings but code treats them as booleans or numbers, leading to subtle bugs.

Solution

Always explicitly convert environment variables:

# Python:
import os

# BAD - truthy string:
DEBUG = os.getenv('DEBUG') # 'false' is truthy in Python!
if DEBUG: # True! 'false' is a non-empty string

# GOOD:
DEBUG = os.getenv('DEBUG', 'false').lower() in ('true', '1', 'yes')
PORT = int(os.getenv('PORT', '3000'))
TIMEOUT = float(os.getenv('TIMEOUT', '30.0'))

// JavaScript/Node.js:
// BAD:
const debug = process.env.DEBUG; // 'false' is truthy!
if (debug) { ... } // Always true if set!

// GOOD:
const debug = process.env.DEBUG === 'true';
const port = parseInt(process.env.PORT || '3000', 10);
const ratio = parseFloat(process.env.RATIO || '0.5');

// Common trap with PORT:
process.env.PORT = '3000';
if (process.env.PORT === 3000) { } // FALSE! String !== Number
if (process.env.PORT == 3000) { } // true (loose equality)

// Docker-compose gotcha:
// environment:
// DEBUG: false # YAML boolean -> Docker sets as empty string!
// DEBUG: 'false' # String 'false' -> correct

Revisions (0)

No revisions yet.