def _convert_to_type_or_raise(target_type, key, value):
    """Tries to convert value to a target type. Used when
    setting items in mappings.

    Args:
        target_type: the target type for conversion
        key: originating key - used in the error message
        value: value to be converted

    Returns:
        target_type(value)

    Raises:
        TypeError: if any error occurs during the conversion
    """

    if target_type != type(value) and target_type is not None:
        try:
            value = target_type(value)
        except Exception:
            msg = 'cannot assign value of type {0} to key "{1}"'
            msg += "[{0} is not convertible to {2}]"
            raise TypeError(msg.format(type(value).__name__, key, target_type.__name__))
    return value