Skip to content

Instantly share code, notes, and snippets.

@joewright
Created June 24, 2025 15:31
Show Gist options
  • Save joewright/1bc15b836a92f35567d0aee3a778a21a to your computer and use it in GitHub Desktop.
Save joewright/1bc15b836a92f35567d0aee3a778a21a to your computer and use it in GitHub Desktop.
Python -> more environment variable parsing notes

Dealing with environment variable type conversion in Python.

You've got a program that you want to configure using an OS environment variable - MY_VARIABLE.

The program

# my_program.py
import os

# parse the environment variable
if os.environ.get('MY_VARIABLE'):
  print("it's true")
  # do a thing
else:
  print("it's false")

When it's True, you want the program to print "it's true".

MY_VARIABLE=True my_program.py
# -> it's true

But we're only doing a truthy check, so unexpected behavior can happen when other people use your program and use unexpected values.

MY_VARIABLE=true my_program.py
# -> it's true
MY_VARIABLE=False my_program.py
# -> it's true
MY_VARIABLE=None my_program.py
# -> it's true

Be more explicit with your checks and your environment variable values

Even though we Know Better™, you can avoid confusion if you limit your environment variable values to their available type -> strings only.

And in your Python value check, you can be more explicit about the allowed variable values.

Program 2

# my_program2.py
import os

# parse the environment variable
if os.environ.get('MY_VARIABLE') == "YES":
  print("it's true")
  # do a thing
else:
  print("it's false")
MY_VARIABLE=YES my_program.py
# -> it's true
MY_VARIABLE=anything-else my_program.py
# -> it's false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment