Python:当父函数中存在变量时,嵌套函数中未定义的变量



Edit:我意识到这不是一个嵌套函数,而是在函数中调用一个函数!

我从5个不同的端点(endpoint_a到endpoint_e(提取数据,每个端点都有自己的函数get_endpoint_,如下所示:

def get_endpoint_a() -> pd.dataFrame:
"""
Return data from API endpoint.
Includes all data. It is initially returned as a JSON and
then transformed into a DataFrame.
"""
url = configs.ENDPOINT_A
querystring = configs.a_querystring
try:
response = requests.request("GET", url, headers=header, params=querystring)
except requests.exceptions.RequestException as e:
raise sys.exit(e)
if response.status_code != 200:
raise Exception(f"Response from API: {response.status_code}")
response = response.json()
return _get_all_data(response)

我有一个子函数_get_all_data来附加结果,以及下面定义的用于分页的whilr循环:

def _get_all_data(response):
"""
Return the results of the get request.
Loops over api response and appends results to list in addition to appending the
results of a while loop for pagination.
"""
results = []
for x in response["results"]:
results.append(x)
while response["paging"]["next"]["link"] is not None:
url = response["paging"]["next"]["link"]
response = requests.request("GET", url, headers=header, params=querystring)
response = response.json()
for x in response["results"]:
results.append(x)
return json_normalize(results)

当我在Jupyter中运行函数时,它是有效的,但是当我通过linter运行代码时,我会收到一条undefined variable "querystring"错误消息,引用子函数中的params=querystring。假设每个端点都需要不同的查询字符串,我无法全局定义它,并且使用nonlocal会返回unable to parsenonlocal variable must be bound in outer function scope

有人能帮我,或者给我指一个正确的方向吗?提前感谢

正如注释中所指出的,这不是一个嵌套函数。然而,要解决您的问题,您只需要将querystring作为参数添加到函数中,并每次传递它:

def _get_all_data(response, querystring):
"""
Return the results of the get request.
Loops over api response and appends results to list in addition to appending the
results of a while loop for pagination.
"""
results = []
for x in response["results"]:
results.append(x)
while response["paging"]["next"]["link"] is not None:
url = response["paging"]["next"]["link"]
response = requests.request("GET", url, headers=header, params=querystring)
response = response.json()
for x in response["results"]:
results.append(x)
return json_normalize(results)

def get_endpoint_a() -> pd.dataFrame:
"""
Return data from API endpoint.
Includes all data. It is initially returned as a JSON and
then transformed into a DataFrame.
"""
url = configs.ENDPOINT_A
querystring = configs.a_querystring
try:
response = requests.request("GET", url, headers=header, params=querystring)
except requests.exceptions.RequestException as e:
raise sys.exit(e)
if response.status_code != 200:
raise Exception(f"Response from API: {response.status_code}")
response = response.json()
return _get_all_data(response, querystring)

最新更新