Elif和别的区别?

时间:2018-10-13 20:00:15

标签: python performance if-statement control-flow

我在Python中具有以下功能:

def _extract_grp_entitlements(self,saml_authentication_attributes,groups):
    result = []
    input_length = len(saml_authentication_attributes[groups])
    if input_length == 0:
        log.error(self.empty_entitlements_message)
        raise RuntimeError(self.empty_entitlements_message)
    if input_length == 1:
        result = [t.strip() for t in saml_authentication_attributes[groups][0].split(',')]
    elif input_length:
        result = saml_authentication_attributes[groups]
    return result

除了使用逻辑elif子句来代替else之外,还有速度/内存等方面的好处/缺点(除了逻辑控制流之外)?

这会更好吗?

    def _extract_grp_entitlements(self,saml_authentication_attributes,groups):

        input_length = len(saml_authentication_attributes[groups])

        if input_length == 0:
            log.error(self.empty_entitlements_message)
            raise RuntimeError(self.empty_entitlements_message)


        return [t.strip() for t in saml_authentication_attributes[groups][0].split(',')] \
            if len(saml_authentication_attributes[groups]) == 1\
            else saml_authentication_attributes[groups]

3 个答案:

答案 0 :(得分:3)

else会更清楚。您的elif将始终运行,因此没有任何条件限制。

答案 1 :(得分:0)

您的第一个功能已经足够可读,因此性能不太可能成为问题。为了在短函数中获得最大的可读性,我会这样写:

def _extract_grp_entitlements(self,saml_authentication_attributes,groups):
    inp = saml_authentication_attributes[groups]
    if inp:    
        if len(inp) == 1:
            return [t.strip() for t in inp[0].split(',')]
        else:
            return inp
    else:
        log.error(self.empty_entitlements_message)
        raise RuntimeError(self.empty_entitlements_message)

在我看来,这使流程一目了然。 else都是不必要的(因为如果条件为真,该函数将已经return被修改),并且仅用于使其更加明确。 Some倾向于在else之后省略return

对于更长的函数,将所有主要逻辑都这样嵌套可能会很痛苦,并且不再清楚结尾处的末尾else是什么情况,因此处理起来更加方便顶部参数的基本问题。

def _extract_grp_entitlements(self,saml_authentication_attributes,groups):
    inp = saml_authentication_attributes[groups]

    # get the no input error out of the way
    if not inp:
        log.error(self.empty_entitlements_message)
        raise RuntimeError(self.empty_entitlements_message)

    # now do everything else (no need for else)
    if len(inp) == 1:
    # etc.

答案 2 :(得分:-1)

我设法缩短了该函数的第二个版本,使其既可读又简洁:

def _extract_grp_entitlements(self,groups):

    groups_length = len(groups)

    if groups_length == 0:
        log.error(self.empty_entitlements_message)
        raise RuntimeError(self.empty_entitlements_message)

    return [t.strip() for t in groups[0].split(',')] \
        if groups_length == 1\
        else groups
相关问题