def check_utf8(string):
    if not string:
        return False
    try:
        if isinstance(string, six.text_type):
            string.encode('utf-8')
        else:
            decoded = string.decode('UTF-8')
            if decoded.encode('UTF-8') != string:
                return False
            # A UTF-8 string with surrogates in it is invalid.
            if any(0xD800 <= ord(codepoint) <= 0xDFFF
                   for codepoint in decoded):
                return False
        return '\x00' not in string
    # If string is unicode, decode() will raise UnicodeEncodeError
    # So, we should catch both UnicodeDecodeError & UnicodeEncodeError
    except UnicodeError:
        return False
Validate if a string is valid UTF-8 str or unicode and that it
dataset/ETHPy150Open openstack/swift/swift/common/constraints.py/check_utf8