lots of good answers there, and quickly, too!
I can see that I need to explain a bit further what I'm up to.
I have a number of variables (environmental variables, actually), most
of which will have a value. But some may not have been found by
os.environ.get(), so I set those to None. Now, if any of them are None,
the app cannot proceed, so I want to test for this and warn the user.
I could do something like this (actually, there are more than 3 vars):
a = "c:\\programs"
b = "d:\\data"
c = None (result of an assignment after the os.environ.get() returned
a KeyError).
if (a is None) or (b is None) or (c is None):
#do something here
print 'you are missing some env vars'
But, that seemed clumsy to me, so I wanted to do something more
pythonic, hence my previous post. So, any suggestions?
If you require a specific set of environment variables to be defined,
why don't you create an object that loads them and validates itself
in the process? E.g.,
... def __init__(self, required=''):
... for name in required.split():
... self[name] = os.environ.get(name)
... if None in self.values():
... raise ValueError, 'You are missing some env vars: %r' % [k for k,v in self.items() if v is None]
... __getattr__ = dict.__getitem__
... {'TMP': 'v:\\TEMP', 'OS': 'Windows_NT'}
The __getattr__ assignment lets you access the keys as attributes if you want:
'v:\\TEMP'
If you try to init with some unknown env variable name, it complains:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 6, in __init__
ValueError: You are missing some env vars: ['unknown']
If you have spaces in your environment names (possible?) that would be nasty and
you would have to change the "required" __init__ parameter to split on something other than spaces.
You could arrange for case-insensitivity if you liked. And if you really wanted
to have local or global bindings for your env names, you could easily do that too,
but e.g., myenv.XXX seems like a readable way to group things together.
Regards,
Bengt Richter