import sys

if sys.version_info[0] >= 3: # pragma: no cover (future Python3 compat)
    text_type = str
else:
    text_type = unicode

def encode(u):
    """Try to encode something from Unicode to a string using the
    default encoding.  If it fails, try encoding as UTF-8."""
    if not isinstance(u, text_type):
        return u
    try:
        return u.encode()
    except UnicodeEncodeError:
        return u.encode("utf-8")

def decode(s):
    """Try to decode someting from string to Unicode using the
    default encoding.  If it fails, try decoding as UTF-8."""
    if isinstance(s, text_type):
        return s
    try:
        return s.decode()
    except UnicodeDecodeError:
        try:
            return s.decode("utf-8")
        except UnicodeDecodeError:
            return s # best we can do
