import six


def utf8_encode(val):
    """Return a string in bytes; use utf-8 for unicode strings."""
    if isinstance(val, six.text_type):
        return val.encode('utf-8')
    elif isinstance(val, six.binary_type):
        return val
    else:
        raise TypeError('{} is not a unicode or str object'.format(val))