检查函数是否使用正确的参数调用

时间:2013-05-14 22:02:43

标签: python coding-style assert

哪种编码风格更好 / 正确为什么? 在每个函数中使用assert语句:

def fun_bottom(arg):
    assert isinstance(arg, int)
    #blah blah

def fun_middle(arg):
    assert isinstance(arg, int)
    fun_bottom(arg)
    #blah blah

def fun_top(arg):
    assert isinstance(arg, int)
    fun_middle(arg)
    #blah blah

或者,因为我们知道在fun_bottom函数中检查了arg的类型,所以只省略fun_middle和fun_top中的断言?或许还有另一种解决方案?

编辑#1
哎呀,我被误解了。我只使用assert isinstance(arg,int)作为示例。我会改写这个问题:

使用哪一个:

选项1: 检查参数是否满足每个函数中函数的要求:

def fun_bottom(arg):
    assert arg > 0
    #blah blah

def fun_middle(arg):
    assert arg > 0
    fun_bottom(arg)
    #blah blah

def fun_top(arg):
    assert arg > 0
    fun_middle(arg)
    #blah blah

选项2:因为我们知道在最底层的函数中检查了参数,所以我们在中函数和顶函数中都没有断言:

def fun_bottom(arg):
    assert arg > 0
    #blah blah

def fun_middle(arg):
    fun_bottom(arg)
    #blah blah

def fun_top(arg):
    fun_middle(arg)
    #blah blah

1 个答案:

答案 0 :(得分:2)

我建议采用更加pythonic的做事方式,我会更喜欢:

def fun_fun(some_int): # function that takes hopefully an int/float
    try: # not sure if we got the correct value
        return_value = some_int + 4 % 4 # mathz
        return return_value # return mathz
    except TypeError: # if we didn't get an int/float we'd get this
        return None # So you can return None or do what you like

请参阅:http://docs.python.org/2/tutorial/errors.html

编辑:

也许你想要:

def fun_bottom(arg):
    if arg > 0:
        #blah blah
    else:
        #foo

Assert不应该用在您想要的庄园中,请阅读: http://wiki.python.org/moin/UsingAssertionsEffectively

相关问题