pulsar777
pulsar777

Reputation: 23

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)

Upvotes: 0

Views: 127

Answers (1)

nadapez
nadapez

Reputation: 2727

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

Upvotes: 1

Related Questions