Handling 3 operands in an expression without raising an exception

Dave Angel davea at davea.name
Thu Sep 26 16:37:40 EDT 2013


On 26/9/2013 12:58, Νίκος wrote:

   <snip>

> But actually i have 2 variables that relay on a proper ip address.
>
> ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or 
> os.environ.get('REMOTE_ADDR', "UnKnown Origin") )
> try:
> 	gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')
> 	city = gi.time_zone_by_addr( ipval )
> 	host = socket.gethostbyaddr( ipval ) [0]
> except socket.gaierror as e:
> 	city = host = "UnKnown Origin"

First concept:  A try/except should wrap one conceptual calculation.  In
this case, you have three.  So if the host lookup fails, you'll
overwrite the city you already presumably figured out.

You also don't do anything about an exception that might occur
calculating gi.  If one isn't possible, or if it's unrelated to the
other two, then that line should come OUT of the try-block.

What is city?  The function name implies it's a time zone, which is
presumably a float, -12 < x < +12.  If this is the case, then a string
is a lousy default value.

>
> But then what if in case of an error i needed different string set to be 
> assigned on city and host respectively?

Nothing limits the except clause to a single line.

>
> As i ahve it know in case of n address related error i get the smae 
> sting for both of them.
>
No idea what this is trying to say.

-- 
DaveA





More information about the Python-list mailing list