Skip to content
shellhacks.dev
Python

Read an Environment Variable with a Default in Python

Read an environment variable with os.environ.get("NAME", "default"). An empty string counts as set, so add or default to treat it as missing, and convert the type.

1 min read
Summarize in AI

A script reads its settings from the environment, and a variable that is set but empty does not use the default you wrote.

Python
import os

os.environ["EMPTY"] = ""
print(repr(os.environ.get("MISSING", "fallback")))
print(repr(os.environ.get("EMPTY", "fallback")))
print(repr(os.environ.get("EMPTY") or "fallback"))
port = int(os.environ.get("PORT", "8080"))
print(port + 1)
try:
    os.environ["MISSING"]
except KeyError as e:
    print("KeyError:", e)
Text
'fallback'
''
'fallback'
8081
KeyError: 'MISSING'

os.environ behaves like a dictionary, so get returns the default only when the key is absent. An empty value is a value, which the second line shows, and the or form replaces it too. Environment values are always strings, so a number needs int() and the default must be a string if it goes through the same conversion. Indexing with brackets raises KeyError for an unset name, described in the os.environ documentation.

os.getenv(name, default) is a shortcut with the same rules. Use brackets when the variable is required, so a missing one stops the program with a clear name and not a later None error. bool(os.environ.get("DEBUG")) is true for the string "0" and "false", so compare against the strings you accept.

Share

More snippets

Python

Read a TOML File in Python with tomllib

Read a TOML file with tomllib.load in Python 3.11 or later. Open the file in binary mode, or it raises TypeError, and use tomllib.loads for a string.

1 min read

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.