import six


def _to_bytes(obj, encoding):
    """
    In Python3:
        Encode the str type object to bytes type with specific encoding

    In Python2:
        Encode the unicode type object to str type with specific encoding,
        or we just return the 8-bit string of object

    Args:
        obj(unicode|str|bytes) : The object to be encoded.
        encoding(str) : The encoding format

    Returns:
        encoded result of obj
    """
    if obj is None:
        return obj

    assert encoding is not None
    if isinstance(obj, six.text_type):
        return obj.encode(encoding)
    elif isinstance(obj, six.binary_type):
        return obj
    else:
        return six.b(obj)