Handling 3 operands in an expression without raising an exception

Dave Angel davea at davea.name
Sun Sep 29 05:50:08 EDT 2013


On 29/9/2013 03:35, Νίκος wrote:

>
> 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") )
gi = city=host=None
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=gi if gi is not None else "who knows", city if city is not
None else"Άγνωστη Πόλη", host if host is not None else "Άγνωστη
Προέλευση"

That's one line.  And if you now want to eliminate the gi=city=host=None
line, let me attempt that.  But this probably will have some serious
typo in it, as I'm not testing any of these.  And it assumes that the
code is at top-level, and that none of these variables already exists.

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

Or perhaps even, assuming this is the main script, and not a loaded
module:

import __main__ as qq
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=getattr(qq,"gi", "who knows"), getattr(qq,"city","Άγνωστη
Πόλη"),getattr(qq, "host", "Άγνωστη
Προέλευση")



-- 
DaveA





More information about the Python-list mailing list