3

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?

Ricky Robinson
  • 21,798
  • 42
  • 129
  • 185

1 Answers1

4

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.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Ha! The last solution is cool! As for `**kwargs`, when I don't specify it I guess it's just `None` and I can pass it as an argument with no side-effects, right? – Ricky Robinson Mar 27 '13 at 08:45
  • @RickyRobinson: It's OK to specify no arguments when using `**kwargs`. You'll just get an empty dictionary, and everything will work as expected. – NPE Mar 27 '13 at 09:00
  • Note that in `**kwargs` (and `*args`), the names are just conventions. The important bit are [the * and the **](http://docs.python.org/2/tutorial/controlflow.html#arbitrary-argument-lists) – Rafael Barbosa Mar 27 '13 at 09:00