I was looking through https://github.com/python/cpython/blob/master/Lib/datetime.py and stumbled across some type checking functions (I simplified them, original is _check_int_field)
def foo(year, month, day): year = check_int(year) month = check_int(month) day = check_int(day) check_int returns the value inputted (if it's an integer) - and raises ValueError if it's not. Let me shorten the function they used:
def check_int(value): if isinstance(value, int): return value if not isinstance(value, int): raise TypeError('integer argument expected, got %s' % type(value)) My question is: What's the meaning behind the return statement? Surely you could just have it implemented as
def check_int(value): if not isinstance(value, int): raise TypeError('integer argument expected, got %s' % value) This would change the foo function to (where you wouldn't have to define the variables, but simply use the foo arguments)
def foo(year, month, day): check_int(year) check_int(month) check_int(day) This would raise an TypeError if the input type is wrong - and simply keep on going with the function arguments if not, without having to define any variables. So why do they return the input variable, if they dont modify it, but simply check it?
_check_int_field? Because in some cases it does return something other than just its argument. Your "simplification" is profoundly unhelpful; your posted version could be replaced, because it's not representative of the real thing.tryblock. This has the potential to change the value ofvalue. if it was a simple type check you could useassert isinstance(value, int), "Type of %s should be int"%srather than defining functions for this at all.returnsimply makes it more general. Consider a call likecheck_int(x + 3); if its valid, you don't have a reference to what is valid, and you need to compute it again.