Adding Python 3 compatibility to Clang Python bindings

Russell Keith-Magee via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 13 20:45:23 PST 2016


For your consideration:

Attached is a patch that adds Python 3 compatibility (without losing Python
2 compatibility) to Clang’s Python bindings.

The patch also includes PEP8 formatting cleanups, and a setup.py file to
make it easier to install the bindings into a working Python development
environment.

Yours,
Russell Keith-Magee %-)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-commits/attachments/20160114/f7750bba/attachment-0001.html>
-------------- next part --------------
diff --git a/bindings/python/clang/cindex.py b/bindings/python/clang/cindex.py
index e4b3876..b1a9abe 100644
--- a/bindings/python/clang/cindex.py
+++ b/bindings/python/clang/cindex.py
@@ -6,6 +6,7 @@
 # License. See LICENSE.TXT for details.
 #
 #===------------------------------------------------------------------------===#
+from __future__ import unicode_literals
 
 r"""
 Clang Indexing Library Bindings
@@ -75,6 +76,7 @@ c_object_p = POINTER(c_void_p)
 
 callbacks = {}
 
+
 ### Exception Classes ###
 
 class TranslationUnitLoadError(Exception):
@@ -87,6 +89,7 @@ class TranslationUnitLoadError(Exception):
     """
     pass
 
+
 class TranslationUnitSaveError(Exception):
     """Represents an error that occurred when saving a TranslationUnit.
 
@@ -117,6 +120,7 @@ class TranslationUnitSaveError(Exception):
         self.save_error = enumeration
         Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
 
+
 ### Structures and Utility Classes ###
 
 class CachedProperty(object):
@@ -157,6 +161,7 @@ class _CXString(Structure):
         assert isinstance(res, _CXString)
         return conf.lib.clang_getCString(res)
 
+
 class SourceLocation(Structure):
     """
     A SourceLocation represents a particular location within a source file.
@@ -167,8 +172,9 @@ class SourceLocation(Structure):
     def _get_instantiation(self):
         if self._data is None:
             f, l, c, o = c_object_p(), c_uint(), c_uint(), c_uint()
-            conf.lib.clang_getInstantiationLocation(self, byref(f), byref(l),
-                    byref(c), byref(o))
+            conf.lib.clang_getInstantiationLocation(
+                self, byref(f), byref(l), byref(c), byref(o)
+            )
             if f:
                 f = File(f)
             else:
@@ -228,6 +234,7 @@ class SourceLocation(Structure):
         return "<SourceLocation file %r, line %r, column %r>" % (
             filename, self.line, self.column)
 
+
 class SourceRange(Structure):
     """
     A SourceRange describes a range of source locations within the source
@@ -272,8 +279,8 @@ class SourceRange(Structure):
             return False
         if other.file is None and self.start.file is None:
             pass
-        elif ( self.start.file.name != other.file.name or
-               other.file.name != self.end.file.name):
+        elif (self.start.file.name != other.file.name or
+              other.file.name != self.end.file.name):
             # same file name
             return False
         # same file, in between lines
@@ -292,6 +299,7 @@ class SourceRange(Structure):
     def __repr__(self):
         return "<SourceRange start %r, end %r>" % (self.start, self.end)
 
+
 class Diagnostic(object):
     """
     A Diagnostic is a single instance of a Clang diagnostic. It includes the
@@ -300,10 +308,10 @@ class Diagnostic(object):
     """
 
     Ignored = 0
-    Note    = 1
+    Note = 1
     Warning = 2
-    Error   = 3
-    Fatal   = 4
+    Error = 3
+    Fatal = 4
 
     def __init__(self, ptr):
         self.ptr = ptr
@@ -321,7 +329,7 @@ class Diagnostic(object):
 
     @property
     def spelling(self):
-        return conf.lib.clang_getDiagnosticSpelling(self)
+        return conf.lib.clang_getDiagnosticSpelling(self).decode('utf-8')
 
     @property
     def ranges(self):
@@ -350,8 +358,9 @@ class Diagnostic(object):
 
             def __getitem__(self, key):
                 range = SourceRange()
-                value = conf.lib.clang_getDiagnosticFixIt(self.diag, key,
-                        byref(range))
+                value = conf.lib.clang_getDiagnosticFixIt(
+                    self.diag, key, byref(range)
+                )
                 if len(value) == 0:
                     raise IndexError
 
@@ -367,12 +376,12 @@ class Diagnostic(object):
     @property
     def category_name(self):
         """The string name of the category for this diagnostic."""
-        return conf.lib.clang_getDiagnosticCategoryText(self)
+        return conf.lib.clang_getDiagnosticCategoryText(self).decode('utf-8')
 
     @property
     def option(self):
         """The command-line option that enables this diagnostic."""
-        return conf.lib.clang_getDiagnosticOption(self, None)
+        return conf.lib.clang_getDiagnosticOption(self, None).decode('utf-8')
 
     @property
     def disable_option(self):
@@ -380,14 +389,15 @@ class Diagnostic(object):
         disable = _CXString()
         conf.lib.clang_getDiagnosticOption(self, byref(disable))
 
-        return conf.lib.clang_getCString(disable)
+        return conf.lib.clang_getCString(disable).decode('utf-8')
 
     def __repr__(self):
         return "<Diagnostic severity %r, location %r, spelling %r>" % (
             self.severity, self.location, self.spelling)
 
     def from_param(self):
-      return self.ptr
+        return self.ptr
+
 
 class FixIt(object):
     """
@@ -398,11 +408,12 @@ class FixIt(object):
 
     def __init__(self, range, value):
         self.range = range
-        self.value = value
+        self.value = value.decode('utf-8')
 
     def __repr__(self):
         return "<FixIt range %r, value %r>" % (self.range, self.value)
 
+
 class TokenGroup(object):
     """Helper class to facilitate token management.
 
@@ -435,8 +446,9 @@ class TokenGroup(object):
         tokens_memory = POINTER(Token)()
         tokens_count = c_uint()
 
-        conf.lib.clang_tokenize(tu, extent, byref(tokens_memory),
-                byref(tokens_count))
+        conf.lib.clang_tokenize(
+            tu, extent, byref(tokens_memory), byref(tokens_count)
+        )
 
         count = int(tokens_count.value)
 
@@ -449,7 +461,7 @@ class TokenGroup(object):
 
         token_group = TokenGroup(tu, tokens_memory, tokens_count)
 
-        for i in xrange(0, count):
+        for i in range(0, count):
             token = Token()
             token.int_data = tokens_array[i].int_data
             token.ptr_data = tokens_array[i].ptr_data
@@ -458,10 +470,11 @@ class TokenGroup(object):
 
             yield token
 
+
 class TokenKind(object):
     """Describes a specific type of a Token."""
 
-    _value_map = {} # int -> TokenKind
+    _value_map = {}  # int -> TokenKind
 
     def __init__(self, value, name):
         """Create a new TokenKind instance from a numeric value and a name."""
@@ -495,6 +508,7 @@ class TokenKind(object):
         TokenKind._value_map[value] = kind
         setattr(TokenKind, name, kind)
 
+
 ### Cursor Kinds ###
 class BaseEnumeration(object):
     """
@@ -512,13 +526,12 @@ class BaseEnumeration(object):
         if value >= len(self.__class__._kinds):
             self.__class__._kinds += [None] * (value - len(self.__class__._kinds) + 1)
         if self.__class__._kinds[value] is not None:
-            raise ValueError,'{0} value {1} already loaded'.format(
-                str(self.__class__), value)
+            raise ValueError('{0} value {1} already loaded'.format(
+                str(self.__class__), value))
         self.value = value
         self.__class__._kinds[value] = self
         self.__class__._name_map = None
 
-
     def from_param(self):
         return self.value
 
@@ -535,7 +548,7 @@ class BaseEnumeration(object):
     @classmethod
     def from_id(cls, id):
         if id >= len(cls._kinds) or cls._kinds[id] is None:
-            raise ValueError,'Unknown template argument kind %d' % id
+            raise ValueError('Unknown template argument kind %d' % id)
         return cls._kinds[id]
 
     def __repr__(self):
@@ -554,7 +567,7 @@ class CursorKind(BaseEnumeration):
     @staticmethod
     def get_all_kinds():
         """Return all CursorKind enumeration instances."""
-        return filter(None, CursorKind._kinds)
+        return [k for k in CursorKind._kinds if k]
 
     def is_declaration(self):
         """Test if this is a declaration kind."""
@@ -1120,7 +1133,9 @@ CursorKind.MODULE_IMPORT_DECL = CursorKind(600)
 # A type alias template declaration
 CursorKind.TYPE_ALIAS_TEMPLATE_DECL = CursorKind(601)
 
+
 ### Template Argument Kinds ###
+
 class TemplateArgumentKind(BaseEnumeration):
     """
     A TemplateArgumentKind describes the kind of entity that a template argument
@@ -1137,6 +1152,7 @@ TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2)
 TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3)
 TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4)
 
+
 ### Cursors ###
 
 class Cursor(Structure):
@@ -1228,7 +1244,7 @@ class Cursor(Structure):
     def spelling(self):
         """Return the spelling of the entity pointed at by the cursor."""
         if not hasattr(self, '_spelling'):
-            self._spelling = conf.lib.clang_getCursorSpelling(self)
+            self._spelling = conf.lib.clang_getCursorSpelling(self).decode('utf-8')
 
         return self._spelling
 
@@ -1244,7 +1260,7 @@ class Cursor(Structure):
         if not hasattr(self, '_displayname'):
             self._displayname = conf.lib.clang_getCursorDisplayName(self)
 
-        return self._displayname
+        return self._displayname.decode('utf-8')
 
     @property
     def mangled_name(self):
@@ -1252,7 +1268,7 @@ class Cursor(Structure):
         if not hasattr(self, '_mangled_name'):
             self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
 
-        return self._mangled_name
+        return self._mangled_name.decode('utf-8')
 
     @property
     def location(self):
@@ -1339,8 +1355,7 @@ class Cursor(Structure):
         """
         if not hasattr(self, '_underlying_type'):
             assert self.kind.is_declaration()
-            self._underlying_type = \
-              conf.lib.clang_getTypedefDeclUnderlyingType(self)
+            self._underlying_type = conf.lib.clang_getTypedefDeclUnderlyingType(self)
 
         return self._underlying_type
 
@@ -1376,8 +1391,7 @@ class Cursor(Structure):
                                         TypeKind.ULONG,
                                         TypeKind.ULONGLONG,
                                         TypeKind.UINT128):
-                self._enum_value = \
-                  conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
+                self._enum_value = conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
             else:
                 self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
         return self._enum_value
@@ -1386,8 +1400,7 @@ class Cursor(Structure):
     def objc_type_encoding(self):
         """Return the Objective-C type encoding as a str."""
         if not hasattr(self, '_objc_type_encoding'):
-            self._objc_type_encoding = \
-              conf.lib.clang_getDeclObjCTypeEncoding(self)
+            self._objc_type_encoding = conf.lib.clang_getDeclObjCTypeEncoding(self).decode('utf-8')
 
         return self._objc_type_encoding
 
@@ -1482,10 +1495,11 @@ class Cursor(Structure):
             # Create reference to TU so it isn't GC'd before Cursor.
             child._tu = self._tu
             children.append(child)
-            return 1 # continue
+            return 1  # continue
         children = []
-        conf.lib.clang_visitChildren(self, callbacks['cursor_visit'](visitor),
-            children)
+        conf.lib.clang_visitChildren(
+            self, callbacks['cursor_visit'](visitor), children
+        )
         return iter(children)
 
     def walk_preorder(self):
@@ -1563,6 +1577,7 @@ class Cursor(Structure):
         res._tu = args[0]._tu
         return res
 
+
 class StorageClass(object):
     """
     Describes the storage class of a declaration
@@ -1576,7 +1591,7 @@ class StorageClass(object):
         if value >= len(StorageClass._kinds):
             StorageClass._kinds += [None] * (value - len(StorageClass._kinds) + 1)
         if StorageClass._kinds[value] is not None:
-            raise ValueError,'StorageClass already loaded'
+            raise ValueError('StorageClass already loaded')
         self.value = value
         StorageClass._kinds[value] = self
         StorageClass._name_map = None
@@ -1589,15 +1604,15 @@ class StorageClass(object):
         """Get the enumeration name of this storage class."""
         if self._name_map is None:
             self._name_map = {}
-            for key,value in StorageClass.__dict__.items():
-                if isinstance(value,StorageClass):
+            for key, value in StorageClass.__dict__.items():
+                if isinstance(value, StorageClass):
                     self._name_map[value] = key
         return self._name_map[self]
 
     @staticmethod
     def from_id(id):
         if id >= len(StorageClass._kinds) or not StorageClass._kinds[id]:
-            raise ValueError,'Unknown storage class %d' % id
+            raise ValueError('Unknown storage class %d' % id)
         return StorageClass._kinds[id]
 
     def __repr__(self):
@@ -1636,6 +1651,7 @@ AccessSpecifier.PROTECTED = AccessSpecifier(2)
 AccessSpecifier.PRIVATE = AccessSpecifier(3)
 AccessSpecifier.NONE = AccessSpecifier(4)
 
+
 ### Type Kinds ###
 
 class TypeKind(BaseEnumeration):
@@ -1650,7 +1666,7 @@ class TypeKind(BaseEnumeration):
     @property
     def spelling(self):
         """Retrieve the spelling of this TypeKind."""
-        return conf.lib.clang_getTypeKindSpelling(self.value)
+        return conf.lib.clang_getTypeKindSpelling(self.value).decode('utf-8')
 
     def __repr__(self):
         return 'TypeKind.%s' % (self.name,)
@@ -1705,6 +1721,7 @@ TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
 TypeKind.MEMBERPOINTER = TypeKind(117)
 TypeKind.AUTO = TypeKind(118)
 
+
 class RefQualifierKind(BaseEnumeration):
     """Describes a specific ref-qualifier of a type."""
 
@@ -1722,6 +1739,7 @@ RefQualifierKind.NONE = RefQualifierKind(0)
 RefQualifierKind.LVALUE = RefQualifierKind(1)
 RefQualifierKind.RVALUE = RefQualifierKind(2)
 
+
 class Type(Structure):
     """
     The type of an element in the abstract syntax tree.
