Kshitij Saraogi Kshitij Saraogi - 1 month ago 8
Python Question

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

, in Python. For this purpose, I am using the
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.


Use the first; it directly tries to check if something is defined in environ. The second form works equally well but lacks sense since you actually get a value back if it exists and don't use it.

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:

if environ.get('Foo') is not None: