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.
# 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 trueBut 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 trueEven 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.
# 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