简体   繁体   中英

How to pass variable number of functions as arguments in Python

I'd like to use method assesion.run() , which expects pointers to async functions. Number of functions differs, so I tried to make a list of functions and spread it in .run() arguments section. But when appending them to list, they immediately invoke. How to generate variable number of functions please?

from requests_html import AsyncHTMLSession
asession = AsyncHTMLSession()

urls = [
    'https://python.org/',
    'https://reddit.com/',
    'https://google.com/'
    ]

async def get_html(url):
    r = await asession.get(url)
    return r

functionList = []

for url in urls:
    functionList.append(get_html(url))

# results = asession.run(fn1, fn2, fn3, fn4, ...)
results = asession.run(*functionList)

for result in results:
    print(result.html.url)

You have to pass the async functions not the coruoutines. The run function calls the arguments to create the coruoutines and then create the tasks.

So when you pass the coroutines run invoke them instead of creating tasks.

The functions are called without argument, so you should use functools.partial to put in the argument:

from functools import partial


...
for url in urls:
    functionList.append(partial(get_html, url))


 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM