Handling 3 operands in an expression without raising an exception

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

Îίκος

Στις 27/9/2013 1:55 πμ, ο/η Dave Angel έγÏαψε:
newlines are still cheap. And they can really help readability.


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

Steven D'Aprano

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


Can you please make it more clear for me?


variable = "default value"
try:
variable = something_that_might_fail()
except SomeException:
pass
 
Î

Îίκος

Στις 27/9/2013 12:26 μμ, ο/η Steven D'Aprano έγÏαψε:
variable = "default value"
try:
variable = something_that_might_fail()
except SomeException:
pass

Thanks Steven but this way i still have to declare the default string
sfor the variables:

Its no different than:

except socket.gaierror as e:
city = "Άγνωστη Πόλη"
host = "Άγνωστη ΠÏοέλευση"

Your way set the vars on top, the other way set the vars inside the
except block.
 
D

Dave Angel

Óôéò 27/9/2013 1:55 ðì, ï/ç Dave Angel Ýãñáøå:
Yes gi must be removed form within the try block because iam tesign it
for failure.

Then why don't you do it below?
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 = "¶ãíùóôç ÐñïÝëåõóç"

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
city = "¶ãíùóôç Ðüëç"
host = "¶ãíùóôç ÐñïÝëåõóç"
try:
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
pass
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.

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
city = None
host = None
try:
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
if not city:
city = "¶ãíùóôç Ðüëç"
if not host:
host = "¶ãíùóôç ÐñïÝëåõóç"

or:

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
city = None
host = None
try:
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
if not host:
host = "¶ãíùóôç ÐñïÝëåõóç"
if not city:
city = "¶ãíùóôç Ðüëç"

Note that in that last case, I tested the variables in the reverse
order. Note also on both of these that I assumed that None is not a
reasonable value for either of those. In fact, I also assume that an
empty string is not a reasonable value. If I didn't like the latter
assumption, I'd have used tests like if host is None:
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.

Ridiculous. But if you like code golf, you can always do:

city, host = "¶ãíùóôç Ðüëç", "¶ãíùóôç ÐñïÝëåõóç"

You should study APL. Many functions were written in one line, with
twenty lines of explanation. The function itself was considered
unreadable nonsense. And if a function stopped working, general wisdom
was to throw it out, and re-implement the explanation. I studied it
briefly in class in 1970, and have no idea if there are current
implementations.
 
Î

Îίκος

Στις 27/9/2013 1:43 μμ, ο/η Dave Angel έγÏαψε:
Στις 27/9/2013 1:55 πμ, ο/η Dave Angel έγÏαψε:
Yes gi must be removed form within the try block because iam tesign it
for failure.
Then why don't you do it below?
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 = "Άγνωστη ΠÏοέλευση"
ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
city = "Άγνωστη Πόλη"
host = "Άγνωστη ΠÏοέλευση"
try:
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
pass

Thanks for taking the time to expain this:

In the exact above solution of yours opposed to the top of mines is that
you code has the benefit of actually identifying the variable that
failed to have been assigned a value while in my code no matter what
variable failes in the try block i assign string to both 'city' and
'host' hence i dont really know which one of them is failing?

Di i understood it correctly?
 
D

Dave Angel

Óôéò 27/9/2013 1:43 ìì, ï/ç Dave Angel Ýãñáøå:
ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
city = "¶ãíùóôç Ðüëç"
host = "¶ãíùóôç ÐñïÝëåõóç"
try:
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
pass

Thanks for taking the time to expain this:

In the exact above solution of yours opposed to the top of mines is that

No idea what you mean here. I'll assume you're talking about the
version you DON'T quote here, the one with the if statements in the
except clause.
you code has the benefit of actually identifying the variable that
failed to have been assigned a value while in my code no matter what
variable failes in the try block i assign string to both 'city' and
'host' hence i dont really know which one of them is failing?

Yes, it has that advantage. Of course it doesn't USE that advantage for
anything so I'd go back to the pass version quoted immediately above.
Or I'd have two separate try/except clauses, one for each function call.
After all, the implication of the failure is different for each.

Di i understood it correctly?

I think so.
 
Î

Îίκος

