Handling 3 operands in an expression without raising an exception

  • Thread starter Îίκος
  • Start date
A

Antoon Pardon

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:
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.
 
Î

Îίκος

Στις 26/9/2013 1:41 μμ, ο/η Antoon Pardon έγÏαψε:
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:
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.

I'm surepirsed, becaus eon my domain [superhost.gr] the same lien of
code works withnout an error and it display the 'host' fileds properly.

Perhaps its failing via shell or you do not have a web server installed
to prepare the enviromental variables or i dont know what else to hink.

But in my website this code runs at the probelm with no problem.
 
J

James Harris

????? said:
???? 26/9/2013 12:07 ??, ?/? Antoon Pardon ??????:

I have tried code and also provided alternative code to solve my problem
which also doesn't solve it.

So, you cannot accuse me that i'm not trying, that would be the case to
just ask for a line without trying anything for myself, which i did twice.

Agreed. You did post the work you had already done which seems reasonable to
me.

For your first example, because you are worried about key errors maybe you
could code something like the following.

try:
city = gi.time_zone_by_addr( os.environ['HTTP_CF_CONNECTING_IP'] )
except KeyError:
try:
city = gi.time_zone_by_addr( os.environ['REMOTE_ADDR'] )
except KeyError:
city = "??????? ????"

Does that help?

James
 
A

Antoon Pardon

Op 26-09-13 12:51, Îίκος schreef:
Στις 26/9/2013 1:41 μμ, ο/η Antoon Pardon έγÏαψε:
Op 26-09-13 12:18, Îίκος schreef:
Στις 26/9/2013 1:12 μμ, ο/η Antoon Pardon έγÏαψε:
Op 26-09-13 11:56, Îίκος schreef:

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.

I'm surepirsed, becaus eon my domain [superhost.gr] the same lien of
code works withnout an error and it display the 'host' fileds properly.

You shoudn't be. This illustrates beautifully the difference between
understanding what one is doing and dabbling around until one stumbles
on something that currently works but that will stop working in other
circumstances.
Perhaps its failing via shell or you do not have a web server installed
to prepare the enviromental variables or i dont know what else to hink.

Yes it is failing via shell, but that doesn't matter. If your purpose
was to have that line working even if the environ variables were not
available, then the line should work from a shell too.
But in my website this code runs at the probelm with no problem.

So? That just means that your website is not a good test environment
for checking whether the code works under all circumstances you want
it to work.
 
D

Dave Angel

On 26/9/2013 06:51, Íßêïò wrote:

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.

I'm surepirsed, becaus eon my domain [superhost.gr] the same lien of
code works withnout an error and it display the 'host' fileds properly.

Perhaps its failing via shell or you do not have a web server installed
to prepare the enviromental variables or i dont know what else to hink.

But in my website this code runs at the probelm with no problem.
In Python 3.3, but not on a web server, I get:

import socket
socket.gethostbyaddr("unknown")[0]
Traceback (most recent call last):

Question, do you get the same result on your server? (You can put the
Greek string in place of "unknown" of course)

If so, then the default value makes no sense; it'll cause an exception
if it's ever used. If you insist on sticking to expressions (no
try/catch, no if statements), then perhaps you should default to a
string representing a domain which will always exist.
 
Î

Îίκος

Στις 26/9/2013 2:07 μμ, ο/η Antoon Pardon έγÏαψε:
Op 26-09-13 12:51, Îίκος schreef:
Στις 26/9/2013 1:41 μμ, ο/η Antoon Pardon έγÏαψε:
Op 26-09-13 12:18, Îίκος schreef:
Στις 26/9/2013 1:12 μμ, ο/η Antoon Pardon έγÏαψε:
Op 26-09-13 11:56, Îίκος schreef:

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.

I'm surepirsed, becaus eon my domain [superhost.gr] the same lien of
code works withnout an error and it display the 'host' fileds properly.

