Handling 3 operands in an expression without raising an exception

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

Antoon Pardon

Op 29-09-13 09:35, Îίκος schreef:
Στις 29/9/2013 2:04 πμ, ο/η Chris Angelico έγÏαψε:

Its not that i don't listen, its that i want something to be implemented
in a specific way.

Why? What is so important about this particular way, that you are
willing to spend/waste so much time on it? You act like someone
who want to get from Brussels to London and when asked how to
do that gets advise on how to take the boat or plane at which
point you react that you want to get to Londen without boat
or plane but just by bicycle. And in further exchange make it
clear that using a bike is more important than arriving in London.

So please why do you make it your priority to implement it in a
specific way, over it working correctly?
 
D

Dave Angel

Óôéò 29/9/2013 12:50 ìì, ï/ç Dave Angel Ýãñáøå:
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:
gi,city,host=globals().get("gi", "who knows"), globals().get("city",
"¶ãíùóôç Ðüëç"), globals().get("host", "¶ãíùóôç
ÐñïÝëåõóç")

Hello Dave,

By looking at your code i think that you are tellign the progrma to try
to gri don't know what the function globals() is supposed to do

Try help(globals()) at the interpreter prompt.

Help on built-in function globals in module builtins:

globals(...)
globals() -> dictionary

Return the dictionary containing the current scope's global variables.

So once you have a dictionary, you can use get() to fetch values which
might or not be present, and supply the default in case they aren't.
but i was thinking more of:

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
try:
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
# We need something here to identify which one of the 2 above variables
or even both of them went wrong, and then assign the appropriate value
to each one of them but i don't know how to write it.

Is there a function that can tell us which variable failed to be
assigned a value that we can use in order to decide to which variable we
will

I showed you the only 3 ways I know of, and none of them is as readable
as just setting the defaults in the standard way.

I only showed you those in order to show you how unreadable it would be.
 
J

Jussi Piitulainen

Steven said:
Bad advice, and buggy as well.

py> city = "New New York"
py> ('city' in locals() or "Blah blah")
True

Oh man, can you imagine Nikos trying to debug that?

Thanks. Sorry. This hurts. I didn't mean it to be buggy.

Let's see. The task is to assign a default value to city and host, if
they haven't a value yet; on one line (which I take to mean one
statement); in an "except" block where we may not know which
assignment failed in the "try" block; without "if"; but "or" is
allowed.

But the logic I was trying to implement is

city, host = ( (city if 'city' in locals() else "default city"),
(host if 'host' in locals() else "default host") )

which uses an "if". The old tricks of using "or" and stuff for this
would surely go too far.

I know!

city, host = ( locals().get('city', "default city"),
locals().get('host', "default host") )

Testing if the variables only exists when actually assigned:
... if x: foo = None
... if y: bar = "bar"
... return locals()
...{'y': True, 'x': False, 'bar': 'bar'}

Seems so.

What a monster, though. I don't even want to know if this, too, is
buggy in some way. It looks fragile.

Nikos, don't do this. The way to test if an assignment failed is to
use a try-catch. The way to know which one failed is to put each in
its own try-catch.
 
Î

Îίκος

Στις 29/9/2013 12:50 μμ, ο/η Dave Angel έγÏαψε:
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:
gi,city,host=globals().get("gi", "who knows"), globals().get("city",
"Άγνωστη Πόλη"), globals().get("host", "Άγνωστη
ΠÏοέλευση")

Hello Dave,

By looking at your code i think that you are tellign the progrma to try
to gri don't know what the function globals() is supposed to do

but i was thinking more of:

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
try:
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
# We need something here to identify which one of the 2 above variables
or even both of them went wrong, and then assign the appropriate value
to each one of them but i don't know how to write it.

Is there a function that can tell us which variable failed to be
assigned a value that we can use in order to decide to which string we
weill be defaulting to?
 
Î

Îίκος

Στις 29/9/2013 2:04 μμ, ο/η Jussi Piitulainen έγÏαψε:
Thanks. Sorry. This hurts. I didn't mean it to be buggy.

Let's see. The task is to assign a default value to city and host, if
they haven't a value yet; on one line (which I take to mean one
statement); in an "except" block where we may not know which
assignment failed in the "try" block; without "if"; but "or" is
allowed.

But the logic I was trying to implement is

city, host = ( (city if 'city' in locals() else "default city"),
(host if 'host' in locals() else "default host") )

