How to turn a variable name into a string?

Bengt Richter bokr at oz.net
Fri Mar 11 18:48:46 EST 2005


On 11 Mar 2005 12:39:30 -0800, "stewart.midwinter at gmail.com" <stewart.midwinter at gmail.com> wrote:

>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.,

 >>> import os
 >>> class MyEnv(dict):
 ...     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__
 ...
 >>> myenv = MyEnv('TMP OS')
 >>> myenv
 {'TMP': 'v:\\TEMP', 'OS': 'Windows_NT'}

The __getattr__ assignment lets you access the keys as attributes if you want:

 >>> myenv.TMP
 'v:\\TEMP'

If you try to init with some unknown env variable name, it complains:

 >>> me2 = MyEnv('TMP OS unknown')
 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



More information about the Python-list mailing list