You shoudn't be. This illustrates beautifully the difference between
understanding what one is doing and dabbling around until one stumbles
on something that currently works but that will stop working in other
circumstances.
Perhaps its failing via shell or you do not have a web server installed
to prepare the enviromental variables or i dont know what else to hink.

Yes it is failing via shell, but that doesn't matter. If your purpose
was to have that line working even if the environ variables were not
available, then the line should work from a shell too.
But in my website this code runs at the probelm with no problem.

So? That just means that your website is not a good test environment
for checking whether the code works under all circumstances you want
it to work.
Okey then please tell me, what do you see wrong in it:

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

the [0] at then end in case the statemnt default to the string?
please tell me in details what might go wrong with it so i cna
understand it.
 
A

Antoon Pardon

Op 26-09-13 13:25, Îίκος schreef:
Okey then please tell me, what do you see wrong in it:

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

the [0] at then end in case the statemnt default to the string?
please tell me in details what might go wrong with it so i cna
understand it.

Startup python and try to figure it out yourself. Show us you can
really learn something.
 
Î

Îίκος

Στις 26/9/2013 2:24 μμ, ο/η Dave Angel έγÏαψε:
On 26/9/2013 06:51, Îίκος wrote:

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.

I'm surepirsed, becaus eon my domain [superhost.gr] the same lien of
code works withnout an error and it display the 'host' fileds properly.

Perhaps its failing via shell or you do not have a web server installed
to prepare the enviromental variables or i dont know what else to hink.

But in my website this code runs at the probelm with no problem.
In Python 3.3, but not on a web server, I get:

import socket
socket.gethostbyaddr("unknown")[0]
Traceback (most recent call last):

Question, do you get the same result on your server? (You can put the
Greek string in place of "unknown" of course)

If so, then the default value makes no sense; it'll cause an exception
if it's ever used. If you insist on sticking to expressions (no
try/catch, no if statements), then perhaps you should default to a
string representing a domain which will always exist.

Yes, you are right, in my shell it fails too givign the same error
message as yours, while on the other had in the websste is working.

Can you explain this please?
why doesnt it fail to both enviroments?
 
A

Antoon Pardon

Op 26-09-13 14:39, Îίκος schreef:
Yes, you are right, in my shell it fails too givign the same error
message as yours, while on the other had in the websste is working.

Can you explain this please?
why doesnt it fail to both enviroments?

Your site and your shell are two different environments. The state
of the website environment lets your code succeed while the state
of the shell environment, doesn't.
 
Î

Îίκος

Στις 26/9/2013 3:53 μμ, ο/η Antoon Pardon έγÏαψε:
Op 26-09-13 14:39, Îίκος schreef:

Your site and your shell are two different environments. The state
of the website environment lets your code succeed while the state
of the shell environment, doesn't.
What modification does it need to also work in the shell environmentthe
[0] at the end is what complicates things.
 
D

Dave Angel

Óôéò 26/9/2013 3:53 ìì, ï/ç Antoon Pardon Ýãñáøå:
Op 26-09-13 14:39, Íßêïò schreef:

Your site and your shell are two different environments. The state
of the website environment lets your code succeed while the state
of the shell environment, doesn't.
What modification does it need to also work in the shell environmentthe
[0] at the end is what complicates things.

Not at all. What complicates/confuses things is trying to do too much
in one line.

The line is trying to solve two separate things. You might now
understand the first of them; the fetching of multiple environment
variables that may or may not exist.

The second thing is the function call to gethostbyname(). If fed
invalid data, this call will throw an exception. So you need to either
put it in a try/catch or somehow pretend that you can know what
constitutes invalid data. One example of invalid data is your default
string. Another might be if one of those environment variables exists,
but isn't reasonable. And a third might be if the domain server
temporarily refuses to recognize a valid hostname.

I'd say you need to put the gethostbyname() in a try/catch, and then
supply some reasonable bogus string for host. Only you will know what
to use there; depending on what you're going to use it for.


