干净地处理多个变量的TypeErrors

时间:2019-03-18 09:05:15

标签: python error-handling code-structure

当前,我在一个Web应用程序上工作,遇到了一个问题,即一个函数必须处理多个输入,但是其中任意多个输入可能是None(或引起其他错误):

def my_func(input_1: set, input_2: set, input_3: set): -> set
    return input_1 | input_2 | input_3

处理此问题的最优雅的方法是什么?只写出所有案例肯定是一个选择。

期待学到很多东西,谢谢!

2 个答案:

答案 0 :(得分:1)

如果唯一的情况是输入可能是None,则可以分配空的set()而不是None

def my_func(input_1: set, input_2: set, input_3: set) -> set:
    inputs = (
        input_1 or set(), 
        input_2 or set(),
        input_3 or set()
    )

    return set.union(*inputs)

答案 1 :(得分:0)

通过列出所有情况来采用蛮横的方式:

def my_func(input_1, input_2, input_3):
    types = (
        type(input_1),
        type(input_2),
        type(input_3),
        )

    if not all(types):
        return None
    elif not (types[0] and types[1]):
        return input_3
    elif not (types[0] and types[2]):
        return input_2
    elif not (types[1] and types[2]):
        return imput_1
    elif not types[0]:
        return input_2 | input_3
    elif not types[1]:
       return input_1 | input_3
    elif not types[2]:
        return input_1 | input_2
    else:
        return input_1 | input_2 | input_3

不幸的是,这将因使用更多的输入而失败,因为其中一个需要处理2 ^(num_inputs)个案例,所以我愿意提出更好的建议。

相关问题