def safe_encode(string, target_encoding=TERMINAL_ENCODING,
                errors='backslashreplace'):
    """Encode a unicode string to target_encoding.

    If given a str type, check to see that target_encoding can decode it
    without an error. Raises a SafeEncodeError if it can't.
    Given any other type, returns str() version of it.

    Args:
      string: unicode String to encode.
      target_encoding: str Encoding to encode to. Default TERMINAL_ENCODING.
      errors: str Name of the error handler to call if something goes wrong.
              See docs on the codecs module. Default 'backslashreplace'.

    Returns:
      A string encoded with target_encoding, or raises an error.

    """
    if isinstance(string, unicode):
        return string.encode(target_encoding, errors)
    elif isinstance(string, str):
        try:
            string.decode(target_encoding)
        except __HOLE__:
            raise SafeEncodeError(
                'Passed a non-unicode string to safe_encode!')
        else:
            return string
    else:
        # Got something else, probably an int or bool or the like.
        return str(string)
dataset/ETHPy150Open vinitkumar/googlecl/src/googlecl/__init__.py/safe_encode