The Python Oracle

Checking if an environment variable exists and is set to True

--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzling Curiosities

--

Chapters
00:00 Checking If An Environment Variable Exists And Is Set To True
00:22 Answer 1 Score 10
00:34 Answer 2 Score 0
00:44 Answer 3 Score 1
00:56 Accepted Answer Score 15
01:27 Thank you

--

Full question
https://stackoverflow.com/questions/4450...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python27 #python3x #environmentvariables

#avk47



ACCEPTED ANSWER

Score 15


You can check to see if the variable is in the dictionaries returned by globals() and locals(). (Thank you to Aaron for reminding me to add the full code)

For a local variable:

if locals().get('abc'):
    print(abc)

For a global variable:

if globals().get('abc'):
    print(abc)

For an environment variable:

if os.environ.get('abc')=='True':
    #abc is set to True

More information here:

https://docs.python.org/3/library/functions.html#locals https://docs.python.org/3/library/functions.html#globals




ANSWER 2

Score 10


You can use:

env.get("abc", False)

False is the default value if "abc" is not in env.




ANSWER 3

Score 1


You could use a Try Except Block.

try:
    # Try calling ABC here anyway you like
    # Here I am just printing it
    print(abc)
except NameError:
    print("Variable ABC does not exist")



ANSWER 4

Score 0


It's enough get it from env, I think

env.get('abc')