Handling 3 operands in an expression without raising an exception

Νίκος nikos.gr33k at gmail.com
Fri Sep 27 05:19:53 EDT 2013


Στις 27/9/2013 1:55 πμ, ο/η Dave Angel έγραψε:
> On 26/9/2013 18:14, Νίκος wrote:
>
>> Στις 26/9/2013 11:16 μμ, ο/η Denis McMahon έγραψε:
>>> On Thu, 26 Sep 2013 19:58:02 +0300, Νίκος wrote:
>>>
>>>> except socket.gaierror as e:
>>>> 	city = host = "UnKnown Origin"
>>>>
>>>> But then what if in case of an error i needed different string set to be
>>>> assigned on city and host respectively?
>>>
>>> Oh FFS
>>>
>>> Are you serious when you ask this?
>>>
>>> Simply change:
>>>
>>> except socket.gaierror as e:
>>>       city = host = "UnKnown Origin"
>>>
>>> To:
>>>
>>> except socket.gaierror as e:
>>>       city = "Unknown City"
>>>       host = "Unknown Host"
>>
>> Yes indeed that was an idiotic question made by me, but i was somehow
>> feeling again that i should handle it in one-liner, avoid wanting to use
>> 2 statements.
>
> newlines are still cheap.  And they can really help readability.
>
>> I wonder if there is a way to assign the string "Unknown Origin" to the
>> variable that failed in the try block to get a value.
>>
>> Can i describe that somehow inside the except block?
>>
>> I mean like:
>>
>> except socket.gaierror as e:
>> 	what_ever_var_failed = "Unknown Origin"
>
> Simply assign the default values BEFORE the try block, and use pass as
> the except block.
>
> That still doesn't get around the inadvisability of putting those 3
> lines in the try block.
>
> You still haven't dealt with the gt assignment and its possible
> exception.
>
Yes gi must be removed form within the try block because iam tesign it 
for failure.

I'am not sure what you mean though when you say:

> Simply assign the default values BEFORE the try block, and use pass as
> the except block.

Can you please make it more clear for me?

This is my code as i have it at the moment:

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or 
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
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 = "Άγνωστη Προέλευση"

Or even better since i actually use 3 vars inside the try block it would 
be really neat to be able to detect which far failed and assign a 
specific value variable failed depended.

IF it can also be written in one-line afteer the excpect would be even 
better. Call me persistent but when i can write somethign in 1-line i 
wou;d prefer it over 3-lines.



More information about the Python-list mailing list