Op 26-09-13 12:18, Νίκος schreef: > Στις 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]
No it is not. Your purpose was to have a line that wouldn't throw an exception even if some environ variables were not available. That means it shouldn't throw an exception when I execute the code. Guess what happens: >>> socket.gethostbyaddr( os.environ.get('HTTP_CF_CONNECTING_IP') or os.environ.get('REMOTE_ADDR') or "Άγνωστη Προέλευση" )[0] Traceback (most recent call last): File "<stdin>", line 1, in <module> socket.gaierror: [Errno -2] Name or service not known You are just illustrating your lack of basic understaning. -- Antoon Pardon -- https://mail.python.org/mailman/listinfo/python-list