Handling 3 operands in an expression without raising an exception

Jussi Piitulainen jpiitula at ling.helsinki.fi
Sun Sep 29 08:24:59 EDT 2013


Νίκος writes:
> ΣÏις 29/9/2013 2:04 μμ, ο/η Jussi Piitulainen
> έγÏαÏε:
>
> > 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.

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



More information about the Python-list mailing list