Testing existance of variable

Steve George python-group at rascal.remove_this_bit.org
Sun Oct 15 09:42:40 EDT 2000


Hi,

I've just started playing with Python and CGI and need to know if
something exists in the environment.  According to the O'Reilly CGI text
you would do this in Perl as follows:

my $remote_id = $ENV{REMOTE_HOST} || $ENV{REMOTE_ADDR};

I can't seem to find a Python equivalent.  As far as I have got is:

if os.environ.has_key('REMOTE_HOST') or os.environ.has_key('REMOTE_ADDR'):
        remote_id = os.environ['REMOTE_HOST'] or os.environ['REMOTE_ADDR']

However, this fails with an exception for KeyError if one of them doesn't
exist.  The only thing I can think to do is to try and catch the exception,
but this feels so long winded that I wondered if there is a shorter
answer.

Thanks,

Steve




More information about the Python-list mailing list