Handling 3 operands in an expression without raising an exception

Νίκος nikos.gr33k at gmail.com
Thu Sep 26 06:18:41 EDT 2013


Στις 26/9/2013 1:12 μμ, ο/η Antoon Pardon έγραψε:
> Op 26-09-13 11:56, Νίκος schreef:
>> Στις 26/9/2013 11:55 πμ, ο/η Nobody έγραψε:
>>> On Thu, 26 Sep 2013 10:26:48 +0300, Νίκος wrote:
>>>
>>>> How can i wrote the two following lines so for NOT to throw out
>>>> KeyErrors when a key is missing?
>>>>
>>>> city = gi.time_zone_by_addr( os.environ['HTTP_CF_CONNECTING_IP'] ) or
>>>> gi.time_zone_by_addr( os.environ['REMOTE_ADDR'] ) or
>>>> "Άγνωστη Πόλη"
>>>
>>> tz = None
>>> ip = os.environ.get('HTTP_CF_CONNECTING_IP')
>>> if ip:
>>>     tz = gi.time_zone_by_addr(ip)
>>> if not tz:
>>>     ip = os.environ.get('REMOTE_ADDR')
>>>     if ip:
>>>       tz = gi.time_zone_by_addr(ip)
>>> if not tz:
>>>     tz = "ÎγνÏÏÏη Î Ïλη"
>>>
>>> Likewise for the hostname.
>>>
>>
>> Its logic is simple and straightforward but too many lines:
>>
>> host = socket.gethostbyaddr( os.environ.get('HTTP_CF_CONNECTING_IP') or
>> os.environ.get('REMOTE_ADDR') or  "Άγνωστη Προέλευση" )
>>
>> this is much better in my opinion and straighforward also and more clear
>> to read:
>
> No it is not and you prove that in the very next line.
>
>> it doens't work though:
>
> If it doesn't do what you think it should do then it is not straight
> forward or clear, at least not to you.

It is far better than the ifs, even easier to read, i was just missing a 
[0] at the end.

host = socket.gethostbyaddr( os.environ.get('HTTP_CF_CONNECTING_IP') or 
os.environ.get('REMOTE_ADDR') or  "Άγνωστη Προέλευση" )[0]




More information about the Python-list mailing list