def encode_to_py3bytes_or_py2str(s):
 fallback_encoding = 'utf8'
 if IS_PY3:
  if isinstance(s, bytes):
   pass
  else:
   s = str(s)
   try:
    s = bytes(s, DEFAULT_ENCODING)
   except UnicodeEncodeError:
    s = bytes(s, fallback_encoding)
 else:
  try:
   s = unicode(s, DEFAULT_ENCODING)
  except TypeError:
   s = unicode(s)
  try:
   s = s.encode(DEFAULT_ENCODING)
  except:
   s = s.encode(fallback_encoding, 'replace')
 return s

def encode_to_py3bytes_or_py2str ( s ) : fallback_encoding = 'utf8' if IS_PY3 : if isinstance ( s , bytes ) : pass else : s = str ( s ) try : s = bytes ( s , DEFAULT_ENCODING ) except UnicodeEncodeError : s = bytes ( s , fallback_encoding ) else : try : s = unicode ( s , DEFAULT_ENCODING ) except TypeError : s = unicode ( s ) try : s = s . encode ( DEFAULT_ENCODING ) except : s = s . encode ( fallback_encoding , 'replace' ) return s
takes anything and attempts to return a py2 string or py3 bytes .