pythonpython-3.xfunctionparameter-passing

Best way to ensure user to specify one and only one of the two function parameters in Python


In some_function, I have two parameters freq and frac, I don't want users to specify both of them, or none of them. I want them to specify just one of them.

Here is the working code:

def some_function(freq=False, frac=False):
    if (freq is False) & (frac is False):
        return (str(ValueError)+': Both freq and frac are not specified')
    elif (freq is not False) & (frac is not False):
        return (str(ValueError)+': Both freq and frac are specified')
    elif (freq is not False) & (frac is False):
        try:
            print ('Do something')
        except Exception as e:
            print (e)
    elif (freq is False) & (frac is not False):
        try: 
            print ('Do something else')
        except Exception as e:
            print (e)
    else: return (str(ValueError)+': Undetermined error')

Are there better and less verbose practices to express this in Python?


Solution

  • You can use assert before your if statement. The type of your inputs is unclear; in general, I would use None if I know this isn't a valid input.

    def some_function(freq=None, frac=None):
    
        freq_flag = freq is not None
        frac_flag = frac is not None
    
        assert freq_flag + frac_flag == 1, "Specify exactly one of freq or frac"
    
        if freq_flag:
            print('Do something')
    
        elif frac_flag:
            print('Do something else')