验证函数中的返回语句

2024-03-28 14:13:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我在浏览https://github.com/python/cpython/blob/master/Lib/datetime.py时偶然发现了一些类型检查函数(我简化了它们,原来是{u check}u int}字段)

def foo(year, month, day):
    year = check_int(year)
    month = check_int(month)
    day = check_int(day)

check_int返回输入的值(如果是整数)-如果不是,则引发ValueError。让我缩短他们使用的函数:

def check_int(value):
    if isinstance(value, int):
        return value
    if not isinstance(value, int):
        raise TypeError('integer argument expected, got %s' % type(value))

我的问题是:回报声明背后的含义是什么?你当然可以把它当作

def check_int(value):
    if not isinstance(value, int):
        raise TypeError('integer argument expected, got %s' % value)

这将把foo函数改为(在这里不必定义变量,只需使用foo参数)

def foo(year, month, day):
    check_int(year)
    check_int(month)
    check_int(day)

如果输入类型错误,这将引发TypeError—如果不是,则继续使用函数参数,而不必定义任何变量。那么,如果他们不修改输入变量,而只是简单地检查它,为什么还要返回输入变量呢


Tags: 函数类型iffoovaluedefchecknot
1条回答
网友
1楼 · 发布于 2024-03-28 14:13:25

一般来说,我同意纯验证函数也可以是void,即不返回任何内容,并在需要时引发异常

然而,在这种特殊情况下,_check_int_field函数实际上是这样使用的:

year = _check_int_field(year)

这是有意义的,因为在_check_int_field中,它们是这样做的:

try:
    value = value.__int__()
except AttributeError:
    pass
else:
    if not isinstance(value, int):
        raise TypeError('__int__ returned non-int (type %s)' %
                        type(value).__name__)
    return value

所以函数实际上不仅仅是验证。在这种情况下,函数返回值是有意义的

相关问题 更多 >