Search code examples
pythonasynchronouspython-requests-html

Python AsyncHTMLSession with lambda function with variable not work


Code below get 4,4,4,4,4

expected 0,1,2,3,4

It works with functools.partial but not lambda, how to fix it?

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()

Solution

  • You need to pass index to your lambda like this: 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)
    

    For more information, it is documented here !