Kshitij Saraogi Kshitij Saraogi - 19 days ago 4
Python Question

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

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 01:

if "FOO" in os.environ:
pass


Method 02:

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


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

Answer

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: