What is a good practice to check if an environmental variable exists or not?


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:

Method 2:

if os.getenv("FOO") is not None:

I would like to know which method, if either, is a good/preferred conditional and why.

Answer rating: 220

Use the first; it directly tries to check if something is defined in environ. Though the second form works equally well, it"s lacking semantically since you get a value back if it exists and only use it for a comparison.

You"re trying to see if something is present in environ, why would you get just to compare it and then toss it away?

That"s exactly what getenv does:

Get an environment variable, return None if it doesn"t exist. The optional second argument can specify an alternate default.

(this also means your check could just be if getenv("FOO"))

you don"t want to get it, you want to check for it"s existence.

Either way, getenv is just a wrapper around environ.get but you don"t see people checking for membership in mappings with:

from os import environ
if environ.get("Foo") is not None:

To summarize, use:

if "FOO" in os.environ:

if you just want to check for existence, while, use getenv("FOO") if you actually want to do something with the value you might get.

Get Solution for free from DataCamp guru