-1

I made the timer function for measuring performance of functions

but I got a problem when I use **kwargs for function's parameter

for example when I want to use scipy.stats.zscore(a, axis=0, ddof=0, nan_policy='propagate') only using 3 parameters.

generally I will use like a below code

import scipy.stats as st

temp = np.array([[3,4,2],[2,2,4]])

st.zscore(a=temp, axis=1, nan_policy='omit')

but when I measure performance of scipy.stats.zscore(a, axis=0, ddof=0, nan_policy='propagate') by my function timer, it makes error....

this is my code

import numpy as np
import scipy.stats as st
from time import perf_counter

def timer(f,*args,**kwargs):
    start = perf_counter()
    if args:
        f(*args)
    elif kwargs!=None: 
        f(**kwargs)
    return 1000 * (perf_counter() - start)

temp = np.array([[3,4,2],[2,2,4]])

# it has error...
# I know para =["a"=1] is wrong code... 
para = ["a" = temp, "axis" = 1, "nan_policy" = "omit"]
used_time = 1000 * np.mean([timer(st.zscore, *para) for _ in range(1000)])

# but *args works very well... 
used_time = 1000 * np.mean([timer(st.zscore, temp) for _ in range(1000)])

so my object is

I want to use **kwargs for timer's callback function's parameter

plz help me..

박지현
  • 1
  • 2
  • For what it's worth, you don't need to check to make sure args, kwargs are empty, python will do it for you simply calling f(*args, **kwargs) – AJ Biffl May 19 '22 at 08:19
  • As for your current error, the issue is with the line where you define `para`: this syntax is just plainly wrong. Look into a tutorial on using args and kwargs (or [this question](https://stackoverflow.com/questions/36901/what-does-double-star-asterisk-and-star-asterisk-do-for-parameters) is the site standard) – AJ Biffl May 19 '22 at 08:23
  • @AJBiffl when use st.zscore(temp,1,'omit') it makes error because the parameter's order is not correct, st.zscore has only 4 parameter so I can use *args not **kwargs but if function had many parameter's how could you fill that all? and I know para: this is wrong but I just write down for what I want to do – 박지현 May 19 '22 at 08:29
  • Read the question I linked to, everything you need is in the answer – AJ Biffl May 19 '22 at 08:32

1 Answers1

0

Send the values directly as named parameters

timer(st.zscore, a=temp, axis=1, nan_policy="omit")

You should also change elif kwargs != None to elif kwargs, as it eon't be None if you don't send anything, it will be empty.

Guy
  • 40,130
  • 10
  • 33
  • 74