我正在浏览https://github.com/python/cpython/blob/master/Lib/datetime.py,偶然发现了一些类型检查功能(我简化了它们)
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-如果没有错误,只需继续使用函数参数,而无需定义任何变量。那么,为什么不修改输入变量,而只是检查它,为什么返回输入变量呢?
[通常,我同意验证功能也可以是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
因此,该功能实际上所做的不仅仅是验证。在这种情况下,函数返回值是有意义的。