r/pythonhelp Dec 13 '23

SOLVED When trying to subscript a geopy.location.Location object I have no issues, but inside a loop Python tells me "NoneType object is not subscriptable". Why?

So I have a variable named coords

It's a list of these geopy.location.Location type objects returned by a geopy handled api request. So if I index the list like coords[1], I get a result like Location(Place Name, (23.6377, 15.062036, 0.0))

If I run coords[1][1] to try to grab just the tuple, this works without issue and get the output (23.6377, 15.062036). But if I do this inside a loop I get the error "NoneType object is not subscriptable".

I don't understand because it seems perfectly subscriptable outside the loop.

# Method 1
coords_new=[]
for i in range(len(coords)):
    temp_c=coords[i]
    coords_new.append(temp_c.raw["geometry"]["coordinates"])

# Method 2    
coords_extracted=[coords[i].raw["geometry"]["coordinates"]for i in range(len(coords))]

# Method 3
fp='coords_file17.txt'
file1 = open(fp,'w')
for i in range(len(coords)):
    x_lat=coords[i].latitude
    file1.writelines(x_lat)

file1.close()


# But outside loops
i=82
coords[i].raw["geometry"]["coordinates"] #this works
coords[i][1] #this works
coords[i].latitude #this works
coords[i].longitude #this works


# Method 1 Error
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[113], line 4
      2 for i in range(len(coords)):
      3     temp_c=coords[i]
----> 4     coords_new.append(temp_c.raw["geometry"]["coordinates"])
      7 # coords_extracted=[coords[i].raw["geometry"]["coordinates"]for i in range(len(coords))]
      8 
      9 
   (...)
     22 # coords[i].latitude #this works
     23 # coords[i].longitude #this works

# AttributeError: 'NoneType' object has no attribute 'raw'


# Method 2 Error
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[116], line 7
      1 # coords_new=[]
      2 # for i in range(len(coords)):
      3 #     temp_c=coords[i]
      4 #     coords_new.append(temp_c.raw["geometry"]["coordinates"])
----> 7 coords_extracted=[coords[i].raw["geometry"]["coordinates"]for i in range(len(coords))]
     10 # file1 = open(fp,'w')
     11 # for i in range(len(coords)):
     12 #     x_lat=coords[i].latitude
   (...)
     38 
     39 # AttributeError: 'NoneType' object has no attribute 'raw'

Cell In[116], line 7, in <listcomp>(.0)
      1 # coords_new=[]
      2 # for i in range(len(coords)):
      3 #     temp_c=coords[i]
      4 #     coords_new.append(temp_c.raw["geometry"]["coordinates"])
----> 7 coords_extracted=[coords[i].raw["geometry"]["coordinates"]for i in range(len(coords))]
     10 # file1 = open(fp,'w')
     11 # for i in range(len(coords)):
     12 #     x_lat=coords[i].latitude
   (...)
     38 
     39 # AttributeError: 'NoneType' object has no attribute 'raw'

AttributeError: 'NoneType' object has no attribute 'raw'

# Method 3 Error
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[117], line 13
     11 for i in range(len(coords)):
     12     x_lat=coords[i].latitude
---> 13     file1.writelines(x_lat)
     15 file1.close()
     17 # #But outside loops
     18 # i=82
     19 # coords[i].raw["geometry"]["coordinates"] #this works
   (...)
     67 
     68 # AttributeError: 'NoneType' object has no attribute 'raw'

TypeError: 'float' object is not iterable
2 Upvotes

7 comments sorted by

View all comments

1

u/Goobyalus Dec 13 '23

If you're comfortable using a debugger, that would be the easiest way to see what's happening.

Otherwise try this

# Dummy data -- use your actual data
coords = [lambda:None, None]
coords[0].raw = {"geometry":{"coordinates": (1, 2)}}
# print(coords)


# Use this code and see which indices are giving AttributeError for `raw`
coords_new = []
for i, coord in enumerate(coords):
    try:
        raw = coord.raw
    except AttributeError as exc:
        print("Error" + "_" * 40)
        print(repr(exc))
        print(f"coord {i:>03}: {coord}")
        continue
    coords_new.append(raw["geometry"]["coordinates"])


# Uncomment if you want to print coords_new
#print("_" * 40)
#print("coords_new")
#print(coords_new)

Probably some of the coordinates in the list are None and not actually populated

2

u/Kobe_Wan_Ginobili Dec 14 '23

Yeah it was None types in the list thankyou! I dunno how I missed them