Python: pass function as parameter, with options to be set

孤人 提交于 2021-02-09 08:01:28

问题


In Python, I need to call many very similar functions on the same input arguments sampleA and sampleB . The only thing is that some of these functions require an option to be set, and some don't. For example:

import scipy.stats
scipy.stats.mannwhitneyu(sampleA, sampleB)
[...some actions...]
scipy.stats.mstats.ks_twosamp(sampleA, sampleB, alternative='greater')
[...same actions as above...]
scipy.stats.mstats.mannwhitneyu(sampleA, sampleB, use_continuity=True)
[...same actions as above...]

Therefore I would like to pass the names of such functions as input argument of a more generic function computeStats, as well as sampleA and sampleB, but I don't know how to handle options that I sometimes have to use.

def computeStats(functionName, sampleA, sampleB, options???):
   functionName(sampleA, sampleB)  #and options set when necessary
   ...some actions...
   return testStatistic

How do I specify an option that sometimes has to be set, sometimes not?


回答1:


Use **kwargs:

def computeStats(func, sampleA, sampleB, **kwargs):
   func(sampleA, sampleB, **kwargs)
   ...some actions...
   return testStatistic

Then you'll be able to use computeStats() like so:

computeStats(scipy.stats.mstats.ks_twosamp, sampleA, sampleB, alternative='greater')

That said, I am not entirely convinced you need this at all. How about simply

def postprocessStats(testStatistic):
   ...some actions...
   return testStatistic

postprocessStats(scipy.stats.mstats.ks_twosamp(sampleA, sampleB, alternative='greater'))

?

I think this is easier to read and at the same time is more general.



来源:https://stackoverflow.com/questions/15654390/python-pass-function-as-parameter-with-options-to-be-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!