pythonvalidationreturnconventionstypechecking

Return statements in validation functions


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?


Solution

  • In general I agree that pure validation functions may as well be void i.e. return nothing and raise an exception if required.

    However, in this particular case, the _check_int_field function is actually used like this:

    year = _check_int_field(year)
    

    And this makes sense because in the _check_int_field they do this:

    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
    

    So the function is actually doing more than just validation. In which case, it makes sense for the function to return the value.