0

I have a wrapper to time the execution of certain functions in a list. Most of these functions have one and the same parameter: era. I run the functions like displayed below. However, some functions require an extra parameter, e.g. the function dummy_function(). I've been looking for a way to be able to add this parameter in a Pythonic way. I found some solutions but they are very ugly and not quite scalable. Any help or suggestions would be tremendously appreciated!

def dummy_function(self, period, letter='A'):
    """ Debugging purposes only """
    print(f'This function prints the letter {letter}.')
    from time import sleep
    sleep(3)

def timed_execution(callbacks, era):
    for callback in callbacks:
        start_time = time.time()
        callback(era)
        end_time = time.time()
        print(f'{callback.__name__} took {end_time-start_time:.3f}s')

    
def calculate_insights(era):
    timed_execution([
        dummy_function,
        another_function,
        yet_another_function,
    ], era)

calculate_insights(era)

Knoerifast
  • 27
  • 6

1 Answers1

0

Perhaps the best way is to actually pass the arguments for their respective function or just try to use a wrapper to calculate the time of a function.

Code taken from another question

from functools import wraps
from time import time

def timing(f):
    @wraps(f)
    def wrap(*args, **kw):
        ts = time()
        result = f(*args, **kw)
        te = time()
        print 'func:%r args:[%r, %r] took: %2.4f sec' % \
          (f.__name__, args, kw, te-ts)
        return result
    return wrap

Then you can do something along the lines of

@timming
def dummy_function(self, period, letter='A'):
    """ Debugging purposes only """
    print(f'This function prints the letter {letter}.')
    from time import sleep
    sleep(3)

    
def calculate_insights():
    dummy_function(era)

or you could just a dict with all the parameters passed into each callback but that doesn't sounds to pythonic for me.

Gabe
  • 50
  • 6