Στις 27/9/2013 3:17 μμ, ο/η Dave Angel έγÏαψε:
Στις 27/9/2013 1:43 μμ, ο/η Dave Angel έγÏαψε:
ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
city = "Άγνωστη Πόλη"
host = "Άγνωστη ΠÏοέλευση"
try:
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
pass

Thanks for taking the time to expain this:

In the exact above solution of yours opposed to the top of mines is that

No idea what you mean here. I'll assume you're talking about the
version you DON'T quote here, the one with the if statements in the
except clause.
you code has the benefit of actually identifying the variable that
failed to have been assigned a value while in my code no matter what
variable failes in the try block i assign string to both 'city' and
'host' hence i dont really know which one of them is failing?

Yes, it has that advantage. Of course it doesn't USE that advantage for
anything so I'd go back to the pass version quoted immediately above.
Or I'd have two separate try/except clauses, one for each function call.
After all, the implication of the failure is different for each.

Di i understood it correctly?

I think so.

Thank you for everything, i appreciate your time and effort to help me
understand.
 
D

Denis McMahon

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 = "Άγνωστη ΠÏοέλευση"

Here is the basic problem: You're trying to do too many things at once in
a language you don't understand and without any understanding of the
fundamental underlying concepts of the systems that you're interfacing
with.

Break the task down into simpler steps and do the steps one at a time:

Calculate ipval

Calculate gi

If ipval is valid, calculate city, else give city a default value

If ipval is valid, calculate host, else give host a default value

Then consider which of the above needs to be contained within a try /
catch.

Finally, code them as 4 separate units of code, eg:

# instantiate geolocation by ip
gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')

# calculate ipval
try:
ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
except ( KeyError, TypeError ):
ipval = some_default

# try and obtain time zone from ip
try:
city = gi.time_zone_by_addr( ipval )
except (error type):
city = "Unknown City"

# try and obtain hostname from ip
try:
host = socket.gethostbyaddr( ipval ) [0]
except ( socket.gaierror ):
host = "Unknown Host"

Note that there is nothing special about writing it in as few lines as
code as possible. Writing it out in a way that is easy to understand and
follow helps make sure it actually works, and makes it a lot easier to
maintain in future.
 
G

Grant Edwards

Note that there is nothing special about writing it in as few lines as
code as possible.

Hah! That's what they _want_ you to think. First they get you hooked
on newlines, then the newline mine owners form a cartel and start
jacking up the prices. Then you'll wish you'd spent more time
learning to write Perl one-liners...
 
Î

Îίκος

Στις 27/9/2013 6:16 μμ, ο/η Denis McMahon έγÏαψε:
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 = "Άγνωστη ΠÏοέλευση"

Here is the basic problem: You're trying to do too many things at once in
a language you don't understand and without any understanding of the
fundamental underlying concepts of the systems that you're interfacing
with.

Break the task down into simpler steps and do the steps one at a time:

Calculate ipval

Calculate gi

If ipval is valid, calculate city, else give city a default value

If ipval is valid, calculate host, else give host a default value

Then consider which of the above needs to be contained within a try /
catch.

Finally, code them as 4 separate units of code, eg:

# instantiate geolocation by ip
gi = pygeoip.GeoIP('/usr/local/share/GeoIPCity.dat')

# calculate ipval
try:
ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
except ( KeyError, TypeError ):
ipval = some_default

# try and obtain time zone from ip
try:
city = gi.time_zone_by_addr( ipval )
except (error type):
city = "Unknown City"

# try and obtain hostname from ip
try:
host = socket.gethostbyaddr( ipval ) [0]
except ( socket.gaierror ):
host = "Unknown Host"

Note that there is nothing special about writing it in as few lines as
code as possible. Writing it out in a way that is easy to understand and
follow helps make sure it actually works, and makes it a lot easier to
maintain in future.


Sure your method follows the the logic in a straighforward way
step-by-step but i just dont want to spent almost 20 lines of code just
to calculate 2 variables(city and host).

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
city = "Άγνωστη Πόλη"
host = "Άγνωστη ΠÏοέλευση"
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:
print( "metrites.py => (%s): " % lastvisit, repr( sys.exc_info() ),
file=open('/tmp/err.out', 'w') )

The above code works in less lines of codes and because the assignment
of the vars happen before the try:/except: block, if something fails
during try: we can tell by looking at the values of city or host.

