I want to check my environment for the existence of a variable, say "FOO"
, in Python. For this purpose, I am using the os
standard library. After reading the library's documentation, I have figured out 2 ways to achieve my goal:
Method 1:
if "FOO" in os.environ:
pass
Method 2:
if os.getenv("FOO") is not None:
pass
I would like to know which method, if either, is a good/preferred conditional and why.
This question is related to
python
python-2.7
python-3.x
if-statement
environment-variables
In case you want to check if multiple env variables are not set, you can do the following:
import os
MANDATORY_ENV_VARS = ["FOO", "BAR"]
for var in MANDATORY_ENV_VARS:
if var not in os.environ:
raise EnvironmentError("Failed because {} is not set.".format(var))
I'd recommend the following solution.
It prints the env vars you didn't include, which lets you add them all at once. If you go for the for loop, you're going to have to rerun the program to see each missing var.
from os import environ
REQUIRED_ENV_VARS = {"A", "B", "C", "D"}
diff = REQUIRED_ENV_VARS.difference(environ)
if len(diff) > 0:
raise EnvironmentError(f'Failed because {diff} are not set')
To be on the safe side use
os.getenv('FOO') or 'bar'
A corner case with the above answers is when the environment variable is set but is empty
For this special case you get
print(os.getenv('FOO', 'bar'))
# prints new line - though you expected `bar`
or
if "FOO" in os.environ:
print("FOO is here")
# prints FOO is here - however its not
To avoid this just use or
os.getenv('FOO') or 'bar'
Then you get
print(os.getenv('FOO') or 'bar')
# bar
When do we have empty environment variables?
You forgot to set the value in the .env
file
# .env
FOO=
or exported as
$ export FOO=
or forgot to set it in settings.py
# settings.py
os.environ['FOO'] = ''
Update: if in doubt, check out these one-liners
>>> import os; os.environ['FOO'] = ''; print(os.getenv('FOO', 'bar'))
$ FOO= python -c "import os; print(os.getenv('FOO', 'bar'))"
There is a case for either solution, depending on what you want to do conditional on the existence of the environment variable.
When you want to take different actions purely based on the existence of the environment variable, without caring for its value, the first solution is the best practice. It succinctly describes what you test for: is 'FOO' in the list of environment variables.
if 'KITTEN_ALLERGY' in os.environ:
buy_puppy()
else:
buy_kitten()
When you want to set a default value if the value is not defined in the environment variables the second solution is actually useful, though not in the form you wrote it:
server = os.getenv('MY_CAT_STREAMS', 'youtube.com')
or perhaps
server = os.environ.get('MY_CAT_STREAMS', 'youtube.com')
Note that if you have several options for your application you might want to look into ChainMap
, which allows to merge multiple dicts based on keys. There is an example of this in the ChainMap
documentation:
[...]
combined = ChainMap(command_line_args, os.environ, defaults)
My comment might not be relevant to the tags given. However, I was lead to this page from my search. I was looking for similar check in R and I came up the following with the help of @hugovdbeg post. I hope it would be helpful for someone who is looking for similar solution in R
'USERNAME' %in% names(Sys.getenv())
Source: Stackoverflow.com