I have a scenario where I need to store values from some environment variables (names of which I cannot control). My first run at this was pretty basic, however this is not usable as an exception would be raised for the first missing environment variable only. A requirement is the capture all missing environment variables and raise an exception listing them all.
For this, I have come up with two possible techniques, but I'm not sure which would be considered the most Pythonic, or whether there would be a better way of doing it?
Note that the name of the variable I store may not match the name of the environment variable (as some are very long, but I cannot change them).
Thoughts and criticisms on this techniques would be applicated.
Technique 1
Each environment variable is checked individually. While this looks reasonable, in reality there will be 15-20 environment variables to set.
environ_errors = []
environ1 = (os.environ.get('ENVIRON1')
or environ_errors.append('ENVIRON1'))
environ2 = (os.environ.get('ENVIRON2')
or environ_errors.append('ENVIRON2'))
environ3 = (os.environ.get('ENVIRON3_IS_A_REALLY_LONG_NAME')
or environ_errors.append('ENVIRON3_IS_A_REALLY_LONG_NAME'))
if len(environ_errors) > 0:
base_err = 'One or more required environment variables do not exist:'
err_msg = ('%s %s' % (base_err, ', '.join(environ_errors)))
raise Exception(err_msg)
Technique 2
Use a dict
to store the variable name and environment variable to target, then iterate over the dict
and update the value of each with the value of the corresponding environment variable.
My issue with this is that I won't be able to use python variables to represent each environment variable, but instead they are all in one dict
.
I'm also unsure if updating a dict
during a for
loop is considered Pythonic.
environs = {
'environ1': 'ENVIRON1',
'environ2': 'ENVIRON2',
'environ3': 'ENVIRON3_IS_A_REALLY_LONG_NAME'
}
environ_errors = []
for k, v in environs.items():
try:
environs[k] = os.environ[v]
except KeyError as e:
environs_error.append(e.args[0])
if len(environ_errors) > 0:
base_err = 'One or more required environment variables do not exist:'
err_msg = ('%s %s' % (base_err, ', '.join(environ_errors)))
raise Exception(err_msg)