I have a simple set of functions that use each other. For example:
def func(x)
y = func_1(x)
z = func_2(y)
return z
def func_1(x):
return x + 1
def func_2(x)
a = func_a(x)
b = func_b(y)
return b
As you can see, the func
is the "root" function that uses func_1
and func_2
and func_2
, in its turn, uses func_a
and func_b
. When I call func
I get z
as the result.
Now I would like to "modify" or "extend" my functions with a decorator such that in the end (as a result of func
) I get not only z
but also an object that shows me how much it took to execute this function as well as what functions have been used by the function and how long it took to execute these "sub-functions" as well as what "sub-sub-functions" have been used by what "sub-functions" and how long does it took to execute them. To make it simpler I give an example of what I expect as an "additional" result:
{
'fname' : 'func',
'etime' : 12.000,
'subs' : [
{
'fname' : 'func_1',
'etime' : 2.000,
'subs' : []
},
{
'fname' : 'func_2',
'etime' : 10,
'subs' : [
{
'fname' : 'func_a',
'etime' : 6,
'subs' : []
},
{
'fname' : 'func_b',
'etime' : 4
'subs' : []
}
]
}
]
}
In the above example "fname" means name of the function, "etime" means execution time (how long did it took to execute this function), and "subs" is a list of sub-function that were used by the considered function. For each sub-function we have the same keys ("fname", "etime", "subs"). So, it is a "recursive" structure. If a function did not use any function then "subs" maps to an empty list.
I have started with the following decorator:
def decorate(func):
def wrapper(*args, **kw):
d = {}
d['fname'] = func.__name__
t0 = time.time()
out = func(*args, **kw)
d['etime'] = time.time() - t0
d['subs'] = ?
?.append(d)
return wrapper
But then I stack with the further implementation. I cannot find a solution and am not even sure that it is possible.
The idea is that I use a decorator to extend the number of arguments passed to each function. Each function gets an empty list containing all sub-functions used so far and append itself to this list.