@@ -1760,7 +1778,7 @@ class Type(Structure):
 
                 if key >= len(self):
                     raise IndexError("Index greater than container length: "
-                                     "%d > %d" % ( key, len(self) ))
+                                     "%d > %d" % (key, len(self)))
 
                 result = conf.lib.clang_getArgType(self.parent, key)
                 if result.kind == TypeKind.INVALID:
@@ -1918,7 +1936,7 @@ class Type(Structure):
         """
         Retrieve the offset of a field in the record.
         """
-        return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname))
+        return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname.encode('utf-8')))
 
     def get_ref_qualifier(self):
         """
@@ -1936,16 +1954,17 @@ class Type(Structure):
             # Create reference to TU so it isn't GC'd before Cursor.
             field._tu = self._tu
             fields.append(field)
-            return 1 # continue
+            return 1  # continue
         fields = []
-        conf.lib.clang_Type_visitFields(self,
-                            callbacks['fields_visit'](visitor), fields)
+        conf.lib.clang_Type_visitFields(
+            self, callbacks['fields_visit'](visitor), fields
+        )
         return iter(fields)
 
     @property
     def spelling(self):
         """Retrieve the spelling of this Type."""
-        return conf.lib.clang_getTypeSpelling(self)
+        return conf.lib.clang_getTypeSpelling(self).decode('utf-8')
 
     def __eq__(self, other):
         if type(other) != type(self):
@@ -1956,6 +1975,7 @@ class Type(Structure):
     def __ne__(self, other):
         return not self.__eq__(other)
 
+
 ## CIndex Objects ##
 
 # CIndex objects (derived from ClangObject) are essentially lightweight
@@ -1989,23 +2009,24 @@ SpellingCache = {
             # 3: CompletionChunk.Kind("Placeholder"),
             # 4: CompletionChunk.Kind("Informative"),
             # 5 : CompletionChunk.Kind("CurrentParameter"),
-            6: '(',   # CompletionChunk.Kind("LeftParen"),
-            7: ')',   # CompletionChunk.Kind("RightParen"),
-            8: '[',   # CompletionChunk.Kind("LeftBracket"),
-            9: ']',   # CompletionChunk.Kind("RightBracket"),
+            6: '(',  # CompletionChunk.Kind("LeftParen"),
+            7: ')',  # CompletionChunk.Kind("RightParen"),
+            8: '[',  # CompletionChunk.Kind("LeftBracket"),
+            9: ']',  # CompletionChunk.Kind("RightBracket"),
             10: '{',  # CompletionChunk.Kind("LeftBrace"),
             11: '}',  # CompletionChunk.Kind("RightBrace"),
             12: '<',  # CompletionChunk.Kind("LeftAngle"),
             13: '>',  # CompletionChunk.Kind("RightAngle"),
-            14: ', ', # CompletionChunk.Kind("Comma"),
+            14: ', ',  # CompletionChunk.Kind("Comma"),
             # 15: CompletionChunk.Kind("ResultType"),
-            16: ':',  # CompletionChunk.Kind("Colon"),
-            17: ';',  # CompletionChunk.Kind("SemiColon"),
-            18: '=',  # CompletionChunk.Kind("Equal"),
-            19: ' ',  # CompletionChunk.Kind("HorizontalSpace"),
+            16: ':',   # CompletionChunk.Kind("Colon"),
+            17: ';',   # CompletionChunk.Kind("SemiColon"),
+            18: '=',   # CompletionChunk.Kind("Equal"),
+            19: ' ',   # CompletionChunk.Kind("HorizontalSpace"),
             # 20: CompletionChunk.Kind("VerticalSpace")
 }
 
+
 class CompletionChunk:
     class Kind:
         def __init__(self, name):
@@ -2029,7 +2050,7 @@ class CompletionChunk:
     def spelling(self):
         if self.__kindNumber in SpellingCache:
                 return SpellingCache[self.__kindNumber]
-        return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling
+        return conf.lib.clang_getCompletionChunkText(self.cs, self.key).spelling.decode('utf-8')
 
     # We do not use @CachedProperty here, as the manual implementation is
     # apparently still significantly faster. Please profile carefully if you
@@ -2051,24 +2072,25 @@ class CompletionChunk:
                                                                 self.key)
 
         if (res):
-          return CompletionString(res)
+            return CompletionString(res)
         else:
-          None
+            None
 
     def isKindOptional(self):
-      return self.__kindNumber == 0
+        return self.__kindNumber == 0
 
     def isKindTypedText(self):
-      return self.__kindNumber == 1
+        return self.__kindNumber == 1
 
     def isKindPlaceHolder(self):
-      return self.__kindNumber == 3
+        return self.__kindNumber == 3
 
     def isKindInformative(self):
-      return self.__kindNumber == 4
+        return self.__kindNumber == 4
 
     def isKindResultType(self):
-      return self.__kindNumber == 15
+        return self.__kindNumber == 15
+
 
 completionChunkKindMap = {
             0: CompletionChunk.Kind("Optional"),
@@ -2093,6 +2115,7 @@ completionChunkKindMap = {
             19: CompletionChunk.Kind("HorizontalSpace"),
             20: CompletionChunk.Kind("VerticalSpace")}
 
+
 class CompletionString(ClangObject):
     class Availability:
         def __init__(self, name):
@@ -2132,10 +2155,11 @@ class CompletionString(ClangObject):
         return _CXString()
 
     def __repr__(self):
+        comment = self.briefComment.spelling.decode('utf-8') if self.briefComment.spelling else 'None'
         return " | ".join([str(a) for a in self]) \
                + " || Priority: " + str(self.priority) \
                + " || Availability: " + str(self.availability) \
-               + " || Brief comment: " + str(self.briefComment.spelling)
+               + " || Brief comment: " + comment
 
 availabilityKinds = {
             0: CompletionChunk.Kind("Available"),
@@ -2143,6 +2167,7 @@ availabilityKinds = {
             2: CompletionChunk.Kind("NotAvailable"),
             3: CompletionChunk.Kind("NotAccessible")}
 
+
 class CodeCompletionResult(Structure):
     _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
 
@@ -2157,6 +2182,7 @@ class CodeCompletionResult(Structure):
     def string(self):
         return CompletionString(self.completionString)
 
+
 class CCRStructure(Structure):
     _fields_ = [('results', POINTER(CodeCompletionResult)),
                 ('numResults', c_int)]
@@ -2170,6 +2196,7 @@ class CCRStructure(Structure):
 
         return self.results[key]
 
+
 class CodeCompletionResults(ClangObject):
     def __init__(self, ptr):
         assert isinstance(ptr, POINTER(CCRStructure)) and ptr
@@ -2189,11 +2216,10 @@ class CodeCompletionResults(ClangObject):
     def diagnostics(self):
         class DiagnosticsItr:
             def __init__(self, ccr):
-                self.ccr= ccr
+                self.ccr = ccr
 
             def __len__(self):
-                return int(\
-                  conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
+                return int(conf.lib.clang_codeCompleteGetNumDiagnostics(self.ccr))
 
             def __getitem__(self, key):
                 return conf.lib.clang_codeCompleteGetDiagnostic(self.ccr, key)
@@ -2224,7 +2250,7 @@ class Index(ClangObject):
         """Load a TranslationUnit from the given AST file."""
         return TranslationUnit.from_ast_file(path, self)
 
-    def parse(self, path, args=None, unsaved_files=None, options = 0):
+    def parse(self, path, args=None, unsaved_files=None, options=0):
         """Load the translation unit from the given source code file by running
         clang and generating the AST before loading. Additional command line
         parameters can be passed to clang via the args parameter.
@@ -2240,6 +2266,7 @@ class Index(ClangObject):
         return TranslationUnit.from_source(path, args, unsaved_files, options,
                                            self)
 
+
 class TranslationUnit(ClangObject):
     """Represents a source code translation unit.
 
@@ -2332,7 +2359,8 @@ class TranslationUnit(ClangObject):
 
         args_array = None
         if len(args) > 0:
-            args_array = (c_char_p * len(args))(* args)
+            bargs = [arg.encode('utf-8') for arg in args]
+            args_array = (c_char_p * len(args))(* bargs)
 
         unsaved_array = None
         if len(unsaved_files) > 0:
@@ -2341,13 +2369,16 @@ class TranslationUnit(ClangObject):
                 if hasattr(contents, "read"):
                     contents = contents.read()
 
-                unsaved_array[i].name = name
-                unsaved_array[i].contents = contents
+                unsaved_array[i].name = name.encode('utf-8')
+                unsaved_array[i].contents = contents.encode('utf-8')
                 unsaved_array[i].length = len(contents)
 
-        ptr = conf.lib.clang_parseTranslationUnit(index, filename, args_array,
-                                    len(args), unsaved_array,
-                                    len(unsaved_files), options)
+        ptr = conf.lib.clang_parseTranslationUnit(
+            index, filename.encode('utf-8') if filename else None,
+            args_array, len(args),
+            unsaved_array, len(unsaved_files),
+            options
+        )
 
         if not ptr:
             raise TranslationUnitLoadError("Error parsing translation unit.")
@@ -2370,7 +2401,7 @@ class TranslationUnit(ClangObject):
         if index is None:
             index = Index.create()
 
-        ptr = conf.lib.clang_createTranslationUnit(index, filename)
+        ptr = conf.lib.clang_createTranslationUnit(index, filename.encode('utf-8'))
         if not ptr:
             raise TranslationUnitLoadError(filename)
 
@@ -2397,7 +2428,7 @@ class TranslationUnit(ClangObject):
     @property
     def spelling(self):
         """Get the original translation unit source file name."""
-        return conf.lib.clang_getTranslationUnitSpelling(self)
+        return conf.lib.clang_getTranslationUnitSpelling(self).decode('utf-8')
 
     def get_includes(self):
         """
@@ -2414,8 +2445,9 @@ class TranslationUnit(ClangObject):
 
         # Automatically adapt CIndex/ctype pointers to python objects
         includes = []
-        conf.lib.clang_getInclusions(self,
-                callbacks['translation_unit_includes'](visitor), includes)
+        conf.lib.clang_getInclusions(
+            self, callbacks['translation_unit_includes'](visitor), includes
+        )
 
         return iter(includes)
 
@@ -2463,15 +2495,16 @@ class TranslationUnit(ClangObject):
         start_location, end_location = locations
 
         if hasattr(start_location, '__len__'):
-            start_location = SourceLocation.from_position(self, f,
-                start_location[0], start_location[1])
+            start_location = SourceLocation.from_position(
+                self, f, start_location[0], start_location[1]
+            )
         elif isinstance(start_location, int):
-            start_location = SourceLocation.from_offset(self, f,
-                start_location)
+            start_location = SourceLocation.from_offset(self, f, start_location)
 
         if hasattr(end_location, '__len__'):
-            end_location = SourceLocation.from_position(self, f,
-                end_location[0], end_location[1])
+            end_location = SourceLocation.from_position(
+                self, f, end_location[0], end_location[1]
+            )
         elif isinstance(end_location, int):
             end_location = SourceLocation.from_offset(self, f, end_location)
 
@@ -2515,19 +2548,20 @@ class TranslationUnit(ClangObject):
         unsaved_files_array = 0
         if len(unsaved_files):
             unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
-            for i,(name,value) in enumerate(unsaved_files):
+            for i, (name, value) in enumerate(unsaved_files):
                 if not isinstance(value, str):
                     # FIXME: It would be great to support an efficient version
                     # of this, one day.
                     value = value.read()
-                    print value
+                    print(value)
                 if not isinstance(value, str):
-                    raise TypeError,'Unexpected unsaved file contents.'
+                    raise TypeError('Unexpected unsaved file contents.')
                 unsaved_files_array[i].name = name
                 unsaved_files_array[i].contents = value
                 unsaved_files_array[i].length = len(value)
-        ptr = conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
-                unsaved_files_array, options)
+        conf.lib.clang_reparseTranslationUnit(
+            self, len(unsaved_files), unsaved_files_array, options
+        )
 
     def save(self, filename):
         """Saves the TranslationUnit to a file.
@@ -2545,11 +2579,10 @@ class TranslationUnit(ClangObject):
         filename -- The path to save the translation unit to.
         """
         options = conf.lib.clang_defaultSaveOptions(self)
