多个出口是否可以用来压缩长Python函数?

fbm*_*bmd 4 python coding-style

我有一个该结构的长Python函数:

def the_function(lots, of, arguments):

    return_value = None

    if some_important_condition:

        # a lot of stuff here

        return_value = "some value"

    else:

        # even more stuff here

        return_value = "some other value"

    return return_value
Run Code Online (Sandbox Code Playgroud)

一个问题是ifelse块和块都包含多个屏幕代码.很容易忘记压痕,或者不得不向上滚动以查看我们目前处于什么状态.

改进这一点的一个想法是将其分成几个函数:

def case_true(lots, of, arguments):

    # a lot of stuff here

    return "some value"

def case_false(lots, of, arguments):

    # even more stuff here

    return "some other value"

def the_function(lots, of, arguments):

    return_value = None

    if some_important_condition:

        return_value = case_true(lots, of, arguments)

    else:

        return_value = case_false(lots, of, arguments)

    return return_value
Run Code Online (Sandbox Code Playgroud)

但考虑到争论的争论,我不确定这是否可以解决问题.

另一个想法是使用多个退出点:

def the_function(lots, of, arguments):

    if some_important_condition:

        # a lot of stuff here

        return "some value"

    # even more stuff here

    return "some other value"
Run Code Online (Sandbox Code Playgroud)

但是有几种编码风格可以针对多个退出点提出建议,特别是当它们分开时.

问题是:什么是一种首选的pythonic方法,使原始结构更易于阅读和维护?

Ósc*_*pez 5

在一个函数中有几个退出点是完全没问题的,只需要一个退出点是一个旧的约定,可以追溯到编程语言没有异常处理的日子,并且有一个单一的退出点是有意义的.集中错误处理.异常的存在使旧的惯例过时了.

在某些情况下,即使强制使用单一功能退出点策略,也可以使用多个退出点- 例如,函数顶部的保护子句需要从函数快速返回"如果参数不正确,或者在任何有意义的工作完成之前,大部分功能显然是不合适的",在这种情况下很有意义"在顶部拯救.否则,你将需要大量的if语句来覆盖大部分功能,给出你还有另一个级别的缩进".

为了完整起见,这里有一个扩展我的观点的解释.