def safe_encode(text, incoming=None, encoding='utf-8', errors='strict'):
 if (not isinstance(text, basestring)):
  raise TypeError(("%s can't be encoded" % type(text)))
 if (not incoming):
  incoming = (sys.stdin.encoding or sys.getdefaultencoding())
 if isinstance(text, unicode):
  return text.encode(encoding, errors)
 elif (text and (encoding != incoming)):
  text = safe_decode(text, incoming, errors)
  return text.encode(encoding, errors)
 return text

def safe_encode ( text , incoming = None , encoding = 'utf-8' , errors = 'strict' ) : if ( not isinstance ( text , basestring ) ) : raise TypeError ( ( "%s can't be encoded" % type ( text ) ) ) if ( not incoming ) : incoming = ( sys . stdin . encoding or sys . getdefaultencoding ( ) ) if isinstance ( text , unicode ) : return text . encode ( encoding , errors ) elif ( text and ( encoding != incoming ) ) : text = safe_decode ( text , incoming , errors ) return text . encode ( encoding , errors ) return text
safely decodes a binary string to unicode .