def to_str(obj, encoding='<STR_LIT:utf-8>', **encode_args):
<EOL>if isinstance(obj, binary_type):<EOL><INDENT>return obj<EOL><DEDENT>if isinstance(obj, text_type) or hasattr(obj, text_type_magicmethod):<EOL><INDENT>return text_type(obj).encode(encoding, **encode_args)<EOL><DEDENT>return binary_type(obj)<EOL>
r"""
    Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For
    example::

        >>> some_str = b"\xff"
        >>> some_unicode = u"\u1234"
        >>> some_exception = Exception(u'Error: ' + some_unicode)
        >>> r(to_str(some_str))
        b'\xff'
        >>> r(to_str(some_unicode))
        b'\xe1\x88\xb4'
        >>> r(to_str(some_exception))
        b'Error: \xe1\x88\xb4'
        >>> r(to_str([42]))
        b'[42]'

    See source code for detailed semantics.