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)