Testing existance of variable
Alex Martelli
aleaxit at yahoo.com
Sun Oct 15 10:07:47 EDT 2000
"Steve George" <python-group at rascal.remove_this_bit.org> wrote in message
news:H5hG5.575$7u4.11173 at news.dircon.co.uk...
> 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.
One possibility, just for example:
enget = os.environ.get
remote_id = enget('REMOTE_HOST',None) or enget('REMOTE_ADDR', None)
Binding the bound method os.environ.get to the name enget is just a
minor abbreviation. The key is that method.get, which looks up a key
(first argument) and returns the second argument if the key's not there.
Python's "or" works quite like Perl's "||"...
Alex
More information about the Python-list
mailing list