简化嵌套的Python代码

时间:2018-07-22 16:18:10

标签: python

我编写了一个小的辅助函数,用于检查导航项是否处于活动状态。该代码可以正常工作,但看起来有点嵌套。有谁知道如何简化它?

def url_name_active(view_name, name, exact=True, exclude=None):
    exclude_names = exclude.split(',') if exclude else None

    if exclude:
        for exclude_name in exclude_names:
            if exclude_name in view_name:
                return None

    if exact and name == view_name or \
            not exact and name in view_name:
        return 'active'

1 个答案:

答案 0 :(得分:1)

根据您对行的关注程度,可以将第一个条件简化为未嵌套的条件

if exclude and any(exclude_name in view_name for exclude_name in exclude.split(',')):
    return None

整个方法可以归结为(或多或少不可读的)两层式

if not (exclude and any(exclude_name in view_name for exclude_name)) and (exact and name == view_name or not exact and name in view_name):
    return 'active'

您提到您最终想检查某物是否为'active'。有了以上观察,该函数将准确返回'active',如果

not (exclude and any(exclude_name in view_name for exclude_name)) and (exact and name == view_name or not exact and name in view_name)

因此,如果您只关心该表达式的真值,则可以

return not (exclude and any(exclude_name in view_name for exclude_name)) and (exact and name == view_name or not exact and name in view_name)

并且没有任何条件。