0

In the following script, a TypeError is occuring on my try block which doesn't allow the ValueError from the API to happen. How can I skip the execution of the line self.address, (self.lat, self.lng) = g.geocode(place) so as to only catch errors from Google's API and not errors that occur in my code because of it?

from geopy import geocoders

class GeoCode():
    def __init__(self, place):
        try:
            g = geocoders.GoogleV3()
            self.address, (self.lat, self.lng) = g.geocode(place)
        except ValueError as e:
            print "Failed for address %s with message:\n %s" % (place,e) 
            continue

While testing for wrong values

>>> b = GeoCode('nosuchplacecanexist')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "geocode.py", line 7, in __init__
    self.address, (self.lat, self.lng) = g.geocode(place)
TypeError: 'NoneType' object is not iterable

Changing it to:

from geopy import geocoders

class GeoCode():
    def __init__(self, place = "Yashwant Place, Chanakyapuri, New Delhi"):
        try:
            g = geocoders.GoogleV3()
            addr = g.geocode(place)
            if addr is not None:
                self.address, (self.lat, self.lng) = addr 

        except ValueError as e:
            print "Failed for address %s with message:\n %s" % (place,e) 
yayu
  • 7,758
  • 17
  • 54
  • 86
  • 1
    Hint: `a, b, c = None` gives `TypeError: 'NoneType' object is not iterable`. – nvlass Jan 25 '14 at 07:03
  • @nvlass I have a hackish solution that bypasses it by wrapping the offending statement in an if block. But it is still not catching the ValueError. – yayu Jan 25 '14 at 07:17
  • @yayu: what `ValueError` are you referring to? – DSM Jan 25 '14 at 07:18
  • 1
    @yayu well, the [docs](http://geopy.readthedocs.org/en/latest/#module-geopy.geocoders) mention that `when there are no results found [geocode / reverse] returns None`, so you'll have to check for `None` as well. – nvlass Jan 25 '14 at 07:19

0 Answers0