【问题标题】:Python AsyncHTMLSession with lambda function with variable not work带有变量的 lambda 函数的 Python AsyncHTMLSession 不起作用
【发布时间】:2021-06-10 00:44:27
【问题描述】:
下面的代码获取4,4,4,4,4
预计0,1,2,3,4
它适用于 functools.partial 但不适用于 lambda,如何修复它?
from requests_html import AsyncHTMLSession
asession = AsyncHTMLSession()
async def download(index):
print(index)
def main():
lst = []
for index in range(5):
lst.append(lambda: download(index))
asession.run(*lst)
if __name__ == "__main__":
main()
【问题讨论】:
标签:
python
asynchronous
python-requests-html
【解决方案1】:
您需要像这样将索引传递给您的 lambda:lambda index=index: download(index)
def main():
lst = []
for index in range(5):
lst.append(lambda: download(index))
# Here when you run your lambda the index variable is in
# the main function scope, so the value is 4 for all the lambda
# because the loop is ended.
asession.run(*lst)
def main():
lst = []
for index in range(5):
lst.append(lambda foo=index: download(foo))
# Here a new variable foo is created in the scope of the lambda
# with the value of index for each iteration of the loop
asession.run(*lst)
更多信息,记录在here!