ipval = (os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Please throw a gaierror exception")
try:
host = socket.gethostbyaddr(ipval) [0]
except socket.gaierror as exc;
host = "Unknown host"

I don't know the gethostbyaddr(), so i don't know if there are other
exceptions you should also try to catch.
 
D

Denis McMahon

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

Perhaps you need something that looks more like:

some_value = some_function_of( some_value ) or some_function_of
( some_value )
if some_value:
host = some_function_of( some_value )
else:
host = some_value

or even:

try:
host = some_function_of( some_function_of( some_value ) or
some_function_of( some_value ) )
except some_error_type [ or some_error_type .... ]:
host = some_value
 
D

Denis McMahon

Its logic is simple and straightforward but too many lines:

There is no "too many lines."
this is much better in my opinion and straighforward also and more clear
to read ... it doens't work though:

This is just a stupid attitude for a coder to have.
 
D

Denis McMahon

Okey then please tell me, what do you see wrong in it:

socket.gethostbyaddr( os.environ.get('HTTP_CF_CONNECTING_IP')

If os.environ.get('HTTP_CF_CONNECTING_IP') is false
or os.environ.get('REMOTE_ADDR')

and os.environ.get('REMOTE_ADDR') is false
or "Άγνωστη ΠÏοέλευση" )[0]

The you try and get the host name from the ip address "Άγνωστη
ΠÏοέλευση", but "Άγνωστη ΠÏοέλευση" is not an ip address, so you get an
error.
 
Î

Îίκος

Στις 26/9/2013 5:22 μμ, ο/η Dave Angel έγÏαψε:
Στις 26/9/2013 3:53 μμ, ο/η Antoon Pardon έγÏαψε:
Op 26-09-13 14:39, Îίκος schreef:
Yes, you are right, in my shell it fails too givign the same error
message as yours, while on the other had in the websste is working.

Can you explain this please?
why doesnt it fail to both enviroments?

Your site and your shell are two different environments. The state
of the website environment lets your code succeed while the state
of the shell environment, doesn't.
What modification does it need to also work in the shell environmentthe
[0] at the end is what complicates things.

Not at all. What complicates/confuses things is trying to do too much
in one line.

The line is trying to solve two separate things. You might now
understand the first of them; the fetching of multiple environment
variables that may or may not exist.

The second thing is the function call to gethostbyname(). If fed
invalid data, this call will throw an exception. So you need to either
put it in a try/catch or somehow pretend that you can know what
constitutes invalid data. One example of invalid data is your default
string. Another might be if one of those environment variables exists,
but isn't reasonable. And a third might be if the domain server
temporarily refuses to recognize a valid hostname.

I'd say you need to put the gethostbyname() in a try/catch, and then
supply some reasonable bogus string for host. Only you will know what
to use there; depending on what you're going to use it for.


ipval = (os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Please throw a gaierror exception")
try:
host = socket.gethostbyaddr(ipval) [0]
except socket.gaierror as exc;
host = "Unknown host"

I don't know the gethostbyaddr(), so i don't know if there are other
exceptions you should also try to catch.

Indeed this logic you follow is hethe best i have seen so far.
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"

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

As i ahve it know in case of n address related error i get the smae
sting for both of them.
 
D

Denis McMahon

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"
 
D

Dave Angel

On 26/9/2013 12:58, Íßêïò wrote:

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.
 
Î

Îίκος

Στις 26/9/2013 11:16 μμ, ο/η Denis McMahon έγÏαψε:
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.

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"
 
D

Dave Angel

Óôéò 26/9/2013 11:16 ìì, ï/ç Denis McMahon Ýãñáøå:

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.
 
A

alex23

You dont have to be ironic. I dont have the experience you do.

This is bulshytt. You only just a few days ago started a thread in which
handling lookups in dictionaries with potentially non-existent keys was
dealt with. At length. And now you're restructuring pretty much the
exact same question to troll the list. Again.

You're either not reading what people are saying, not trying to
understand things by working with simpler examples at the interpreter,
or just flat out lying. In any case, you're not acting in good faith.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top