validate that a value is in ``within`` and optionally a ``dtype``

def __within2(value, within=None, errmsg=None, dtype=None):
    '''validate that a value is in ``within`` and optionally a ``dtype``'''
    valid, _value = False, value
    if dtype:
        try:
            _value = dtype(value)  # TODO: this is a bit loose when dtype is a class
            valid = _value in within
        except ValueError:
            pass
    else:
        valid = _value in within
    if errmsg is None:
        if dtype:
            typename = getattr(dtype, '__name__',
                               hasattr(dtype, '__class__')
                               and getattr(dtype.__class__, 'name', dtype))
            errmsg = '{0} within \'{1}\''.format(typename, within)
        else:
            errmsg = 'within \'{0}\''.format(within)
    return (valid, _value, errmsg)