Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get function passed as an argument name inside another function

I am trying to measure elapse time for different functions with simple method like this:

def taketime(executable,exname='method'):
    tic = time.time()
    exname = executable.__name__
    out = executable
    toc = time.time()
    print('Time taken for ',exname,' ',toc-tic,' sec')
    return out

Executable is another method, can be whatever. Nevertheless, the program does not work as the line exname = executable.__name__ is actually already running executable and trying to get the property name from the output.

What is the correct way to get the name of the executable passed to another function?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Small test program (not working):

import time
def taketime(executable,exname=None):
    tic = time.time()
    if exname is None: exname = executable.__name__
    out = executable
    toc = time.time()
    print('Time taken for ',exname,' ',toc-tic,' sec')
    return out
# -----------------------------------------
def hello():
    print('Hello!')
    return
dd = taketime(hello())

Of course it works when I do this:
dd = taketime(hello(),'hello')

>Solution :

You are calling the target function before it is passed into your taketime() function. Also, you don’t call anything inside your function either. You meant to write your code like this:

import time
def taketime(executable, *args, **kwargs):
    exname = executable.__name__
    tic = time.time()
    out = executable(*args, **kwargs)
    toc = time.time()
    print('Time taken for ',exname,' ',toc-tic,' sec')
    return out
# -----------------------------------------
def hello():
    print('Hello!')
    return
dd = taketime(hello)

Note that:

  1. the call to taketime is like this: taketime(hello)
  2. the target function is actually called like this: out = executable()
  3. supply extra arguments like this: taketime(hello, arg1, arg2)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading