Passing a function (with arguments) as an argument in Python

﹥>﹥吖頭↗ 提交于 2021-01-29 05:41:32

问题


I am measuring performance of different sorting methods using Python built-in library timeit. I would like to pass a function and an integer as arguments to the statement being tested in timeit(). I tried the following:

def sort_1(l):
    ...
    return l_sorted

def test(f: Callable, l_len: int):
    l = np.random.rand(low=-1000, high=1000, size=l_len)
    f(l)


timeit.timeit(stmt=test(sort_1, l_len=10), number=1000)

... with a ValueError saying that stmt is neither a string nor callable. The error doesn't occur when I call it like this:

timeit.timeit(stmt=test, number=1000)

... but then I cannot pass any argument to test(). What is a general solution if someone wants to pass arguments to a function given as an argument? (let's say, when a method is already implemented and there is not way to pass arguments in a separate argument)

Cheers

Edit:

@jonrsharpe, thanks! The solution looks like this:

timeit.timeit(stmt='test(f=sort_1, l_len=10)', number=100, globals=globals())

来源:https://stackoverflow.com/questions/61039221/passing-a-function-with-arguments-as-an-argument-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!