'TypeError: object of type 'NoneType' has no len() -- Even with Try Except

I am attempting to pull data from an api into an empty list and convert it to a dataframe. I have used a try and except for cases where the api would return a null value as well, but still keep getting this error. This is my code: (I have written a function called get_data to pull in my required datapoints from the API:

d = []

base_url = "api url inserted here"
for i in range(len(df)):
    try: 
        address = base_url + df.loc[i,"column_for_api_call"] 
        d.append(get_data(address))
    except (IndexError, TypeError) as error: 
        print('ERROR at index {}: {!r}'.format(i, address))
        d.append(["  "])
lat = pd.DataFrame(d)

But keep getting the error TypeError: object of type 'NoneType' has no len() after the entire code runs. What am I missing?



Solution 1:[1]

df is None so your for-loop never gets entered. You should specify what should happen in that case:

if df is None:
    pass  # FIXME: what should happen here?
else:
    for i in range(len(df):
        address = base_url + df.loc[i,"column_for_api_call"] 
        d.append(get_data(address))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jasmijn