Testing existance of variable

Steve George python-group at rascal.remove_this_bit.org
Sun Oct 15 11:52:39 EDT 2000


In article <etdy9zqnvw5.fsf at w20-575-86.mit.edu>, Alex <the_brain at mit.edu>
wrote:
> 
>> 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.
> 
> Try this:
> 
> new_remote_id = os.environ.get('REMOTE_HOST') or \
>                 os.environ.get('REMOTE_ADDR')
> if new_remote_id:
>     remote_id = new_remote_id
> 
> Alex.
> 

Thanks Alex - that's just the operation I wanted. According to the Quick
Python Book I can also use it to provide a default in case the environment
doesn't have that variable:

remote_id = os.environ.get('REMOTE_HOST') or \
			os.environ.get('REMOTE_ADDR', 'empty')

Steve





More information about the Python-list mailing list