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

Discussão em 'Python' iniciado por Stack, Novembro 1, 2024.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página