Also its being logged at the err.out too.
Only problem is that iam handlign address related issues and not the
case of when gi fails.

But i dont know how to do that.

except (error type): i saw in your code but iam not sure what exactly
this is supposed to handle.
 
N

Neil Cerutti

Sure your method follows the the logic in a straighforward way
step-by-step but i just dont want to spent almost 20 lines of
code just to calculate 2 variables(city and host).

Sure, eating with my mouth is straightforward and step-by-step,
but I just want to shove the food directly into my stomach.
 
G

Grant Edwards

Sure your method follows the the logic in a straighforward way
step-by-step but i just dont want to spent almost 20 lines of code just
to calculate 2 variables(city and host).

Does your provider charge you per line of code?

If all that matters is the number of lines of code then use this:

city,host = 0,0

Only _1_ nice short line of code.

Happy?
 
J

Joel Goldstick

Does your provider charge you per line of code?

If all that matters is the number of lines of code then use this:

city,host = 0,0

Only _1_ nice short line of code.

Happy?

--
Grant Edwards grant.b.edwards Yow! If Robert Di Niro
at assassinates Walter
Slezak,
gmail.com will Jodie Foster marry
Bonzo??


Better yet, don't write the program. Zero lines of code, and every line
works perfectly. It runs extremely fast too!

.... or Nikos the annoyance, write it in apl
 
M

Mark Lawrence

Does your provider charge you per line of code?

If all that matters is the number of lines of code then use this:

city,host = 0,0

Only _1_ nice short line of code.

Happy?

Classic overengineering, fancy wasting two whole spaces and having such
long names. Surely c,h=0,0 is vastly superior?
 
D

Denis McMahon

Classic overengineering, fancy wasting two whole spaces and having such
long names. Surely c,h=0,0 is vastly superior?

Why not c=h=0

2 characters (28%) shorter!
 
J

Joel Goldstick

And 47% more opaque!

--
Grant Edwards grant.b.edwards Yow! ... he dominates
the
at DECADENT SUBWAY SCENE.
gmail.com


better yet: i=l=0

The names have even less meaning, and they are thin -- less space
 
Î

Îίκος

Στις 27/9/2013 8:00 μμ, ο/η Grant Edwards έγÏαψε:
Does your provider charge you per line of code?

If all that matters is the number of lines of code then use this:

city,host = 0,0

Only _1_ nice short line of code.

Happy?

Well to tell the truth no matter what you say to me if something can be
written in less lines than another implementation but still retain its
simplicity and straightforward logic behind it i would prefer it!
I don't know why you think otherwise, especially people who are used to
write Perl code(me being one of them) would agree with me!

But in this case i cant use your examples even if i wanted too and thats
because the strings needed to be assigned to the 2 vars respectively are
different.

city = "Άγνωστη Πόλη"
host = "Άγνωστη ΠÏοέλευση"

If they were to have the same string assigned to them it should be okey
but they do not.

Or perhaps you can even still think of writing the above into 1-liner
whatsoever!

I wouldn't be surprised if you can! :)
 
D

Dave Angel

city = "¶ãíùóôç Ðüëç"
host = "¶ãíùóôç ÐñïÝëåõóç"

If they were to have the same string assigned to them it should be okey
but they do not.

Or perhaps you can even still think of writing the above into 1-liner
whatsoever!

I already did earlier in this thread. And you must have read the
message, because you replied to other parts of it. it's the one where I
referred to code golf, and to APL. About 12 hours ago, at 6:43 my time.

city, host = "¶ãíùóôç Ðüëç", "¶ãíùóôç ÐñïÝëåõóç"

I still think it's foolish, but be my guest.
 
C

Chris Angelico

Well to tell the truth no matter what you say to me if something can be
written in less lines than another implementation but still retain its
simplicity and straightforward logic behind it i would prefer it!
I don't know why you think otherwise, especially people who are used to
write Perl code(me being one of them) would agree with me!

It's high time you stopped trying to write Perl code that runs under
the Python interpreter, and started writing Python code that runs
under the Python interpreter.

There are rules. You first learn the rules and learn to code within
them; then later, once you actually achieve some measure of
competence, you begin learning when to break the rules.

ChrisA
 

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,776
Messages
2,569,602
Members
45,182
Latest member
BettinaPol

Latest Threads

Top