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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
@RickyRobinson: It's OK to specify no arguments when using **kwargs. You'll just get an empty dictionary, and everything will work as expected.
Note that in **kwargs (and *args), the names are just conventions. The important bit are the * and the **

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.