1

I am having an issue with mypy tossing an error saying I'm missing a return statement. While I have one in the function, it still proceeds to exist. Am I doing something wrong?

(I am using python3.8)

def misc_menu_choice(misc_menu_input: str) -> str:
    """Provides mapping for the misc_menu"""
    try:
        if misc_menu_input == '1':
            list_all()
        if misc_menu_input == '2':
            intermarriages()
        elif misc_menu_input == '3':
            toggle_program()
            toggle_living_only()

        elif misc_menu_input == '4':

            selection = get_user_input(main_menu())
            main_menu_selection(selection)
        elif misc_menu_input == '':

            print(f'Current ID: {current_person}\t\t\
Living Only: {program_status}')
            miscellanious_menu_prompt()

        else:

            print('Please select again')
            miscellanious_menu_prompt()
        return misc_menu_input

    except ValueError:
        print("That is not an option")
        miscellanious_menu_prompt()
Alex Waygood
  • 6,304
  • 3
  • 24
  • 46

1 Answers1

3

You've annotated your function signature like so:

def misc_menu_choice(misc_menu_input: str) -> str: ...

Your annotation states that your function accepts a single argument, misc_menu_input, a string, and returns a string. However, this is not what your function does.

If there is no ValueError inside the try clause, your function adheres to the annotation you've given it, and returns a string. However, if there is a ValueError inside the try clause, the rest of the try clause is skipped, and the except clause is executed. There is no return statement in the except clause, meaning that if there is a ValueError leading to the except clause being executed, your function will return None, contradicting the annotation you have given it.

Alex Waygood
  • 6,304
  • 3
  • 24
  • 46
  • So how should the function be annotated? Since it can return a str or a ValueError, which one would be correct for the function? @alex-waygood – Francisco Pérez Aug 12 '22 at 07:08
  • @FranciscoPérez, it doesn't "return" `ValueError`. In the event that you reach the `except ValueError` block, the function implicitly returns `None`, as there is no `return` statement in the `except ValueError` block. If this is the intended behaviour of the function, then you should put an explicit `return None` at the end of the `except ValueError` block, and change the return annotation to `Union[str, None]` to indicate that it sometimes returns `str`, and sometimes `None`. But I doubt that this is really the intended behaviour of the function. – Alex Waygood Aug 12 '22 at 11:22