Python函数在elif中返回None

时间:2018-01-07 03:22:11

标签: python recursion return

我有dict类型的变量r。变量项包含项列表,total_results是int。只要条件满足项目数小于项目总数,就会递归调用该函数。但是,如果我测试项目是否等于总结果,则return语句返回None。将此elif更改为if会返回正确的值。

有人能指出我正确的方向,找出为什么在elif或者其他块中返回r会产生无效吗?

非常感谢!!

相关代码段:

if len(items) < total_results:
    params['start_index'] = len(items)

    self.fetch_company_officers(company_number=company_number, items=items, **params)

elif len(items) == total_results:
    r['items'] = items
    return r

完整代码:

def fetch_company_officers(self, company_number, items=None, **kwargs):
    uri = 'company/{}/officers'.format(company_number)
    params = kwargs

    r = self.make_request(uri=uri, **params)

    # Test if items are set
    if items is None:
        items = r['items']
    else:
        items.extend(r['items'])

    # Iterate multiple pages
    total_results = r['total_results']

    if len(items) < total_results:
        params['start_index'] = len(items)

        self.fetch_company_officers(company_number=company_number, items=items, **params)

    elif len(items) == total_results: # TO DO: ??
        r['items'] = items
        return r

2 个答案:

答案 0 :(得分:0)

您的函数缺少处理len(items) > total_results的以下方案的逻辑。

因此该函数到达行尾并默认返回None

答案 1 :(得分:0)

我想我了解您要执行的操作,但是递归并不是解决的方法。您希望一直从下一页获取项目,只要(while)检索到的项目数小于期望的结果总数。所以..让我们使用while循环!

这是我的代码版本。请注意,由于我没有其余的代码,因此我无法进行测试。

def fetch_company_officers(self, company_number, **params):

    # Start with an empty list of items
    items = []

    # Make the first request
    uri = f"company/{company_number}/officers"
    response = self.make_request(uri=uri, **params)

    # Extract information from the first batch
    items += response.get("items", [])
    total_results = response.get("total_results")

    # Stop iterating when we don't know the total number of results to expect
    if total_results is None:
        return items

    # Keep getting more results until our list of items
    # is as long as the total number of results we expect
    while len(items) < total_results:

        # Get the next page
        response = self.make_request(uri=uri, start_index=len(items), **params)

        # Extract information from this batch
        items += response.get("items", [])

    # We've now retrieved everything
    return items