which uses an "if". The old tricks of using "or" and stuff for this
would surely go too far.

I know!

city, host = ( locals().get('city', "default city"),
locals().get('host', "default host") )

I tend to like this: I might use it because it is a clear way to tell
what var failed in the try clause and default it to soemthing.

Testing if the variables only exists when actually assigned:

... if x: foo = None
... if y: bar = "bar"
... return locals()
...
{'y': True, 'x': False, 'bar': 'bar'}

Seems so.

What a monster, though. I don't even want to know if this, too, is
buggy in some way. It looks fragile.

Nikos, don't do this. The way to test if an assignment failed is to
use a try-catch. The way to know which one failed is to put each in
its own try-catch.

Dave's way though seems better.
Assign the vars default string and if they get re-assinged correctly
that would be ideal, otherwise we have already given them the defaults.

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 Exception as e:
print( "metrites.py => (%s): " % lastvisit, repr( sys.exc_info() ),
file=open('/tmp/err.out', 'w') )

I'll think i'll stick to this solution.
 
D

Dave Angel

Dave's way though seems better.
Assign the vars default string and if they get re-assinged correctly
that would be ideal, otherwise we have already given them the defaults.

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 Exception as e:
print( "metrites.py => (%s): " % lastvisit, repr( sys.exc_info() ),
file=open('/tmp/err.out', 'w') )

I'll think i'll stick to this solution.

But you've put gi back in to the try-block. If it really belongs there,
then you'd better give it a default value as well. On the other hand,
if it can't get an exception, you should move it out.
 
Î

Îίκος

Στις 29/9/2013 2:27 μμ, ο/η Dave Angel έγÏαψε:
Dave's way though seems better.
Assign the vars default string and if they get re-assinged correctly
that would be ideal, otherwise we have already given them the defaults.

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 Exception as e:
print( "metrites.py => (%s): " % lastvisit, repr( sys.exc_info() ),
file=open('/tmp/err.out', 'w') )

I'll think i'll stick to this solution.

But you've put gi back in to the try-block. If it really belongs there,
then you'd better give it a default value as well. On the other hand,
if it can't get an exception, you should move it out.

You are right i just put it there because its being relevant to the
whole geoip things. Givign it a default value will not really help much
because i'am not printing it later on it just is necessay to poitn to an
existing geopip file in plcace.

If it fails to be assinged then i will just cat /etc/err/out and see
that it erred out and then take action to fix it.
 
J

Jussi Piitulainen

Îίκος said:
ΣÏις 29/9/2013 2:04 μμ, ο/η Jussi Piitulainen
έγÏαÏε:


I tend to like this: I might use it because it is a clear way to
tell what var failed in the try clause and default it to soemthing.

Well, I think it's as close to what you asked as I can get. Seeing it
in a real program would make me nervous, though. I shouldn't have
brought it up at all.

[...]
Dave's way though seems better.
Assign the vars default string and if they get re-assinged correctly
that would be ideal, otherwise we have already given them the defaults.

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 Exception as e:
print( "metrites.py => (%s): " % lastvisit, repr(
sys.exc_info() ), file=open('/tmp/err.out', 'w') )

I'll think i'll stick to this solution.

Yes, that's a serious way to do it. (Except the destination of the
error message probably isn't.)
 
C

Chris Angelico

Try help(globals()) at the interpreter prompt.

Help on built-in function globals in module builtins:

globals(...)
globals() -> dictionary

Return the dictionary containing the current scope's global variables.

Insignificant quibble: help(globals()) will give you help on the dict
type. What you actually want here is help(globals). Otherwise agreed.

ChrisA
 
G

giacomo boffi

Íßêïò said:
IF it can also be written in one-line

def f(x,n,w):return(lambda y=f(x[::2],n/2,w[::2]),z=f(x[1::2],n/2,w[::2]):reduce(lambda x,y:x+y,zip(*[(y[k]+w[k]*z[k],y[k]-w[k]*z[k]) for k in range(n/2)])))()if n>1 else x
 
J

Joel Goldstick

Îίκος said:
IF it can also be written in one-line

def f(x,n,w):return(lambda
y=f(x[::2],n/2,w[::2]),z=f(x[1::2],n/2,w[::2]):reduce(lambda
x,y:x+y,zip(*[(y[k]+w[k]*z[k],y[k]-w[k]*z[k]) for k in range(n/2)])))()if
n>1 else x


