简体   繁体   English

如何在 Python 中将可变数量的函数作为参数传递

[英]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.我想使用方法assesion.run() ,它需要指向异步函数的指针。 Number of functions differs, so I tried to make a list of functions and spread it in .run() arguments section.函数的数量不同,所以我尝试制作一个函数列表并将其分布在.run()参数部分。 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. run 函数调用参数来创建协程,然后创建任务。

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:这些函数是不带参数调用的,所以你应该使用 functools.partial 来放入参数:

from functools import partial


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


 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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