【问题标题】:MyPy Missing return statementMyPy 缺少返回语句
【发布时间】:2021-11-11 15:05:55
【问题描述】:

我遇到了 mypy 抛出错误说我缺少返回语句的问题。虽然我在函数中有一个,但它仍然存在。我做错了吗?

(我用的是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()

【问题讨论】:

  • 捕获异常后不会返回任何内容。

标签: python python-3.x type-hinting mypy python-typing


【解决方案1】:

你已经像这样注释了你的函数签名:

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

您的注释声明您的函数接受单个参数misc_menu_input,一个字符串,并返回一个字符串。但是,这不是您的函数的作用。

如果try 子句中没有ValueError,您的函数将遵循您给它的注释,并返回一个字符串。但是,如果try 子句中有ValueError,则跳过try 子句的其余部分,并执行except 子句。在except 子句中没有return 语句,这意味着如果有一个ValueError 导致except 子句被执行,你的函数将返回None,这与你给它的注释相矛盾。

【讨论】:

    猜你喜欢
    • 2013-11-30
    • 2017-01-26
    • 2017-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2021-07-11
    • 2017-05-15
    相关资源
    最近更新 更多