How to return a value from a function which was passed another function (with arguments) as an argument? I get a TypeError

Question:

Edit:
Sorry for not elaborating on this earlier. My function that I pass actually has arguments.

It looks kind of like this:

...
time_elapsed = get_running_time(runner(x:int, y:int, z:int, return_values:list))
...

I pass a list as return_values parameter (as a reference) and modify it from inside the "runner()" to retrieve values, if it makes any difference

End of Edit

I am new to Python and would be very thankful for your help.

I searched online but couldn’t find solution to this.

In short, I have a piece of code in my program that looks like this:

def get_running_time(fn: Callable):
    time_start = time.time()
    fn()
    return time.time() - time_start

I pass some_func() to get_running_time(fn: Callable) to retrieve the time it takes to run

But all I get is

...line 152, in get_running_time
    fn()
TypeError: 'NoneType' object is not callable

What should I change in order for this to work?

Asked By: Tim Korelov

||

Answers:

Based on your last comment.

def get_running_time(fn: Callable,*args,**kwargs):
    time_start = time.time()
    fn(*args, **kwargs)
    return time.time() - time_start

def fn(arg1, arg2, arg3=None):
   time.sleep(3)

arg1=10
arg2=20
get_running_time(fn, arg1, arg2)

or using partial

from functools import partial

def get_running_time(fn):
    time_start = time.time()
    fn()
    return time.time() - time_start

def fn(arg1, arg2, arg3=None):
   time.sleep(3)

arg1=10
arg2=20
p = partial(fn, arg1, arg2)
get_running_time(p)

Answered By: Jordan Hyatt

As indicated in my comment, you need to pass the function without parentheses. To support arguments, you must pass the function as a lambda function:

Code:

import time

def get_running_time(fn):
    time_start = time.time()
    fn()
    return time.time() - time_start
    
def printer(word):
    for i in range(100):
        print(word)
        
print(get_running_time(lambda: printer("Hello!")))

Output:

Hello!
...
Hello!
7.414817810058594e-05
Answered By: Ryan
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.