我在浏览https://github.com/python/cpython/blob/master/Lib/datetime.py,偶然发现了一些类型检查函数(我简化了它们,最初是_check_int_field)
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))
我的问题是: return语句背后的含义是什么?当然,您可以将其实现为
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 -如果输入类型不正确,则简单地继续使用函数参数,而不必定义任何变量。那么,如果他们不修改输入变量,而只是简单地检查它,为什么还要返回输入变量呢?
发布于 2019-10-12 15:50:18
一般来说,我同意纯验证函数也可以是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
所以这个函数实际上做的不仅仅是验证。在这种情况下,函数返回值是有意义的。
https://stackoverflow.com/questions/58355772
复制