I've been reading along and learning some really obscure coding patterns.
The missing part is the why.
Antoon asks:

Why? What is so important about this particular way, that you are
willing to spend/waste so much time on it?

This question goes completely unnoticed. In the big picture this seems to
be the pattern. Nikos asks a question that shows fundamental flaws in his
understanding of a problem. People probe to understand what he really
wants. He ignores everything except little coding snippets, and requests
different choices on and on. Its like a fussy shopper wanting to see
endless dresses, and in the end choosing none. I don't think any of Nikos
questions have anything to do with finding an answer, because if you dig
deeper into the questions they end up being only red herrings.

As I pointed out yesterday he still hasn't fixed the fact that his python
files on his server are set with permissions to read the code which
contains passwords in plain text. That was the big drama from June

So, Antoon, I think the question is why are 'we' wasting so much time.
Nikos is just the orchestrator. He isn't wasting any time. He isn't doing
anything.

Here's my question: I wonder if Nikos has ever been employed to write
software. If so, I wonder how long he lasted before he was let go. And I
feel bad for the guy who had to support his code!
 
C

Chris Angelico

Here's my question: I wonder if Nikos has ever been employed to write
software. If so, I wonder how long he lasted before he was let go.

Unfortunately that proves nothing. My boss used to have another
employee besides me - he lasted for several years before he finally
quit (wasn't fired). In retrospect, my boss wishes he'd fired him a
lot sooner, but hindsight is 20/20, they say. We've since ripped out
every line of code this guy wrote and rewritten from scratch. No,
merely holding down a job doesn't prove anything more than that your
boss hasn't gone through and evaluated your code. In my example, it
was because the boss was too busy (he knew stuff was taking a long
time to get written and debugged, he didn't know it was because the
code was trash); in other cases, I have no doubt, it's because the
boss has no clue what makes good code. That's why he hired a
programmer, after all - to do what he can't do himself. It's
unfortunately not difficult for someone to be employed to do something
he's utterly incompetent to do.

ChrisA
 
P

Piet van Oostrum

Antoon Pardon said:
Why? What is so important about this particular way, that you are
willing to spend/waste so much time on it? You act like someone
who want to get from Brussels to London and when asked how to
do that gets advise on how to take the boat or plane at which
point you react that you want to get to Londen without boat
or plane but just by bicycle. And in further exchange make it
clear that using a bike is more important than arriving in London.

And then the easiests would be to put your bicycle in the train.
 
G

Gene Heskett

Unfortunately that proves nothing. My boss used to have another
employee besides me - he lasted for several years before he finally
quit (wasn't fired). In retrospect, my boss wishes he'd fired him a
lot sooner, but hindsight is 20/20, they say. We've since ripped out
every line of code this guy wrote and rewritten from scratch. No,
merely holding down a job doesn't prove anything more than that your
boss hasn't gone through and evaluated your code. In my example, it
was because the boss was too busy (he knew stuff was taking a long
time to get written and debugged, he didn't know it was because the
code was trash); in other cases, I have no doubt, it's because the
boss has no clue what makes good code. That's why he hired a
programmer, after all - to do what he can't do himself. It's
unfortunately not difficult for someone to be employed to do something
he's utterly incompetent to do.

ChrisA

+1000 or more Chris. That should be printed, and dye transfered to the
paint on every coders cubicle wall, with a wall sconce above it for
illumination.

I have a similar story but it occurred in the broadcast engineering arena,
back in the middle of the last decade. I had been to this facility with
orders to see if I could clean up the technical mess once before. A year
later I was back out there, and found one of my fixes undone, with
disastrous results on the video quality. So I fixed it again, then, when
the person nominally in charge of those things wandered in a couple of
hours later I took him to an out of the traffic and tried to educate him.
Mind you, he's the one with the degree. The more I talked the more upset I
got and I even questioned his family tree. I figured I was in for a good
scrap the way I laid into him, but when I finally ran down, he floored me
by saying that "no one had ever explained cause and effect to him that
clearly, and why the hell wasn't I teaching someplace?, as I was better by
far than any prof he ever had in school."

He did I think, finally understand that he was in over his head a wee bit
trying to keep 4 television stations and a cable channel on the air. So he
left for a radio station in NC I was told, because I got sent back a third
time to keep it running while the commission was cogitating on the license
transfers to another media group.

Now of course I'm retired, we've since converted to digital broadcasting,
and much of my knowledge in analog studio stuff is largely moot. Time
marches on. And it gives me time to lurk here, hoping I'll learn a bit of
python by osmosis. Please, do carry on. The comments, often pithy but
just as often over my now ancient head, are certainly worth the admission.

Cheers, Gene
--
"There are four boxes to be used in defense of liberty:
soap, ballot, jury, and ammo. Please use in that order."
-Ed Howdershelt (Author)

There are no great men, only great challenges that ordinary men are forced
by circumstances to meet.
-- Admiral William Halsey
A pen in the hand of this president is far more
dangerous than 200 million guns in the hands of
law-abiding citizens.
 
M

MRAB

And then the easiests would be to put your bicycle in the train.
But what if you don't want to use the train, but cycle all the way?
There _must_ be a way of cycling through the tunnel...
 
D

Denis McMahon

Στις 29/9/2013 12:50 μμ, ο/η Dave Angel έγÏαψε:
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:
gi,city,host=globals().get("gi", "who knows"), globals().get ("city",
"Άγνωστη Πόλη"), globals().get("host", "Άγνωστη ΠÏοέλευση")

Hello Dave,

By looking at your code i think that you are tellign the progrma to try
to gri don't know what the function globals() is supposed to do

but i was thinking more of:

ipval = ( os.environ.get('HTTP_CF_CONNECTING_IP') or
os.environ.get('REMOTE_ADDR', "Cannot Resolve") )
try:
city = gi.time_zone_by_addr( ipval )
host = socket.gethostbyaddr( ipval ) [0]
except socket.gaierror as e:
# We need something here to identify which one of the 2 above variables
or even both of them went wrong, and then assign the appropriate value
to each one of them but i don't know how to write it.

Is there a function that can tell us which variable failed to be
assigned a value that we can use in order to decide to which variable we
will

Yes, set the default values first, and overwrite them with the successful
values when the values are successfully calculated.

This is a very common method used in many programming languages.
 
D

Denis McMahon

Στις 29/9/2013 2:27 μμ, ο/η Dave Angel έγÏαψε:
Dave's way though seems better.
Assign the vars default string and if they get re-assinged correctly
that would be ideal, otherwise we have already given them the
defaults.

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 Exception as e:
print( "metrites.py => (%s): " % lastvisit, repr( sys.exc_info() ),
file=open('/tmp/err.out', 'w') )

I'll think i'll stick to this solution.
But you've put gi back in to the try-block. If it really belongs
there,
then you'd better give it a default value as well. On the other hand,
if it can't get an exception, you should move it out.

You are right i just put it there because its being relevant to the
whole geoip things. Givign it a default value will not really help much
because i'am not printing it later on it just is necessay to poitn to an
existing geopip file in plcace.

If it fails to be assinged then i will just cat /etc/err/out and see
that it erred out and then take action to fix it.

Nick, you have now spent 4 days arguing over a minor coding problem that
you were given solutions to on the first day, primarily because you feel
that the solutions you are being offend some programming aesthetic you
have.

I suggest that it's time for you to re-evaluate what you want from this
ng, and indeed what language you want to code in if your perl "minimal
code possible" aesthetic is so important to you.

If you want good python code, then stop telling everyone here that their
working solutions are wrong and should be more like your dysfunctional
code, and use the solutions you are given.

If you want to write minimalist perl code, then stop using python and use
perl.

In either case, you need to stop arguing with people who are offering you
solutions to your problems solely based on the fact that you don't like
their coding styles.

You are the one who comes here asking for solutions. Either accept the
solutions you are offered, or stop asking for them.
 
G

giacomo boffi

Joel Goldstick said:
IF it can also be written in one-line

def f(x,n,w):return(lambda y=f(x[::2],n/2,w[::2]),z=f(x[1::2],n/2,w
[::2]):reduce(lambda x,y:x+y,zip(*[(y[k]+w[k]*z[k],y[k]-w[k]*z[k]) for k in
range(n/2)])))()if n>1 else x

I've been reading along and learning some really obscure coding
patterns.

well, the obscure patterns aren't mine, they were contributed by some
it.comp.python regulars, to which credit is due if credit is due
(please ask google groups for the individual contributions)

to show a recreational one liner from which Íßêïò could learn
something, one way or another
 

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

Forum statistics

Threads
473,776
Messages
2,569,602
Members
45,185
Latest member
GluceaReviews

Latest Threads

Top