Reputation: 2334
What's the best way to define a function that depends on mutually excluding arguments, i.e. set of arguments where I only need to specify one at a time. A simple example would be a function that takes a physical parameter as the input, say the frequency. Now I want the user to be able to specify the frequency directly or the wavelength instead, so that they could equally call
func(freq=10)
func(wavelen=1).
One option would be kwargs, but is there a better way (regarding docstrings for example)?
Upvotes: 0
Views: 204
Reputation: 897
Assuming all possible argument names are known, how about using a default of None?
def func(freq=None, wavelen=None):
if freq:
print(freq)
elif wavelen:
print(wavelen)
Using elif you can prioritize which argument is more important and considered first. You can also write code to return error if more than one argument is given, using xor:
def func(freq=None, wavelen=None):
if not(freq ^ wavelen):
raise Exception("More than one argument was passed")
if freq:
print(freq)
elif wavelen:
print(wavelen)
Upvotes: 1
Reputation: 42133
Since the calculations are going to be different, why not make that part of the function name and have two distinct functions (rather than a bunch of ifs):
def funcWavelen(w):
...
def funcFreq(f):
...
Upvotes: 0