-        result = int(conf.lib.clang_saveTranslationUnit(self, filename,
+        result = int(conf.lib.clang_saveTranslationUnit(self, filename.encode('utf-8'),
                                                         options))
         if result != 0:
-            raise TranslationUnitSaveError(result,
-                'Error saving TranslationUnit.')
+            raise TranslationUnitSaveError(result, 'Error saving TranslationUnit.')
 
     def codeComplete(self, path, line, column, unsaved_files=None,
                      include_macros=False, include_code_patterns=False,
@@ -2579,19 +2612,20 @@ class TranslationUnit(ClangObject):
         unsaved_files_array = 0
         if len(unsaved_files):
             unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
-            for i,(name,value) in enumerate(unsaved_files):
+            for i, (name, value) in enumerate(unsaved_files):
                 if not isinstance(value, str):
                     # FIXME: It would be great to support an efficient version
                     # of this, one day.
                     value = value.read()
-                    print value
+                    print(value)
                 if not isinstance(value, str):
-                    raise TypeError,'Unexpected unsaved file contents.'
-                unsaved_files_array[i].name = name
-                unsaved_files_array[i].contents = value
+                    raise TypeError('Unexpected unsaved file contents.')
+                unsaved_files_array[i].name = name.encode('utf-8')
+                unsaved_files_array[i].contents = value.encode('utf-8')
                 unsaved_files_array[i].length = len(value)
-        ptr = conf.lib.clang_codeCompleteAt(self, path, line, column,
-                unsaved_files_array, len(unsaved_files), options)
+        ptr = conf.lib.clang_codeCompleteAt(
+            self, path.encode('utf-8'), line, column, unsaved_files_array, len(unsaved_files), options
+        )
         if ptr:
             return CodeCompletionResults(ptr)
         return None
@@ -2609,6 +2643,7 @@ class TranslationUnit(ClangObject):
 
         return TokenGroup.get_tokens(self, extent)
 
+
 class File(ClangObject):
     """
     The File class represents a particular source file that is part of a
@@ -2618,12 +2653,12 @@ class File(ClangObject):
     @staticmethod
     def from_name(translation_unit, file_name):
         """Retrieve a file handle within the given translation unit."""
-        return File(conf.lib.clang_getFile(translation_unit, file_name))
+        return File(conf.lib.clang_getFile(translation_unit, file_name.encode('utf-8')))
 
     @property
     def name(self):
         """Return the complete file and path name of the file."""
-        return conf.lib.clang_getCString(conf.lib.clang_getFileName(self))
+        return conf.lib.clang_getCString(conf.lib.clang_getFileName(self)).decode('utf-8')
 
     @property
     def time(self):
@@ -2644,6 +2679,7 @@ class File(ClangObject):
         res._tu = args[0]._tu
         return res
 
+
 class FileInclusion(object):
     """
     The FileInclusion class represents the inclusion of one source file by
@@ -2664,6 +2700,7 @@ class FileInclusion(object):
         """True if the included file is the input file."""
         return self.depth == 0
 
+
 class CompilationDatabaseError(Exception):
     """Represents an error that occurred when working with a CompilationDatabase
 
@@ -2689,6 +2726,7 @@ class CompilationDatabaseError(Exception):
         self.cdb_error = enumeration
         Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
 
+
 class CompileCommand(object):
     """Represents the compile command used to build a file"""
     def __init__(self, cmd, ccmds):
@@ -2711,9 +2749,10 @@ class CompileCommand(object):
         Invariant : the first argument is the compiler executable
         """
         length = conf.lib.clang_CompileCommand_getNumArgs(self.cmd)
-        for i in xrange(length):
+        for i in range(length):
             yield conf.lib.clang_CompileCommand_getArg(self.cmd, i)
 
+
 class CompileCommands(object):
     """
     CompileCommands is an iterable object containing all CompileCommand
@@ -2740,6 +2779,7 @@ class CompileCommands(object):
             return None
         return CompileCommands(res)
 
+
 class CompilationDatabase(ClangObject):
     """
     The CompilationDatabase is a wrapper class around
@@ -2763,9 +2803,10 @@ class CompilationDatabase(ClangObject):
         """Builds a CompilationDatabase from the database found in buildDir"""
         errorCode = c_uint()
         try:
-            cdb = conf.lib.clang_CompilationDatabase_fromDirectory(buildDir,
-                byref(errorCode))
-        except CompilationDatabaseError as e:
+            cdb = conf.lib.clang_CompilationDatabase_fromDirectory(
+                buildDir.encode('utf-8'), byref(errorCode)
+            )
+        except CompilationDatabaseError:
             raise CompilationDatabaseError(int(errorCode.value),
                                            "CompilationDatabase loading failed")
         return cdb
@@ -2776,7 +2817,7 @@ class CompilationDatabase(ClangObject):
         build filename. Returns None if filename is not found in the database.
         """
         return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
-                                                                     filename)
+                                                                     filename.encode('utf-8'))
 
     def getAllCompileCommands(self):
         """
@@ -2806,7 +2847,7 @@ class Token(Structure):
 
         This is the textual representation of the token in source.
         """
-        return conf.lib.clang_getTokenSpelling(self._tu, self)
+        return conf.lib.clang_getTokenSpelling(self._tu, self).decode('utf-8')
 
     @property
     def kind(self):
@@ -2835,653 +2876,807 @@ class Token(Structure):
 # Now comes the plumbing to hook up the C library.
 
 # Register callback types in common container.
-callbacks['translation_unit_includes'] = CFUNCTYPE(None, c_object_p,
-        POINTER(SourceLocation), c_uint, py_object)
+callbacks['translation_unit_includes'] = CFUNCTYPE(
+    None, c_object_p, POINTER(SourceLocation), c_uint, py_object
+)
 callbacks['cursor_visit'] = CFUNCTYPE(c_int, Cursor, Cursor, py_object)
 callbacks['fields_visit'] = CFUNCTYPE(c_int, Cursor, py_object)
 
 # Functions strictly alphabetical order.
 functionList = [
-  ("clang_annotateTokens",
-   [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]),
-
-  ("clang_CompilationDatabase_dispose",
-   [c_object_p]),
-
-  ("clang_CompilationDatabase_fromDirectory",
-   [c_char_p, POINTER(c_uint)],
-   c_object_p,
-   CompilationDatabase.from_result),
-
-  ("clang_CompilationDatabase_getAllCompileCommands",
-   [c_object_p],
-   c_object_p,
-   CompileCommands.from_result),
-
-  ("clang_CompilationDatabase_getCompileCommands",
-   [c_object_p, c_char_p],
-   c_object_p,
-   CompileCommands.from_result),
-
-  ("clang_CompileCommands_dispose",
-   [c_object_p]),
-
-  ("clang_CompileCommands_getCommand",
-   [c_object_p, c_uint],
-   c_object_p),
-
-  ("clang_CompileCommands_getSize",
-   [c_object_p],
-   c_uint),
-
-  ("clang_CompileCommand_getArg",
-   [c_object_p, c_uint],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_CompileCommand_getDirectory",
-   [c_object_p],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_CompileCommand_getNumArgs",
-   [c_object_p],
-   c_uint),
-
-  ("clang_codeCompleteAt",
-   [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int],
-   POINTER(CCRStructure)),
-
-  ("clang_codeCompleteGetDiagnostic",
-   [CodeCompletionResults, c_int],
-   Diagnostic),
-
-  ("clang_codeCompleteGetNumDiagnostics",
-   [CodeCompletionResults],
-   c_int),
-
-  ("clang_createIndex",
-   [c_int, c_int],
-   c_object_p),
-
-  ("clang_createTranslationUnit",
-   [Index, c_char_p],
-   c_object_p),
-
-  ("clang_CXXField_isMutable",
-   [Cursor],
-   bool),
-
-  ("clang_CXXMethod_isConst",
-   [Cursor],
-   bool),
-
-  ("clang_CXXMethod_isPureVirtual",
-   [Cursor],
-   bool),
-
-  ("clang_CXXMethod_isStatic",
-   [Cursor],
-   bool),
-
-  ("clang_CXXMethod_isVirtual",
-   [Cursor],
-   bool),
-
-  ("clang_defaultSaveOptions",
-   [TranslationUnit],
-   c_uint),
-
-  ("clang_disposeCodeCompleteResults",
-   [CodeCompletionResults]),
-
-# ("clang_disposeCXTUResourceUsage",
-#  [CXTUResourceUsage]),
-
-  ("clang_disposeDiagnostic",
-   [Diagnostic]),
-
-  ("clang_disposeIndex",
-   [Index]),
-
-  ("clang_disposeString",
-   [_CXString]),
-
-  ("clang_disposeTokens",
-   [TranslationUnit, POINTER(Token), c_uint]),
-
-  ("clang_disposeTranslationUnit",
-   [TranslationUnit]),
-
-  ("clang_equalCursors",
-   [Cursor, Cursor],
-   bool),
-
-  ("clang_equalLocations",
-   [SourceLocation, SourceLocation],
-   bool),
-
-  ("clang_equalRanges",
-   [SourceRange, SourceRange],
-   bool),
-
-  ("clang_equalTypes",
-   [Type, Type],
-   bool),
-
-  ("clang_getArgType",
-   [Type, c_uint],
-   Type,
-   Type.from_result),
-
-  ("clang_getArrayElementType",
-   [Type],
-   Type,
-   Type.from_result),
-
-  ("clang_getArraySize",
-   [Type],
-   c_longlong),
-
-  ("clang_getFieldDeclBitWidth",
-   [Cursor],
-   c_int),
-
-  ("clang_getCanonicalCursor",
-   [Cursor],
-   Cursor,
-   Cursor.from_cursor_result),
-
-  ("clang_getCanonicalType",
-   [Type],
-   Type,
-   Type.from_result),
-
-  ("clang_getCompletionAvailability",
-   [c_void_p],
-   c_int),
-
-  ("clang_getCompletionBriefComment",
-   [c_void_p],
-   _CXString),
-
-  ("clang_getCompletionChunkCompletionString",
-   [c_void_p, c_int],
-   c_object_p),
-
-  ("clang_getCompletionChunkKind",
-   [c_void_p, c_int],
-   c_int),
-
-  ("clang_getCompletionChunkText",
-   [c_void_p, c_int],
-   _CXString),
-
-  ("clang_getCompletionPriority",
-   [c_void_p],
-   c_int),
-
-  ("clang_getCString",
-   [_CXString],
-   c_char_p),
-
-  ("clang_getCursor",
-   [TranslationUnit, SourceLocation],
-   Cursor),
-
-  ("clang_getCursorDefinition",
-   [Cursor],
-   Cursor,
-   Cursor.from_result),
-
-  ("clang_getCursorDisplayName",
-   [Cursor],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getCursorExtent",
-   [Cursor],
-   SourceRange),
-
-  ("clang_getCursorLexicalParent",
-   [Cursor],
-   Cursor,
-   Cursor.from_cursor_result),
-
-  ("clang_getCursorLocation",
-   [Cursor],
-   SourceLocation),
-
-  ("clang_getCursorReferenced",
-   [Cursor],
-   Cursor,
-   Cursor.from_result),
-
-  ("clang_getCursorReferenceNameRange",
-   [Cursor, c_uint, c_uint],
-   SourceRange),
-
-  ("clang_getCursorSemanticParent",
-   [Cursor],
-   Cursor,
-   Cursor.from_cursor_result),
-
-  ("clang_getCursorSpelling",
-   [Cursor],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getCursorType",
-   [Cursor],
-   Type,
-   Type.from_result),
-
-  ("clang_getCursorUSR",
-   [Cursor],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_Cursor_getMangling",
-   [Cursor],
-   _CXString,
-   _CXString.from_result),
-
-# ("clang_getCXTUResourceUsage",
-#  [TranslationUnit],
-#  CXTUResourceUsage),
-
-  ("clang_getCXXAccessSpecifier",
-   [Cursor],
-   c_uint),
-
-  ("clang_getDeclObjCTypeEncoding",
-   [Cursor],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getDiagnostic",
-   [c_object_p, c_uint],
-   c_object_p),
-
-  ("clang_getDiagnosticCategory",
-   [Diagnostic],
-   c_uint),
-
-  ("clang_getDiagnosticCategoryText",
-   [Diagnostic],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getDiagnosticFixIt",
-   [Diagnostic, c_uint, POINTER(SourceRange)],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getDiagnosticLocation",
-   [Diagnostic],
-   SourceLocation),
-
-  ("clang_getDiagnosticNumFixIts",
-   [Diagnostic],
-   c_uint),
-
-  ("clang_getDiagnosticNumRanges",
-   [Diagnostic],
-   c_uint),
-
-  ("clang_getDiagnosticOption",
-   [Diagnostic, POINTER(_CXString)],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getDiagnosticRange",
-   [Diagnostic, c_uint],
-   SourceRange),
-
-  ("clang_getDiagnosticSeverity",
-   [Diagnostic],
-   c_int),
-
-  ("clang_getDiagnosticSpelling",
-   [Diagnostic],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getElementType",
-   [Type],
-   Type,
-   Type.from_result),
-
-  ("clang_getEnumConstantDeclUnsignedValue",
-   [Cursor],
-   c_ulonglong),
-
-  ("clang_getEnumConstantDeclValue",
-   [Cursor],
-   c_longlong),
-
-  ("clang_getEnumDeclIntegerType",
-   [Cursor],
-   Type,
-   Type.from_result),
-
-  ("clang_getFile",
-   [TranslationUnit, c_char_p],
-   c_object_p),
-
-  ("clang_getFileName",
-   [File],
-   _CXString), # TODO go through _CXString.from_result?
-
-  ("clang_getFileTime",
-   [File],
-   c_uint),
-
-  ("clang_getIBOutletCollectionType",
-   [Cursor],
-   Type,
-   Type.from_result),
-
-  ("clang_getIncludedFile",
-   [Cursor],
-   File,
-   File.from_cursor_result),
-
-  ("clang_getInclusions",
-   [TranslationUnit, callbacks['translation_unit_includes'], py_object]),
-
-  ("clang_getInstantiationLocation",
-   [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint),
-    POINTER(c_uint)]),
-
-  ("clang_getLocation",
-   [TranslationUnit, File, c_uint, c_uint],
-   SourceLocation),
-
-  ("clang_getLocationForOffset",
-   [TranslationUnit, File, c_uint],
-   SourceLocation),
-
-  ("clang_getNullCursor",
-   None,
-   Cursor),
-
-  ("clang_getNumArgTypes",
-   [Type],
-   c_uint),
-
-  ("clang_getNumCompletionChunks",
-   [c_void_p],
-   c_int),
-
-  ("clang_getNumDiagnostics",
-   [c_object_p],
-   c_uint),
-
-  ("clang_getNumElements",
-   [Type],
-   c_longlong),
-
-  ("clang_getNumOverloadedDecls",
-   [Cursor],
-   c_uint),
-
-  ("clang_getOverloadedDecl",
-   [Cursor, c_uint],
-   Cursor,
-   Cursor.from_cursor_result),
-
-  ("clang_getPointeeType",
-   [Type],
-   Type,
-   Type.from_result),
-
-  ("clang_getRange",
-   [SourceLocation, SourceLocation],
-   SourceRange),
-
-  ("clang_getRangeEnd",
-   [SourceRange],
-   SourceLocation),
-
-  ("clang_getRangeStart",
-   [SourceRange],
-   SourceLocation),
-
-  ("clang_getResultType",
-   [Type],
-   Type,
-   Type.from_result),
-
-  ("clang_getSpecializedCursorTemplate",
-   [Cursor],
-   Cursor,
-   Cursor.from_cursor_result),
-
-  ("clang_getTemplateCursorKind",
-   [Cursor],
-   c_uint),
-
-  ("clang_getTokenExtent",
-   [TranslationUnit, Token],
-   SourceRange),
-
-  ("clang_getTokenKind",
-   [Token],
-   c_uint),
-
-  ("clang_getTokenLocation",
-   [TranslationUnit, Token],
-   SourceLocation),
-
-  ("clang_getTokenSpelling",
-   [TranslationUnit, Token],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getTranslationUnitCursor",
-   [TranslationUnit],
-   Cursor,
-   Cursor.from_result),
-
-  ("clang_getTranslationUnitSpelling",
-   [TranslationUnit],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getTUResourceUsageName",
-   [c_uint],
-   c_char_p),
-
-  ("clang_getTypeDeclaration",
-   [Type],
-   Cursor,
-   Cursor.from_result),
-
-  ("clang_getTypedefDeclUnderlyingType",
-   [Cursor],
-   Type,
-   Type.from_result),
-
-  ("clang_getTypeKindSpelling",
-   [c_uint],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_getTypeSpelling",
-   [Type],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_hashCursor",
-   [Cursor],
-   c_uint),
-
-  ("clang_isAttribute",
-   [CursorKind],
-   bool),
-
-  ("clang_isConstQualifiedType",
-   [Type],
-   bool),
-
-  ("clang_isCursorDefinition",
-   [Cursor],
-   bool),
-
-  ("clang_isDeclaration",
-   [CursorKind],
-   bool),
-
-  ("clang_isExpression",
-   [CursorKind],
-   bool),
-
-  ("clang_isFileMultipleIncludeGuarded",
-   [TranslationUnit, File],
-   bool),
-
-  ("clang_isFunctionTypeVariadic",
-   [Type],
-   bool),
-
-  ("clang_isInvalid",
-   [CursorKind],
-   bool),
-
-  ("clang_isPODType",
-   [Type],
-   bool),
-
-  ("clang_isPreprocessing",
-   [CursorKind],
-   bool),
-
-  ("clang_isReference",
-   [CursorKind],
-   bool),
-
-  ("clang_isRestrictQualifiedType",
-   [Type],
-   bool),
-
-  ("clang_isStatement",
-   [CursorKind],
-   bool),
-
-  ("clang_isTranslationUnit",
-   [CursorKind],
-   bool),
-
-  ("clang_isUnexposed",
-   [CursorKind],
-   bool),
-
-  ("clang_isVirtualBase",
-   [Cursor],
-   bool),
-
-  ("clang_isVolatileQualifiedType",
-   [Type],
-   bool),
-
-  ("clang_parseTranslationUnit",
-   [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int],
-   c_object_p),
-
-  ("clang_reparseTranslationUnit",
-   [TranslationUnit, c_int, c_void_p, c_int],
-   c_int),
-
-  ("clang_saveTranslationUnit",
-   [TranslationUnit, c_char_p, c_uint],
-   c_int),
-
-  ("clang_tokenize",
-   [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]),
-
-  ("clang_visitChildren",
-   [Cursor, callbacks['cursor_visit'], py_object],
-   c_uint),
-
-  ("clang_Cursor_getNumArguments",
-   [Cursor],
-   c_int),
-
-  ("clang_Cursor_getArgument",
-   [Cursor, c_uint],
-   Cursor,
-   Cursor.from_result),
-
-  ("clang_Cursor_getNumTemplateArguments",
-   [Cursor],
-   c_int),
-
-  ("clang_Cursor_getTemplateArgumentKind",
-   [Cursor, c_uint],
-   TemplateArgumentKind.from_id),
-
-  ("clang_Cursor_getTemplateArgumentType",
-   [Cursor, c_uint],
-   Type,
-   Type.from_result),
-
-  ("clang_Cursor_getTemplateArgumentValue",
-   [Cursor, c_uint],
-   c_longlong),
-
-  ("clang_Cursor_getTemplateArgumentUnsignedValue",
-   [Cursor, c_uint],
-   c_ulonglong),
-
-  ("clang_Cursor_isAnonymous",
-   [Cursor],
-   bool),
-
-  ("clang_Cursor_isBitField",
-   [Cursor],
-   bool),
-
-  ("clang_Cursor_getBriefCommentText",
-   [Cursor],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_Cursor_getRawCommentText",
-   [Cursor],
-   _CXString,
-   _CXString.from_result),
-
-  ("clang_Cursor_getOffsetOfField",
-   [Cursor],
-   c_longlong),
-
-  ("clang_Type_getAlignOf",
-   [Type],
-   c_longlong),
-
-  ("clang_Type_getClassType",
-   [Type],
-   Type,
-   Type.from_result),
-
-  ("clang_Type_getOffsetOf",
-   [Type, c_char_p],
-   c_longlong),
-
-  ("clang_Type_getSizeOf",
-   [Type],
-   c_longlong),
-
-  ("clang_Type_getCXXRefQualifier",
-   [Type],
-   c_uint),
-
-  ("clang_Type_visitFields",
-   [Type, callbacks['fields_visit'], py_object],
-   c_uint),
+    (
+        "clang_annotateTokens",
+        [TranslationUnit, POINTER(Token), c_uint, POINTER(Cursor)]
+    ),
+    (
+        "clang_CompilationDatabase_dispose",
+        [c_object_p]
+    ),
+    (
+        "clang_CompilationDatabase_fromDirectory",
+        [c_char_p, POINTER(c_uint)],
+        c_object_p,
+        CompilationDatabase.from_result
+    ),
+    (
+        "clang_CompilationDatabase_getAllCompileCommands",
+        [c_object_p],
+        c_object_p,
+        CompileCommands.from_result
+    ),
+    (
+        "clang_CompilationDatabase_getCompileCommands",
+        [c_object_p, c_char_p],
+        c_object_p,
+        CompileCommands.from_result
+    ),
+    (
+        "clang_CompileCommands_dispose",
+        [c_object_p]
+    ),
+    (
+        "clang_CompileCommands_getCommand",
+        [c_object_p, c_uint],
+        c_object_p
+    ),
+    (
+        "clang_CompileCommands_getSize",
+        [c_object_p],
+        c_uint
+    ),
+    (
+        "clang_CompileCommand_getArg",
+        [c_object_p, c_uint],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_CompileCommand_getDirectory",
+        [c_object_p],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_CompileCommand_getNumArgs",
+        [c_object_p],
+        c_uint
+    ),
+    (
+        "clang_codeCompleteAt",
+        [TranslationUnit, c_char_p, c_int, c_int, c_void_p, c_int, c_int],
+        POINTER(CCRStructure)
+    ),
+    (
+        "clang_codeCompleteGetDiagnostic",
+        [CodeCompletionResults, c_int],
+        Diagnostic
+    ),
+    (
+        "clang_codeCompleteGetNumDiagnostics",
+        [CodeCompletionResults],
+        c_int
+    ),
+    (
+        "clang_createIndex",
+        [c_int, c_int],
+        c_object_p
+    ),
+    (
+        "clang_createTranslationUnit",
+        [Index, c_char_p],
+        c_object_p
+    ),
+    (
+        "clang_CXXField_isMutable",
+        [Cursor],
+        bool
+    ),
+    (
+        "clang_CXXMethod_isConst",
+        [Cursor],
+        bool
+    ),
+    (
+        "clang_CXXMethod_isPureVirtual",
+        [Cursor],
+        bool
+    ),
+    (
+        "clang_CXXMethod_isStatic",
+        [Cursor],
+        bool
+    ),
+    (
+        "clang_CXXMethod_isVirtual",
+        [Cursor],
+        bool
+    ),
+    (
+        "clang_defaultSaveOptions",
+        [TranslationUnit],
+        c_uint
+    ),
+    (
+        "clang_disposeCodeCompleteResults",
+        [CodeCompletionResults]
+    ),
+    # (
+    #     "clang_disposeCXTUResourceUsage",
+    #     [CXTUResourceUsage]
+    # ),
+    (
+        "clang_disposeDiagnostic",
+        [Diagnostic]
+    ),
+    (
+        "clang_disposeIndex",
+        [Index]
+    ),
+    (
+        "clang_disposeString",
+        [_CXString]
+    ),
+    (
+        "clang_disposeTokens",
+        [TranslationUnit, POINTER(Token), c_uint]
+    ),
+    (
+        "clang_disposeTranslationUnit",
+        [TranslationUnit]
+    ),
+    (
+        "clang_equalCursors",
+        [Cursor, Cursor],
+        bool
+    ),
+    (
+        "clang_equalLocations",
+        [SourceLocation, SourceLocation],
+        bool
+    ),
+    (
+        "clang_equalRanges",
+        [SourceRange, SourceRange],
+        bool
+    ),
+    (
+        "clang_equalTypes",
+        [Type, Type],
+        bool
+    ),
+    (
+        "clang_getArgType",
+        [Type, c_uint],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getArrayElementType",
+        [Type],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getArraySize",
+        [Type],
+        c_longlong
+    ),
+    (
+        "clang_getFieldDeclBitWidth",
+        [Cursor],
+        c_int
+    ),
+    (
+        "clang_getCanonicalCursor",
+        [Cursor],
+        Cursor,
+        Cursor.from_cursor_result
+    ),
+    (
+        "clang_getCanonicalType",
+        [Type],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getCompletionAvailability",
+        [c_void_p],
+        c_int
+    ),
+    (
+        "clang_getCompletionBriefComment",
+        [c_void_p],
+        _CXString
+    ),
+    (
+        "clang_getCompletionChunkCompletionString",
+        [c_void_p, c_int],
+        c_object_p
+    ),
+    (
+        "clang_getCompletionChunkKind",
+        [c_void_p, c_int],
+        c_int
+    ),
+    (
+        "clang_getCompletionChunkText",
+        [c_void_p, c_int],
+        _CXString
+    ),
+    (
+        "clang_getCompletionPriority",
+        [c_void_p],
+        c_int
+    ),
+    (
+        "clang_getCString",
+        [_CXString],
+        c_char_p
+    ),
+    (
+        "clang_getCursor",
+        [TranslationUnit, SourceLocation],
+        Cursor
+    ),
+    (
+        "clang_getCursorDefinition",
+        [Cursor],
+        Cursor,
+        Cursor.from_result
+    ),
+    (
+        "clang_getCursorDisplayName",
+        [Cursor],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getCursorExtent",
+        [Cursor],
+        SourceRange
+    ),
+    (
+        "clang_getCursorLexicalParent",
+        [Cursor],
+        Cursor,
+        Cursor.from_cursor_result
+    ),
+    (
+        "clang_getCursorLocation",
+        [Cursor],
+        SourceLocation
+    ),
+    (
+        "clang_getCursorReferenced",
+        [Cursor],
+        Cursor,
+        Cursor.from_result
+    ),
+    (
+        "clang_getCursorReferenceNameRange",
+        [Cursor, c_uint, c_uint],
+        SourceRange
+    ),
+    (
+        "clang_getCursorSemanticParent",
+        [Cursor],
+        Cursor,
+        Cursor.from_cursor_result
+    ),
+    (
+        "clang_getCursorSpelling",
+        [Cursor],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getCursorType",
+        [Cursor],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getCursorUSR",
+        [Cursor],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_Cursor_getMangling",
+        [Cursor],
+        _CXString,
+        _CXString.from_result
+    ),
+    # (
+    #     "clang_getCXTUResourceUsage",
+    #     [TranslationUnit],
+    #     CXTUResourceUsage
+    # ),
+    (
+        "clang_getCXXAccessSpecifier",
+        [Cursor],
+        c_uint
+    ),
+    (
+        "clang_getDeclObjCTypeEncoding",
+        [Cursor],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getDiagnostic",
+        [c_object_p, c_uint],
+        c_object_p
+    ),
+    (
+        "clang_getDiagnosticCategory",
+        [Diagnostic],
+        c_uint
+    ),
+    (
+        "clang_getDiagnosticCategoryText",
+        [Diagnostic],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getDiagnosticFixIt",
+        [Diagnostic, c_uint, POINTER(SourceRange)],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getDiagnosticLocation",
+        [Diagnostic],
+        SourceLocation
+    ),
+    (
+        "clang_getDiagnosticNumFixIts",
+        [Diagnostic],
+        c_uint
+    ),
+    (
+        "clang_getDiagnosticNumRanges",
+        [Diagnostic],
+        c_uint
+    ),
+    (
+        "clang_getDiagnosticOption",
+        [Diagnostic, POINTER(_CXString)],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getDiagnosticRange",
+        [Diagnostic, c_uint],
+        SourceRange
+    ),
+    (
+        "clang_getDiagnosticSeverity",
+        [Diagnostic],
+        c_int
+    ),
+    (
+        "clang_getDiagnosticSpelling",
+        [Diagnostic],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getElementType",
+        [Type],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getEnumConstantDeclUnsignedValue",
+        [Cursor],
+        c_ulonglong
+    ),
+    (
+        "clang_getEnumConstantDeclValue",
+        [Cursor],
+        c_longlong
+    ),
+    (
+        "clang_getEnumDeclIntegerType",
+        [Cursor],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getFile",
+        [TranslationUnit, c_char_p],
+        c_object_p
+    ),
+    (
+        "clang_getFileName",
+        [File],
+        _CXString  # TODO go through _CXString.from_result?
+    ),
+    (
+        "clang_getFileTime",
+        [File],
+        c_uint
+    ),
+    (
+        "clang_getIBOutletCollectionType",
+        [Cursor],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getIncludedFile",
+        [Cursor],
+        File,
+        File.from_cursor_result
+    ),
+    (
+        "clang_getInclusions",
+        [TranslationUnit, callbacks['translation_unit_includes'], py_object]
+    ),
+    (
+        "clang_getInstantiationLocation",
+        [SourceLocation, POINTER(c_object_p), POINTER(c_uint), POINTER(c_uint), POINTER(c_uint)]
+    ),
+    (
+        "clang_getLocation",
+        [TranslationUnit, File, c_uint, c_uint],
+        SourceLocation
+    ),
+    (
+        "clang_getLocationForOffset",
+        [TranslationUnit, File, c_uint],
+        SourceLocation
+    ),
+    (
+        "clang_getNullCursor",
+        None,
+        Cursor
+    ),
+    (
+        "clang_getNumArgTypes",
+        [Type],
+        c_uint
+    ),
+    (
+        "clang_getNumCompletionChunks",
+        [c_void_p],
+        c_int
+    ),
+    (
+        "clang_getNumDiagnostics",
+        [c_object_p],
+        c_uint
+    ),
+    (
+        "clang_getNumElements",
+        [Type],
+        c_longlong
+    ),
+    (
+        "clang_getNumOverloadedDecls",
+        [Cursor],
+        c_uint
+    ),
+    (
+        "clang_getOverloadedDecl",
+        [Cursor, c_uint],
+        Cursor,
+        Cursor.from_cursor_result
+    ),
+    (
+        "clang_getPointeeType",
+        [Type],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getRange",
+        [SourceLocation, SourceLocation],
+        SourceRange
+    ),
+    (
+        "clang_getRangeEnd",
+        [SourceRange],
+        SourceLocation
+    ),
+    (
+        "clang_getRangeStart",
+        [SourceRange],
+        SourceLocation
+    ),
+    (
+        "clang_getResultType",
+        [Type],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getSpecializedCursorTemplate",
+        [Cursor],
+        Cursor,
+        Cursor.from_cursor_result
+    ),
+    (
+        "clang_getTemplateCursorKind",
+        [Cursor],
+        c_uint
+    ),
+    (
+        "clang_getTokenExtent",
+        [TranslationUnit, Token],
+        SourceRange
+    ),
+    (
+        "clang_getTokenKind",
+        [Token],
+        c_uint
+    ),
+    (
+        "clang_getTokenLocation",
+        [TranslationUnit, Token],
+        SourceLocation
+    ),
+    (
+        "clang_getTokenSpelling",
+        [TranslationUnit, Token],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getTranslationUnitCursor",
+        [TranslationUnit],
+        Cursor,
+        Cursor.from_result
+    ),
+    (
+        "clang_getTranslationUnitSpelling",
+        [TranslationUnit],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getTUResourceUsageName",
+        [c_uint],
+        c_char_p
+    ),
+    (
+        "clang_getTypeDeclaration",
+        [Type],
+        Cursor,
+        Cursor.from_result
+    ),
+    (
+        "clang_getTypedefDeclUnderlyingType",
+        [Cursor],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_getTypeKindSpelling",
+        [c_uint],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_getTypeSpelling",
+        [Type],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_hashCursor",
+        [Cursor],
+        c_uint
+    ),
+    (
+        "clang_isAttribute",
+        [CursorKind],
+        bool
+    ),
+    (
+        "clang_isConstQualifiedType",
+        [Type],
+        bool
+    ),
+    (
+        "clang_isCursorDefinition",
+        [Cursor],
+        bool
+    ),
+    (
+        "clang_isDeclaration",
+        [CursorKind],
+        bool
+    ),
+    (
+        "clang_isExpression",
+        [CursorKind],
+        bool
+    ),
+    (
+        "clang_isFileMultipleIncludeGuarded",
+        [TranslationUnit, File],
+        bool
+    ),
+    (
+        "clang_isFunctionTypeVariadic",
+        [Type],
+        bool
+    ),
+    (
+        "clang_isInvalid",
+        [CursorKind],
+        bool
+    ),
+    (
+        "clang_isPODType",
+        [Type],
+        bool
+    ),
+    (
+        "clang_isPreprocessing",
+        [CursorKind],
+        bool
+    ),
+    (
+        "clang_isReference",
+        [CursorKind],
+        bool
+    ),
+    (
+        "clang_isRestrictQualifiedType",
+        [Type],
+        bool
+    ),
+    (
+        "clang_isStatement",
+        [CursorKind],
+        bool
+    ),
+    (
+        "clang_isTranslationUnit",
+        [CursorKind],
+        bool
+    ),
+    (
+        "clang_isUnexposed",
+        [CursorKind],
+        bool
+    ),
+    (
+        "clang_isVirtualBase",
+        [Cursor],
+        bool
+    ),
+    (
+        "clang_isVolatileQualifiedType",
+        [Type],
+        bool
+    ),
+    (
+        "clang_parseTranslationUnit",
+        [Index, c_char_p, c_void_p, c_int, c_void_p, c_int, c_int],
+        c_object_p
+    ),
+    (
+        "clang_reparseTranslationUnit",
+        [TranslationUnit, c_int, c_void_p, c_int],
+        c_int
+    ),
+    (
+        "clang_saveTranslationUnit",
+        [TranslationUnit, c_char_p, c_uint],
+        c_int
+    ),
+    (
+        "clang_tokenize",
+        [TranslationUnit, SourceRange, POINTER(POINTER(Token)), POINTER(c_uint)]
+    ),
+    (
+        "clang_visitChildren",
+        [Cursor, callbacks['cursor_visit'], py_object],
+        c_uint
+    ),
+    (
+        "clang_Cursor_getNumArguments",
+        [Cursor],
+        c_int
+    ),
+    (
+        "clang_Cursor_getArgument",
+        [Cursor, c_uint],
+        Cursor,
+        Cursor.from_result
+    ),
+    (
+        "clang_Cursor_getNumTemplateArguments",
+        [Cursor],
+        c_int
+    ),
+    (
+        "clang_Cursor_getTemplateArgumentKind",
+        [Cursor, c_uint],
+        TemplateArgumentKind.from_id
+    ),
+    (
+        "clang_Cursor_getTemplateArgumentType",
+        [Cursor, c_uint],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_Cursor_getTemplateArgumentValue",
+        [Cursor, c_uint],
+        c_longlong
+    ),
+    (
+        "clang_Cursor_getTemplateArgumentUnsignedValue",
+        [Cursor, c_uint],
+        c_ulonglong
+    ),
+    (
+        "clang_Cursor_isAnonymous",
+        [Cursor],
+        bool
+    ),
+    (
+        "clang_Cursor_isBitField",
+        [Cursor],
+        bool
+    ),
+    (
+        "clang_Cursor_getBriefCommentText",
+        [Cursor],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_Cursor_getRawCommentText",
+        [Cursor],
+        _CXString,
+        _CXString.from_result
+    ),
+    (
+        "clang_Cursor_getOffsetOfField",
+        [Cursor],
+        c_longlong
+    ),
+    (
+        "clang_Type_getAlignOf",
+        [Type],
+        c_longlong
+    ),
+    (
+        "clang_Type_getClassType",
+        [Type],
+        Type,
+        Type.from_result
+    ),
+    (
+        "clang_Type_getOffsetOf",
+        [Type, c_char_p],
+        c_longlong
+    ),
+    (
+        "clang_Type_getSizeOf",
+        [Type],
+        c_longlong
+    ),
+    (
+        "clang_Type_getCXXRefQualifier",
+        [Type],
+        c_uint
+    ),
+    (
+        "clang_Type_visitFields",
+        [Type, callbacks['fields_visit'], py_object],
+        c_uint
+    ),
 ]
 
+
 class LibclangError(Exception):
     def __init__(self, message):
         self.m = message
@@ -3489,6 +3684,7 @@ class LibclangError(Exception):
     def __str__(self):
         return self.m
 
+
 def register_function(lib, item, ignore_errors):
     # A function may not exist, if these bindings are used with an older or
     # incompatible version of libclang.so.
@@ -3510,6 +3706,7 @@ def register_function(lib, item, ignore_errors):
     if len(item) == 4:
         func.errcheck = item[3]
 
+
 def register_functions(lib, ignore_errors):
     """Register function prototypes with a libclang library instance.
 
@@ -3520,7 +3717,13 @@ def register_functions(lib, ignore_errors):
     def register(item):
         return register_function(lib, item, ignore_errors)
 
-    map(register, functionList)
+    for f in functionList:
+        try:
+            register(f)
+        except LibclangError:
+            # If the symbol doesn't exist, don't panic.
+            pass
+
 
 class Config:
     library_path = None
@@ -3532,7 +3735,7 @@ class Config:
     def set_library_path(path):
         """Set the path in which to search for libclang"""
         if Config.loaded:
-            raise Exception("library path must be set before before using " \
+            raise Exception("library path must be set before before using "
                             "any other functionalities in libclang.")
 
         Config.library_path = path
@@ -3541,7 +3744,7 @@ class Config:
     def set_library_file(filename):
         """Set the exact location of libclang"""
         if Config.loaded:
-            raise Exception("library file must be set before before using " \
+            raise Exception("library file must be set before before using "
                             "any other functionalities in libclang.")
 
         Config.library_file = filename
@@ -3565,7 +3768,7 @@ class Config:
         libclang versions.
         """
         if Config.loaded:
-            raise Exception("compatibility_check must be set before before " \
+            raise Exception("compatibility_check must be set before before "
                             "using any other functionalities in libclang.")
 
         Config.compatibility_check = check_status
@@ -3615,6 +3818,7 @@ class Config:
 
         return True
 
+
 def register_enumerations():
     for name, value in clang.enumerations.TokenKinds:
         TokenKind.register(value, name)
diff --git a/bindings/python/setup.py b/bindings/python/setup.py
new file mode 100644
index 0000000..849623f
--- /dev/null
+++ b/bindings/python/setup.py
@@ -0,0 +1,34 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+
+from setuptools import setup
+
+setup(
+    name="clang",
+    version="3.7.dev257739",
+    description="libclang python bindings",
+    long_description=open("README.txt").read(),
+    url="http://clang.llvm.org/",
+    download_url="http://llvm.org/releases/download.html",
+    license="License :: OSI Approved :: University of Illinois/NCSA Open Source License",
+    classifiers=[
+        "Intended Audience :: Developers",
+        "License :: OSI Approved ::  University of Illinois/NCSA Open Source License",
+        "Programming Language :: Python",
+        "Development Status :: 5 - Production/Stable",
+        "Topic :: Software Development :: Compilers"
+        'Programming Language :: Python :: 3',
+        'Programming Language :: Python :: 3.4',
+        'Programming Language :: Python :: 3.5',
+        'Programming Language :: Python :: 2',
+        'Programming Language :: Python :: 2.7',
+    ],
+    keywords=["llvm", "clang", "libclang"],
+    author="LLVM team",
+    zip_safe=False,
+    packages=["clang"],
+    # if use nose.collector, many plugins not is avaliable
+    # see: http://nose.readthedocs.org/en/latest/setuptools_integration.html
+    test_suite="nose.collector",
+    tests_require=['nose']
+)
diff --git a/bindings/python/tests/cindex/test_access_specifiers.py b/bindings/python/tests/cindex/test_access_specifiers.py
index cfa04dc..df7816a 100644
--- a/bindings/python/tests/cindex/test_access_specifiers.py
+++ b/bindings/python/tests/cindex/test_access_specifiers.py
@@ -1,11 +1,10 @@
 
 from clang.cindex import AccessSpecifier
-from clang.cindex import Cursor
-from clang.cindex import TranslationUnit
 
 from .util import get_cursor
 from .util import get_tu
 
+
 def test_access_specifiers():
     """Ensure that C++ access specifiers are available on cursors"""
 
@@ -18,10 +17,10 @@ protected:
 private:
   void private_member_function();
 };
-""", lang = 'cpp')
+""", lang='cpp')
 
     test_class = get_cursor(tu, "test_class")
-    assert test_class.access_specifier == AccessSpecifier.INVALID;
+    assert test_class.access_specifier == AccessSpecifier.INVALID
 
     public = get_cursor(tu.cursor, "public_member_function")
     assert public.access_specifier == AccessSpecifier.PUBLIC
@@ -31,4 +30,3 @@ private:
 
     private = get_cursor(tu.cursor, "private_member_function")
     assert private.access_specifier == AccessSpecifier.PRIVATE
-
diff --git a/bindings/python/tests/cindex/test_cdb.py b/bindings/python/tests/cindex/test_cdb.py
index e1f824f..2d47229 100644
--- a/bindings/python/tests/cindex/test_cdb.py
+++ b/bindings/python/tests/cindex/test_cdb.py
@@ -1,30 +1,34 @@
+from __future__ import unicode_literals
+
 from clang.cindex import CompilationDatabase
 from clang.cindex import CompilationDatabaseError
-from clang.cindex import CompileCommands
-from clang.cindex import CompileCommand
 import os
 import gc
 
 kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
 
+
 def test_create_fail():
     """Check we fail loading a database with an assertion"""
     path = os.path.dirname(__file__)
     try:
-      cdb = CompilationDatabase.fromDirectory(path)
+        CompilationDatabase.fromDirectory(path)
     except CompilationDatabaseError as e:
-      assert e.cdb_error == CompilationDatabaseError.ERROR_CANNOTLOADDATABASE
+        assert e.cdb_error == CompilationDatabaseError.ERROR_CANNOTLOADDATABASE
     else:
-      assert False
+        assert False
+
 
 def test_create():
     """Check we can load a compilation database"""
-    cdb = CompilationDatabase.fromDirectory(kInputsDir)
+    CompilationDatabase.fromDirectory(kInputsDir)
+
 
 def test_lookup_fail():
     """Check file lookup failure"""
     cdb = CompilationDatabase.fromDirectory(kInputsDir)
-    assert cdb.getCompileCommands('file_do_not_exist.cpp') == None
+    assert cdb.getCompileCommands('file_do_not_exist.cpp') is None
+
 
 def test_lookup_succeed():
     """Check we get some results if the file exists in the db"""
@@ -32,56 +36,91 @@ def test_lookup_succeed():
     cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp')
     assert len(cmds) != 0
 
+
 def test_all_compilecommand():
     """Check we get all results from the db"""
     cdb = CompilationDatabase.fromDirectory(kInputsDir)
     cmds = cdb.getAllCompileCommands()
     assert len(cmds) == 3
     expected = [
-        { 'wd': '/home/john.doe/MyProjectA',
-          'line': ['clang++', '-o', 'project2.o', '-c',
-                   '/home/john.doe/MyProject/project2.cpp']},
-        { 'wd': '/home/john.doe/MyProjectB',
-          'line': ['clang++', '-DFEATURE=1', '-o', 'project2-feature.o', '-c',
-                   '/home/john.doe/MyProject/project2.cpp']},
-        { 'wd': '/home/john.doe/MyProject',
-          'line': ['clang++', '-o', 'project.o', '-c',
-                   '/home/john.doe/MyProject/project.cpp']}
-        ]
+        {
+            'wd': b'/home/john.doe/MyProjectA',
+            'line': [
+                b'clang++',
+                b'-o', b'project2.o',
+                b'-c', b'/home/john.doe/MyProject/project2.cpp'
+            ]
+        },
+        {
+            'wd': b'/home/john.doe/MyProjectB',
+            'line': [
+                b'clang++',
+                b'-DFEATURE=1',
+                b'-o', b'project2-feature.o',
+                b'-c', b'/home/john.doe/MyProject/project2.cpp'
+            ]
+        },
+        {
+            'wd': b'/home/john.doe/MyProject',
+            'line': [
+                b'clang++',
+                b'-o', b'project.o',
+                b'-c', b'/home/john.doe/MyProject/project.cpp'
+            ]
+        }
+    ]
+
     for i in range(len(cmds)):
         assert cmds[i].directory == expected[i]['wd']
         for arg, exp in zip(cmds[i].arguments, expected[i]['line']):
             assert arg == exp
 
+
 def test_1_compilecommand():
     """Check file with single compile command"""
     cdb = CompilationDatabase.fromDirectory(kInputsDir)
     cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp')
     assert len(cmds) == 1
-    assert cmds[0].directory == '/home/john.doe/MyProject'
-    expected = [ 'clang++', '-o', 'project.o', '-c',
-                 '/home/john.doe/MyProject/project.cpp']
+    assert cmds[0].directory == b'/home/john.doe/MyProject'
+    expected = [
+        b'clang++',
+        b'-o', b'project.o',
+        b'-c', b'/home/john.doe/MyProject/project.cpp'
+    ]
     for arg, exp in zip(cmds[0].arguments, expected):
         assert arg == exp
 
+
 def test_2_compilecommand():
     """Check file with 2 compile commands"""
     cdb = CompilationDatabase.fromDirectory(kInputsDir)
     cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project2.cpp')
     assert len(cmds) == 2
     expected = [
-        { 'wd': '/home/john.doe/MyProjectA',
-          'line': ['clang++', '-o', 'project2.o', '-c',
-                   '/home/john.doe/MyProject/project2.cpp']},
-        { 'wd': '/home/john.doe/MyProjectB',
-          'line': ['clang++', '-DFEATURE=1', '-o', 'project2-feature.o', '-c',
-                   '/home/john.doe/MyProject/project2.cpp']}
-        ]
+        {
+            'wd': b'/home/john.doe/MyProjectA',
+            'line': [
+                b'clang++',
+                b'-o', b'project2.o',
+                b'-c', b'/home/john.doe/MyProject/project2.cpp'
+            ]
+        },
+        {
+            'wd': b'/home/john.doe/MyProjectB',
+            'line': [
+                b'clang++',
+                b'-DFEATURE=1',
+                b'-o', b'project2-feature.o',
+                b'-c', b'/home/john.doe/MyProject/project2.cpp'
+            ]
+        }
+    ]
     for i in range(len(cmds)):
         assert cmds[i].directory == expected[i]['wd']
         for arg, exp in zip(cmds[i].arguments, expected[i]['line']):
             assert arg == exp
 
+
 def test_compilecommand_iterator_stops():
     """Check that iterator stops after the correct number of elements"""
     cdb = CompilationDatabase.fromDirectory(kInputsDir)
@@ -90,13 +129,15 @@ def test_compilecommand_iterator_stops():
         count += 1
         assert count <= 2
 
+
 def test_compilationDB_references():
     """Ensure CompilationsCommands are independent of the database"""
     cdb = CompilationDatabase.fromDirectory(kInputsDir)
     cmds = cdb.getCompileCommands('/home/john.doe/MyProject/project.cpp')
     del cdb
     gc.collect()
-    workingdir = cmds[0].directory
+    cmds[0].directory
+
 
 def test_compilationCommands_references():
     """Ensure CompilationsCommand keeps a reference to CompilationCommands"""
@@ -106,5 +147,4 @@ def test_compilationCommands_references():
     cmd0 = cmds[0]
     del cmds
     gc.collect()
-    workingdir = cmd0.directory
-
+    cmd0.directory
diff --git a/bindings/python/tests/cindex/test_code_completion.py b/bindings/python/tests/cindex/test_code_completion.py
index 357d50d..5661146 100644
--- a/bindings/python/tests/cindex/test_code_completion.py
+++ b/bindings/python/tests/cindex/test_code_completion.py
@@ -1,5 +1,6 @@
 from clang.cindex import TranslationUnit
 
+
 def check_completion_results(cr, expected):
     assert cr is not None
     assert len(cr.diagnostics) == 0
@@ -7,10 +8,12 @@ def check_completion_results(cr, expected):
     completions = [str(c) for c in cr.results]
 
     for c in expected:
-        assert c in completions
+        assert c in completions, "Couldn't find '%s'" % c
+
 
 def test_code_complete():
-    files = [('fake.c', """
+    files = [
+        ('fake.c', """
 /// Aaa.
 int test1;
 
@@ -22,18 +25,22 @@ void f() {
 }
 """)]
 
-    tu = TranslationUnit.from_source('fake.c', ['-std=c99'], unsaved_files=files,
-            options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION)
+    tu = TranslationUnit.from_source(
+            'fake.c', ['-std=c99'],
+            unsaved_files=files,
+            options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION
+        )
 
     cr = tu.codeComplete('fake.c', 9, 1, unsaved_files=files, include_brief_comments=True)
 
     expected = [
-      "{'int', ResultType} | {'test1', TypedText} || Priority: 50 || Availability: Available || Brief comment: Aaa.",
-      "{'void', ResultType} | {'test2', TypedText} | {'(', LeftParen} | {')', RightParen} || Priority: 50 || Availability: Available || Brief comment: Bbb.",
-      "{'return', TypedText} || Priority: 40 || Availability: Available || Brief comment: None"
+        "{'int', ResultType} | {'test1', TypedText} || Priority: 50 || Availability: Available || Brief comment: Aaa.",
+        "{'void', ResultType} | {'test2', TypedText} | {'(', LeftParen} | {')', RightParen} || Priority: 50 || Availability: Available || Brief comment: Bbb.",
+        "{'return', TypedText} || Priority: 40 || Availability: Available || Brief comment: None"
     ]
     check_completion_results(cr, expected)
 
+
 def test_code_complete_availability():
     files = [('fake.cpp', """
 class P {
@@ -57,11 +64,11 @@ void f(P x, Q y) {
     cr = tu.codeComplete('fake.cpp', 12, 5, unsaved_files=files)
 
     expected = [
-      "{'const', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
-      "{'volatile', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
-      "{'operator', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
-      "{'P', TypedText} | {'::', Text} || Priority: 75 || Availability: Available || Brief comment: None",
-      "{'Q', TypedText} | {'::', Text} || Priority: 75 || Availability: Available || Brief comment: None"
+        "{'const', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
+        "{'volatile', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
+        "{'operator', TypedText} || Priority: 40 || Availability: Available || Brief comment: None",
+        "{'P', TypedText} | {'::', Text} || Priority: 75 || Availability: Available || Brief comment: None",
+        "{'Q', TypedText} | {'::', Text} || Priority: 75 || Availability: Available || Brief comment: None"
     ]
     check_completion_results(cr, expected)
 
diff --git a/bindings/python/tests/cindex/test_comment.py b/bindings/python/tests/cindex/test_comment.py
index d8f3129..f644e66 100644
--- a/bindings/python/tests/cindex/test_comment.py
+++ b/bindings/python/tests/cindex/test_comment.py
@@ -1,6 +1,9 @@
+from __future__ import unicode_literals
+
 from clang.cindex import TranslationUnit
 from tests.cindex.util import get_cursor
 
+
 def test_comment():
     files = [('fake.c', """
 /// Aaa.
@@ -15,26 +18,27 @@ void f() {
 }
 """)]
     # make a comment-aware TU
-    tu = TranslationUnit.from_source('fake.c', ['-std=c99'], unsaved_files=files,
-            options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION)
+    tu = TranslationUnit.from_source(
+        'fake.c', ['-std=c99'],
+        unsaved_files=files,
+        options=TranslationUnit.PARSE_INCLUDE_BRIEF_COMMENTS_IN_CODE_COMPLETION
+    )
     test1 = get_cursor(tu, 'test1')
     assert test1 is not None, "Could not find test1."
     assert test1.type.is_pod()
     raw = test1.raw_comment
     brief = test1.brief_comment
-    assert raw == """/// Aaa."""
-    assert brief == """Aaa."""
-    
+    assert raw == b"""/// Aaa."""
+    assert brief == b"""Aaa."""
+
     test2 = get_cursor(tu, 'test2')
     raw = test2.raw_comment
     brief = test2.brief_comment
-    assert raw == """/// Bbb.\n/// x"""
-    assert brief == """Bbb. x"""
-    
+    assert raw == b"""/// Bbb.\n/// x"""
+    assert brief == b"""Bbb. x"""
+
     f = get_cursor(tu, 'f')
     raw = f.raw_comment
     brief = f.brief_comment
     assert raw is None
     assert brief is None
-
-
diff --git a/bindings/python/tests/cindex/test_cursor.py b/bindings/python/tests/cindex/test_cursor.py
index c5ea505..d82a5e5 100644
--- a/bindings/python/tests/cindex/test_cursor.py
+++ b/bindings/python/tests/cindex/test_cursor.py
@@ -1,4 +1,5 @@
-import ctypes
+from __future__ import unicode_literals
+
 import gc
 
 from clang.cindex import CursorKind
@@ -29,6 +30,7 @@ void f0(int a0, int a1) {
 }
 """
 
+
 def test_get_children():
     tu = get_tu(kInput)
 
@@ -68,6 +70,7 @@ def test_get_children():
     assert tu_nodes[2].displayname == 'f0(int, int)'
     assert tu_nodes[2].is_definition() == True
 
+
 def test_references():
     """Ensure that references to TranslationUnit are kept."""
     tu = get_tu('int x;')
@@ -83,7 +86,8 @@ def test_references():
     assert isinstance(cursor.translation_unit, TranslationUnit)
 
     # If the TU was destroyed, this should cause a segfault.
-    parent = cursor.semantic_parent
+    cursor.semantic_parent
+
 
 def test_canonical():
     source = 'struct X; struct X; struct X { int member; };'
@@ -97,6 +101,7 @@ def test_canonical():
     assert len(cursors) == 3
     assert cursors[1].canonical == cursors[2].canonical
 
+
 def test_is_const_method():
     """Ensure Cursor.is_const_method works."""
     source = 'class X { void foo() const; void bar(); };'
@@ -112,6 +117,7 @@ def test_is_const_method():
     assert foo.is_const_method()
     assert not bar.is_const_method()
 
+
 def test_is_mutable_field():
     """Ensure Cursor.is_mutable_field works."""
     source = 'class X { int x_; mutable int y_; };'
@@ -127,6 +133,7 @@ def test_is_mutable_field():
     assert not x_.is_mutable_field()
     assert y_.is_mutable_field()
 
+
 def test_is_static_method():
     """Ensure Cursor.is_static_method works."""
 
@@ -143,6 +150,7 @@ def test_is_static_method():
     assert foo.is_static_method()
     assert not bar.is_static_method()
 
+
 def test_is_pure_virtual_method():
     """Ensure Cursor.is_pure_virtual_method works."""
     source = 'class X { virtual void foo() = 0; virtual void bar(); };'
@@ -158,6 +166,7 @@ def test_is_pure_virtual_method():
     assert foo.is_pure_virtual_method()
     assert not bar.is_pure_virtual_method()
 
+
 def test_is_virtual_method():
     """Ensure Cursor.is_virtual_method works."""
     source = 'class X { virtual void foo(); void bar(); };'
@@ -173,6 +182,7 @@ def test_is_virtual_method():
     assert foo.is_virtual_method()
     assert not bar.is_virtual_method()
 
+
 def test_underlying_type():
     tu = get_tu('typedef int foo;')
     typedef = get_cursor(tu, 'foo')
@@ -182,6 +192,7 @@ def test_underlying_type():
     underlying = typedef.underlying_typedef_type
     assert underlying.kind == TypeKind.INT
 
+
 kParentTest = """\
         class C {
             void f();
@@ -189,6 +200,8 @@ kParentTest = """\
 
         void C::f() { }
     """
+
+
 def test_semantic_parent():
     tu = get_tu(kParentTest, 'cpp')
     curs = get_cursors(tu, 'f')
@@ -197,6 +210,7 @@ def test_semantic_parent():
     assert(curs[0].semantic_parent == curs[1].semantic_parent)
     assert(curs[0].semantic_parent == decl)
 
+
 def test_lexical_parent():
     tu = get_tu(kParentTest, 'cpp')
     curs = get_cursors(tu, 'f')
@@ -206,6 +220,7 @@ def test_lexical_parent():
     assert(curs[0].lexical_parent == decl)
     assert(curs[1].lexical_parent == tu.cursor)
 
+
 def test_enum_type():
     tu = get_tu('enum TEST { FOO=1, BAR=2 };')
     enum = get_cursor(tu, 'TEST')
@@ -215,6 +230,7 @@ def test_enum_type():
     enum_type = enum.enum_type
     assert enum_type.kind == TypeKind.UINT
 
+
 def test_enum_type_cpp():
     tu = get_tu('enum TEST : long long { FOO=1, BAR=2 };', lang="cpp")
     enum = get_cursor(tu, 'TEST')
@@ -223,6 +239,7 @@ def test_enum_type_cpp():
     assert enum.kind == CursorKind.ENUM_DECL
     assert enum.enum_type.kind == TypeKind.LONGLONG
 
+
 def test_objc_type_encoding():
     tu = get_tu('int i;', lang='objc')
     i = get_cursor(tu, 'i')
@@ -230,6 +247,7 @@ def test_objc_type_encoding():
     assert i is not None
     assert i.objc_type_encoding == 'i'
 
+
 def test_enum_values():
     tu = get_tu('enum TEST { SPAM=1, EGG, HAM = EGG * 20};')
     enum = get_cursor(tu, 'TEST')
@@ -249,6 +267,7 @@ def test_enum_values():
     assert ham.kind == CursorKind.ENUM_CONSTANT_DECL
     assert ham.enum_value == 40
 
+
 def test_enum_values_cpp():
     tu = get_tu('enum TEST : long long { SPAM = -1, HAM = 0x10000000000};', lang="cpp")
     enum = get_cursor(tu, 'TEST')
@@ -266,6 +285,7 @@ def test_enum_values_cpp():
     assert ham.kind == CursorKind.ENUM_CONSTANT_DECL
     assert ham.enum_value == 0x10000000000
 
+
 def test_annotation_attribute():
     tu = get_tu('int foo (void) __attribute__ ((annotate("here be annotation attribute")));')
 
@@ -279,6 +299,7 @@ def test_annotation_attribute():
     else:
         assert False, "Couldn't find annotation"
 
+
 def test_result_type():
     tu = get_tu('int foo();')
     foo = get_cursor(tu, 'foo')
@@ -287,6 +308,7 @@ def test_result_type():
     t = foo.result_type
     assert t.kind == TypeKind.INT
 
+
 def test_get_tokens():
     """Ensure we can map cursors back to tokens."""
     tu = get_tu('int foo(int i);')
@@ -297,6 +319,7 @@ def test_get_tokens():
     assert tokens[0].spelling == 'int'
     assert tokens[1].spelling == 'foo'
 
+
 def test_get_arguments():
     tu = get_tu('void foo(int i, int j);')
     foo = get_cursor(tu, 'foo')
@@ -314,12 +337,14 @@ kTemplateArgTest = """\
         void foo<-7, float, true>();
     """
 
+
 def test_get_num_template_arguments():
     tu = get_tu(kTemplateArgTest, lang='cpp')
     foos = get_cursors(tu, 'foo')
 
     assert foos[1].get_num_template_arguments() == 3
 
+
 def test_get_template_argument_kind():
     tu = get_tu(kTemplateArgTest, lang='cpp')
     foos = get_cursors(tu, 'foo')
@@ -328,12 +353,14 @@ def test_get_template_argument_kind():
     assert foos[1].get_template_argument_kind(1) == TemplateArgumentKind.TYPE
     assert foos[1].get_template_argument_kind(2) == TemplateArgumentKind.INTEGRAL
 
+
 def test_get_template_argument_type():
     tu = get_tu(kTemplateArgTest, lang='cpp')
     foos = get_cursors(tu, 'foo')
 
     assert foos[1].get_template_argument_type(1).kind == TypeKind.FLOAT
 
+
 def test_get_template_argument_value():
     tu = get_tu(kTemplateArgTest, lang='cpp')
     foos = get_cursors(tu, 'foo')
@@ -341,6 +368,7 @@ def test_get_template_argument_value():
     assert foos[1].get_template_argument_value(0) == -7
     assert foos[1].get_template_argument_value(2) == True
 
+
 def test_get_template_argument_unsigned_value():
     tu = get_tu(kTemplateArgTest, lang='cpp')
     foos = get_cursors(tu, 'foo')
@@ -348,6 +376,7 @@ def test_get_template_argument_unsigned_value():
     assert foos[1].get_template_argument_unsigned_value(0) == 2 ** 32 - 7
     assert foos[1].get_template_argument_unsigned_value(2) == True
 
+
 def test_referenced():
     tu = get_tu('void foo(); void bar() { foo(); }')
     foo = get_cursor(tu, 'foo')
@@ -357,6 +386,7 @@ def test_referenced():
             assert c.referenced.spelling == foo.spelling
             break
 
+
 def test_mangled_name():
     kInputForMangling = """\
     int foo(int, int);
diff --git a/bindings/python/tests/cindex/test_cursor_kind.py b/bindings/python/tests/cindex/test_cursor_kind.py
index 5bac289..170360d 100644
--- a/bindings/python/tests/cindex/test_cursor_kind.py
+++ b/bindings/python/tests/cindex/test_cursor_kind.py
@@ -1,8 +1,10 @@
 from clang.cindex import CursorKind
 
+
 def test_name():
     assert CursorKind.UNEXPOSED_DECL.name is 'UNEXPOSED_DECL'
 
+
 def test_get_all_kinds():
     kinds = CursorKind.get_all_kinds()
     assert CursorKind.UNEXPOSED_DECL in kinds
@@ -15,6 +17,7 @@ def test_get_all_kinds():
     assert CursorKind.MODULE_IMPORT_DECL in kinds
     assert CursorKind.TYPE_ALIAS_TEMPLATE_DECL in kinds
 
+
 def test_kind_groups():
     """Check that every kind classifies to exactly one group."""
 
@@ -35,14 +38,18 @@ def test_kind_groups():
 
     for k in CursorKind.get_all_kinds():
         group = [n for n in ('is_declaration', 'is_reference', 'is_expression',
-                             'is_statement', 'is_invalid', 'is_attribute')
+                             'is_statement', 'is_attribute', 'is_invalid')
                  if getattr(k, n)()]
 
-        if k in (   CursorKind.TRANSLATION_UNIT,
-                    CursorKind.MACRO_DEFINITION,
-                    CursorKind.MACRO_INSTANTIATION,
-                    CursorKind.INCLUSION_DIRECTIVE,
-                    CursorKind.PREPROCESSING_DIRECTIVE):
-            assert len(group) == 0
+        if k in (CursorKind.TRANSLATION_UNIT,
+                 CursorKind.MACRO_DEFINITION,
+                 CursorKind.MACRO_INSTANTIATION,
+                 CursorKind.INCLUSION_DIRECTIVE,
+                 CursorKind.PREPROCESSING_DIRECTIVE,
+                 CursorKind.VISIBILITY_ATTR,
+                 CursorKind.DLLEXPORT_ATTR,
+                 CursorKind.DLLIMPORT_ATTR,
+                 CursorKind.TYPE_ALIAS_TEMPLATE_DECL):
+            assert len(group) == 0, "Group %s, kind %s" % (group, k)
         else:
-            assert len(group) == 1
+            assert len(group) == 1, "Group %s, kind %s" % (group, k)
diff --git a/bindings/python/tests/cindex/test_diagnostics.py b/bindings/python/tests/cindex/test_diagnostics.py
index 48ab617..8007c4c 100644
--- a/bindings/python/tests/cindex/test_diagnostics.py
+++ b/bindings/python/tests/cindex/test_diagnostics.py
@@ -1,8 +1,11 @@
+from __future__ import unicode_literals
+
 from clang.cindex import *
 from .util import get_tu
 
 # FIXME: We need support for invalid translation units to test better.
 
+
 def test_diagnostic_warning():
     tu = get_tu('int f0() {}\n')
     assert len(tu.diagnostics) == 1
@@ -12,6 +15,7 @@ def test_diagnostic_warning():
     assert (tu.diagnostics[0].spelling ==
             'control reaches end of non-void function')
 
+
 def test_diagnostic_note():
     # FIXME: We aren't getting notes here for some reason.
     tu = get_tu('#define A x\nvoid *A = 1;\n')
@@ -25,6 +29,7 @@ def test_diagnostic_note():
 #    assert tu.diagnostics[1].location.column == 11
 #    assert tu.diagnostics[1].spelling == 'instantiated from'
 
+
 def test_diagnostic_fixit():
     tu = get_tu('struct { int f0; } x = { f0 : 1 };')
     assert len(tu.diagnostics) == 1
@@ -39,6 +44,7 @@ def test_diagnostic_fixit():
     assert tu.diagnostics[0].fixits[0].range.end.column == 30
     assert tu.diagnostics[0].fixits[0].value == '.f0 = '
 
+
 def test_diagnostic_range():
     tu = get_tu('void f() { int i = "a" + 1; }')
     assert len(tu.diagnostics) == 1
@@ -53,11 +59,12 @@ def test_diagnostic_range():
     assert tu.diagnostics[0].ranges[0].end.line == 1
     assert tu.diagnostics[0].ranges[0].end.column == 27
     try:
-      tu.diagnostics[0].ranges[1].start.line
+        tu.diagnostics[0].ranges[1].start.line
     except IndexError:
-      assert True
+        assert True
     else:
-      assert False
+        assert False
+
 
 def test_diagnostic_category():
     """Ensure that category properties work."""
@@ -72,6 +79,7 @@ def test_diagnostic_category():
     assert d.category_number == 2
     assert d.category_name == 'Semantic Issue'
 
+
 def test_diagnostic_option():
     """Ensure that category option properties work."""
     tu = get_tu('int f(int i) { return 7; }', all_warnings=True)
diff --git a/bindings/python/tests/cindex/test_file.py b/bindings/python/tests/cindex/test_file.py
index 146e8c5..aa1da58 100644
--- a/bindings/python/tests/cindex/test_file.py
+++ b/bindings/python/tests/cindex/test_file.py
@@ -1,9 +1,10 @@
 from clang.cindex import Index, File
 
+
 def test_file():
-  index = Index.create()
-  tu = index.parse('t.c', unsaved_files = [('t.c', "")])
-  file = File.from_name(tu, "t.c")
-  assert str(file) == "t.c"
-  assert file.name == "t.c"
-  assert repr(file) == "<File: t.c>"
+    index = Index.create()
+    tu = index.parse('t.c', unsaved_files=[('t.c', "")])
+    file = File.from_name(tu, "t.c")
+    assert str(file) == "t.c"
+    assert file.name == "t.c"
+    assert repr(file) == "<File: t.c>"
diff --git a/bindings/python/tests/cindex/test_location.py b/bindings/python/tests/cindex/test_location.py
index 9e9ef48..b2c72a3 100644
--- a/bindings/python/tests/cindex/test_location.py
+++ b/bindings/python/tests/cindex/test_location.py
@@ -5,13 +5,15 @@ from clang.cindex import SourceRange
 from .util import get_cursor
 from .util import get_tu
 
-baseInput="int one;\nint two;\n"
+baseInput = "int one;\nint two;\n"
+
 
 def assert_location(loc, line, column, offset):
     assert loc.line == line
     assert loc.column == column
     assert loc.offset == offset
 
+
 def test_location():
     tu = get_tu(baseInput)
     one = get_cursor(tu, 'one')
@@ -20,8 +22,8 @@ def test_location():
     assert one is not None
     assert two is not None
 
-    assert_location(one.location,line=1,column=5,offset=4)
-    assert_location(two.location,line=2,column=5,offset=13)
+    assert_location(one.location, line=1, column=5, offset=4)
+    assert_location(two.location, line=2, column=5, offset=13)
 
     # adding a linebreak at top should keep columns same
     tu = get_tu('\n' + baseInput)
@@ -31,16 +33,16 @@ def test_location():
     assert one is not None
     assert two is not None
 
-    assert_location(one.location,line=2,column=5,offset=5)
-    assert_location(two.location,line=3,column=5,offset=14)
+    assert_location(one.location, line=2, column=5, offset=5)
+    assert_location(two.location, line=3, column=5, offset=14)
 
     # adding a space should affect column on first line only
     tu = get_tu(' ' + baseInput)
     one = get_cursor(tu, 'one')
     two = get_cursor(tu, 'two')
 
-    assert_location(one.location,line=1,column=6,offset=5)
-    assert_location(two.location,line=2,column=5,offset=14)
+    assert_location(one.location, line=1, column=6, offset=5)
+    assert_location(two.location, line=2, column=5, offset=14)
 
     # define the expected location ourselves and see if it matches
     # the returned location
@@ -69,17 +71,18 @@ def test_location():
 
     assert verified
 
+
 def test_extent():
     tu = get_tu(baseInput)
     one = get_cursor(tu, 'one')
     two = get_cursor(tu, 'two')
 
-    assert_location(one.extent.start,line=1,column=1,offset=0)
-    assert_location(one.extent.end,line=1,column=8,offset=7)
+    assert_location(one.extent.start, line=1, column=1, offset=0)
+    assert_location(one.extent.end, line=1, column=8, offset=7)
     assert baseInput[one.extent.start.offset:one.extent.end.offset] == "int one"
 
-    assert_location(two.extent.start,line=2,column=1,offset=9)
-    assert_location(two.extent.end,line=2,column=8,offset=16)
+    assert_location(two.extent.start, line=2, column=1, offset=9)
+    assert_location(two.extent.end, line=2, column=8, offset=16)
     assert baseInput[two.extent.start.offset:two.extent.end.offset] == "int two"
 
     file = File.from_name(tu, 't.c')
diff --git a/bindings/python/tests/cindex/test_tokens.py b/bindings/python/tests/cindex/test_tokens.py
index 7074842..adfe071 100644
--- a/bindings/python/tests/cindex/test_tokens.py
+++ b/bindings/python/tests/cindex/test_tokens.py
@@ -1,5 +1,6 @@
+from __future__ import unicode_literals
+
 from clang.cindex import CursorKind
-from clang.cindex import Index
 from clang.cindex import SourceLocation
 from clang.cindex import SourceRange
 from clang.cindex import TokenKind
@@ -8,6 +9,7 @@ from nose.tools import ok_
 
 from .util import get_tu
 
+
 def test_token_to_cursor():
     """Ensure we can obtain a Cursor from a Token instance."""
     tu = get_tu('int i = 5;')
@@ -22,6 +24,7 @@ def test_token_to_cursor():
     assert cursor.kind == CursorKind.VAR_DECL
     assert tokens[1].cursor == tokens[2].cursor
 
+
 def test_token_location():
     """Ensure Token.location works."""
 
@@ -37,6 +40,7 @@ def test_token_location():
     eq_(loc.column, 5)
     eq_(loc.offset, 4)
 
+
 def test_token_extent():
     """Ensure Token.extent works."""
     tu = get_tu('int foo = 10;')
diff --git a/bindings/python/tests/cindex/test_translation_unit.py b/bindings/python/tests/cindex/test_translation_unit.py
index be6cd67..b6153d8 100644
--- a/bindings/python/tests/cindex/test_translation_unit.py
+++ b/bindings/python/tests/cindex/test_translation_unit.py
@@ -1,5 +1,8 @@
+from __future__ import unicode_literals
+
 import gc
 import os
+import sys
 import tempfile
 
 from clang.cindex import CursorKind
@@ -16,11 +19,13 @@ from .util import get_tu
 
 kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
 
+
 def test_spelling():
     path = os.path.join(kInputsDir, 'hello.cpp')
     tu = TranslationUnit.from_source(path)
     assert tu.spelling == path
 
+
 def test_cursor():
     path = os.path.join(kInputsDir, 'hello.cpp')
     tu = get_tu(path)
@@ -28,6 +33,7 @@ def test_cursor():
     assert isinstance(c, Cursor)
     assert c.kind is CursorKind.TRANSLATION_UNIT
 
+
 def test_parse_arguments():
     path = os.path.join(kInputsDir, 'parse_arguments.c')
     tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi'])
@@ -35,6 +41,7 @@ def test_parse_arguments():
     assert spellings[-2] == 'hello'
     assert spellings[-1] == 'hi'
 
+
 def test_reparse_arguments():
     path = os.path.join(kInputsDir, 'parse_arguments.c')
     tu = TranslationUnit.from_source(path, ['-DDECL_ONE=hello', '-DDECL_TWO=hi'])
@@ -43,8 +50,9 @@ def test_reparse_arguments():
     assert spellings[-2] == 'hello'
     assert spellings[-1] == 'hi'
 
+
 def test_unsaved_files():
-    tu = TranslationUnit.from_source('fake.c', ['-I./'], unsaved_files = [
+    tu = TranslationUnit.from_source('fake.c', ['-I./'], unsaved_files=[
             ('fake.c', """
 #include "fake.h"
 int x;
@@ -58,24 +66,32 @@ int SOME_DEFINE;
     assert spellings[-2] == 'x'
     assert spellings[-1] == 'y'
 
+
 def test_unsaved_files_2():
-    import StringIO
-    tu = TranslationUnit.from_source('fake.c', unsaved_files = [
-            ('fake.c', StringIO.StringIO('int x;'))])
+    if sys.version_info.major == 2:
+        from StringIO import StringIO
+    else:
+        from io import StringIO
+    tu = TranslationUnit.from_source('fake.c', unsaved_files=[
+            ('fake.c', StringIO('int x;'))])
     spellings = [c.spelling for c in tu.cursor.get_children()]
     assert spellings[-1] == 'x'
 
+
 def normpaths_equal(path1, path2):
     """ Compares two paths for equality after normalizing them with
         os.path.normpath
     """
     return os.path.normpath(path1) == os.path.normpath(path2)
 
+
 def test_includes():
     def eq(expected, actual):
         if not actual.is_input_file:
-            return  normpaths_equal(expected[0], actual.source.name) and \
-                    normpaths_equal(expected[1], actual.include.name)
+            return (
+                normpaths_equal(expected[0], actual.source.name) and
+                normpaths_equal(expected[1], actual.include.name)
+            )
         else:
             return normpaths_equal(expected[1], actual.include.name)
 
@@ -89,6 +105,7 @@ def test_includes():
     for i in zip(inc, tu.get_includes()):
         assert eq(i[0], i[1])
 
+
 def save_tu(tu):
     """Convenience API to save a TranslationUnit to a file.
 
@@ -99,6 +116,7 @@ def save_tu(tu):
 
     return path
 
+
 def test_save():
     """Ensure TranslationUnit.save() works."""
 
@@ -109,6 +127,7 @@ def test_save():
     assert os.path.getsize(path) > 0
     os.unlink(path)
 
+
 def test_save_translation_errors():
     """Ensure that saving to an invalid directory raises."""
 
@@ -124,6 +143,7 @@ def test_save_translation_errors():
         expected = TranslationUnitSaveError.ERROR_UNKNOWN
         assert ex.save_error == expected
 
+
 def test_load():
     """Ensure TranslationUnits can be constructed from saved files."""
 
@@ -145,12 +165,14 @@ def test_load():
 
     os.unlink(path)
 
+
 def test_index_parse():
     path = os.path.join(kInputsDir, 'hello.cpp')
     index = Index.create()
     tu = index.parse(path)
     assert isinstance(tu, TranslationUnit)
 
+
 def test_get_file():
     """Ensure tu.get_file() works appropriately."""
 
@@ -167,6 +189,7 @@ def test_get_file():
     else:
         assert False
 
+
 def test_get_source_location():
     """Ensure tu.get_source_location() works."""
 
@@ -183,19 +206,20 @@ def test_get_source_location():
     assert location.column == 3
     assert location.file.name == 't.c'
 
+
 def test_get_source_range():
     """Ensure tu.get_source_range() works."""
 
     tu = get_tu('int foo();')
 
-    r = tu.get_extent('t.c', (1,4))
+    r = tu.get_extent('t.c', (1, 4))
     assert isinstance(r, SourceRange)
     assert r.start.offset == 1
     assert r.end.offset == 4
     assert r.start.file.name == 't.c'
     assert r.end.file.name == 't.c'
 
-    r = tu.get_extent('t.c', ((1,2), (1,3)))
+    r = tu.get_extent('t.c', ((1, 2), (1, 3)))
     assert isinstance(r, SourceRange)
     assert r.start.line == 1
     assert r.start.column == 2
@@ -214,6 +238,7 @@ def test_get_source_range():
     assert r.start.file.name == 't.c'
     assert r.end.file.name == 't.c'
 
+
 def test_get_tokens_gc():
     """Ensures get_tokens() works properly with garbage collection."""
 
@@ -221,6 +246,7 @@ def test_get_tokens_gc():
     r = tu.get_extent('t.c', (0, 10))
     tokens = list(tu.get_tokens(extent=r))
 
+    print(type(tokens[0]))
     assert tokens[0].spelling == 'int'
     gc.collect()
     assert tokens[0].spelling == 'int'
@@ -232,7 +258,8 @@ def test_get_tokens_gc():
     # May trigger segfault if we don't do our job properly.
     del tokens
     gc.collect()
-    gc.collect() # Just in case.
+    gc.collect()  # Just in case.
+
 
 def test_fail_from_source():
     path = os.path.join(kInputsDir, 'non-existent.cpp')
@@ -240,7 +267,8 @@ def test_fail_from_source():
         tu = TranslationUnit.from_source(path)
     except TranslationUnitLoadError:
         tu = None
-    assert tu == None
+    assert tu is None
+
 
 def test_fail_from_ast_file():
     path = os.path.join(kInputsDir, 'non-existent.ast')
@@ -248,4 +276,4 @@ def test_fail_from_ast_file():
         tu = TranslationUnit.from_ast_file(path)
     except TranslationUnitLoadError:
         tu = None
-    assert tu == None
+    assert tu is None
diff --git a/bindings/python/tests/cindex/test_type.py b/bindings/python/tests/cindex/test_type.py
index f218433..9fb0fbc 100644
--- a/bindings/python/tests/cindex/test_type.py
+++ b/bindings/python/tests/cindex/test_type.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 import gc
 
 from clang.cindex import CursorKind
@@ -24,6 +26,7 @@ struct teststruct {
 
 """
 
+
 def test_a_struct():
     tu = get_tu(kInput)
 
@@ -76,6 +79,7 @@ def test_a_struct():
     assert fields[7].type.get_pointee().get_pointee().kind == TypeKind.POINTER
     assert fields[7].type.get_pointee().get_pointee().get_pointee().kind == TypeKind.INT
 
+
 def test_references():
     """Ensure that a Type maintains a reference to a TranslationUnit."""
 
@@ -94,13 +98,16 @@ def test_references():
     assert isinstance(t.translation_unit, TranslationUnit)
 
     # If the TU was destroyed, this should cause a segfault.
-    decl = t.get_declaration()
+    t.get_declaration()
 
-constarrayInput="""
+
+constarrayInput = """
 struct teststruct {
   void *A[2];
 };
 """
+
+
 def testConstantArray():
     tu = get_tu(constarrayInput)
 
@@ -113,6 +120,7 @@ def testConstantArray():
     assert fields[0].type.get_array_element_type().kind == TypeKind.POINTER
     assert fields[0].type.get_array_size() == 2
 
+
 def test_equal():
     """Ensure equivalence operators work on Type."""
     source = 'int a; int b; void *v;'
@@ -129,9 +137,10 @@ def test_equal():
     assert a.type == b.type
     assert a.type != v.type
 
-    assert a.type != None
+    assert a.type is not None
     assert a.type != 'foo'
 
+
 def test_type_spelling():
     """Ensure Type.spelling works."""
     tu = get_tu('int c[5]; void f(int i[]); int x; int v[x];')
@@ -148,6 +157,7 @@ def test_type_spelling():
     assert x.type.spelling == "int"
     assert v.type.spelling == "int [x]"
 
+
 def test_typekind_spelling():
     """Ensure TypeKind.spelling works."""
     tu = get_tu('int a;')
@@ -156,6 +166,7 @@ def test_typekind_spelling():
     assert a is not None
     assert a.type.kind.spelling == 'Int'
 
+
 def test_function_argument_types():
     """Ensure that Type.argument_types() works as expected."""
     tu = get_tu('void f(int, int);')
@@ -179,6 +190,7 @@ def test_function_argument_types():
     assert t0 == args2[0]
     assert t1 == args2[1]
 
+
 @raises(TypeError)
 def test_argument_types_string_key():
     """Ensure that non-int keys raise a TypeError."""
@@ -191,6 +203,7 @@ def test_argument_types_string_key():
 
     args['foo']
 
+
 @raises(IndexError)
 def test_argument_types_negative_index():
     """Ensure that negative indexes on argument_types Raises an IndexError."""
@@ -200,6 +213,7 @@ def test_argument_types_negative_index():
 
     args[-1]
 
+
 @raises(IndexError)
 def test_argument_types_overflow_index():
     """Ensure that indexes beyond the length of Type.argument_types() raise."""
@@ -209,6 +223,7 @@ def test_argument_types_overflow_index():
 
     args[2]
 
+
 @raises(Exception)
 def test_argument_types_invalid_type():
     """Ensure that obtaining argument_types on a Type without them raises."""
@@ -218,6 +233,7 @@ def test_argument_types_invalid_type():
 
     i.type.argument_types()
 
+
 def test_is_pod():
     """Ensure Type.is_pod() works."""
     tu = get_tu('int i; void f();')
@@ -230,10 +246,11 @@ def test_is_pod():
     assert i.type.is_pod()
     assert not f.type.is_pod()
 
+
 def test_function_variadic():
     """Ensure Type.is_function_variadic works."""
 
-    source ="""
+    source = """
 #include <stdarg.h>
 
 void foo(int a, ...);
@@ -251,6 +268,7 @@ void bar(int a, int b);
     assert foo.type.is_function_variadic()
     assert not bar.type.is_function_variadic()
 
+
 def test_element_type():
     """Ensure Type.element_type works."""
     tu = get_tu('int c[5]; void f(int i[]); int x; int v[x];')
@@ -268,6 +286,7 @@ def test_element_type():
     assert v.type.kind == TypeKind.VARIABLEARRAY
     assert v.type.element_type.kind == TypeKind.INT
 
+
 @raises(Exception)
 def test_invalid_element_type():
     """Ensure Type.element_type raises if type doesn't have elements."""
@@ -276,6 +295,7 @@ def test_invalid_element_type():
     assert i is not None
     i.element_type
 
+
 def test_element_count():
     """Ensure Type.element_count works."""
     tu = get_tu('int i[5]; int j;')
@@ -293,6 +313,7 @@ def test_element_count():
     except:
         assert True
 
+
 def test_is_volatile_qualified():
     """Ensure Type.is_volatile_qualified works."""
 
@@ -308,6 +329,7 @@ def test_is_volatile_qualified():
     assert i.type.is_volatile_qualified()
     assert not j.type.is_volatile_qualified()
 
+
 def test_is_restrict_qualified():
     """Ensure Type.is_restrict_qualified works."""
 
@@ -323,11 +345,12 @@ def test_is_restrict_qualified():
     assert i.type.is_restrict_qualified()
     assert not j.type.is_restrict_qualified()
 
+
 def test_record_layout():
     """Ensure Cursor.type.get_size, Cursor.type.get_align and
     Cursor.type.get_offset works."""
 
-    source ="""
+    source = """
 struct a {
     long a1;
     long a2:3;
@@ -335,12 +358,14 @@ struct a {
     long long a4;
 };
 """
-    tries=[(['-target','i386-linux-gnu'],(4,16,0,32,35,64)),
-           (['-target','nvptx64-unknown-unknown'],(8,24,0,64,67,128)),
-           (['-target','i386-pc-win32'],(8,16,0,32,35,64)),
-           (['-target','msp430-none-none'],(2,14,0,32,35,48))]
+    tries = [
+        (['-target', 'i386-linux-gnu'], (4, 16, 0, 32, 35, 64)),
+        (['-target', 'nvptx64-unknown-unknown'], (8, 24, 0, 64, 67, 128)),
+        (['-target', 'i386-pc-win32'], (8, 16, 0, 32, 35, 64)),
+        (['-target', 'msp430-none-none'], (2, 14, 0, 32, 35, 48))
+    ]
     for flags, values in tries:
-        align,total,a1,a2,a3,a4 = values
+        align, total, a1, a2, a3, a4 = values
 
         tu = get_tu(source, flags=flags)
         teststruct = get_cursor(tu, 'a')
@@ -359,9 +384,10 @@ struct a {
         assert fields[2].get_bitfield_width() == 4
         assert fields[3].is_bitfield() == False
 
+
 def test_offset():
     """Ensure Cursor.get_record_field_offset works in anonymous records"""
-    source="""
+    source = """
 struct Test {
   struct {int a;} typeanon;
   struct {
@@ -372,12 +398,14 @@ struct Test {
   };
   int bar;
 };"""
-    tries=[(['-target','i386-linux-gnu'],(4,16,0,32,64,96)),
-           (['-target','nvptx64-unknown-unknown'],(8,24,0,32,64,96)),
-           (['-target','i386-pc-win32'],(8,16,0,32,64,96)),
-           (['-target','msp430-none-none'],(2,14,0,32,64,96))]
+    tries = [
+        (['-target', 'i386-linux-gnu'], (4, 16, 0, 32, 64, 96)),
+        (['-target', 'nvptx64-unknown-unknown'], (8, 24, 0, 32, 64, 96)),
+        (['-target', 'i386-pc-win32'], (8, 16, 0, 32, 64, 96)),
+        (['-target', 'msp430-none-none'], (2, 14, 0, 32, 64, 96))
+    ]
     for flags, values in tries:
-        align,total,f1,bariton,foo,bar = values
+        align, total, f1, bariton, foo, bar = values
         tu = get_tu(source)
         teststruct = get_cursor(tu, 'Test')
         children = list(teststruct.get_children())
diff --git a/bindings/python/tests/cindex/util.py b/bindings/python/tests/cindex/util.py
index c53ba7c..ae51488 100644
--- a/bindings/python/tests/cindex/util.py
+++ b/bindings/python/tests/cindex/util.py
@@ -1,8 +1,10 @@
 # This file provides common utility functions for the test suite.
+from __future__ import unicode_literals
 
 from clang.cindex import Cursor
 from clang.cindex import TranslationUnit
 
+
 def get_tu(source, lang='c', all_warnings=False, flags=[]):
     """Obtain a translation unit from source and language.
 
@@ -27,8 +29,10 @@ def get_tu(source, lang='c', all_warnings=False, flags=[]):
     if all_warnings:
         args += ['-Wall', '-Wextra']
 
-    return TranslationUnit.from_source(name, args, unsaved_files=[(name,
-                                       source)])
+    return TranslationUnit.from_source(
+        name, args, unsaved_files=[(name, source)]
+    )
+
 
 def get_cursor(source, spelling):
     """Obtain a cursor from a source object.
@@ -48,6 +52,7 @@ def get_cursor(source, spelling):
 
     return None
 
+
 def get_cursors(source, spelling):
     """Obtain all cursors from a source object with a specific spelling.
 


More information about the cfe-commits mailing list