Adding Python 3 compatibility to Clang Python bindings

Russell Keith-Magee via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 20 20:43:31 PST 2016


Hi all,

Following some feedback on cfe-dev, here is an updated version of the
previous diff, presented as a set of 4 patches. The four patches are:

 1. Python 3 compatibility
 2. Simple (and hopefully uncontroversial) PEP8 formatting fixes
 3. A new setup.py
 4. More controversial PEP8 formatting fixes.

Let me know if there is anything else I can do to smooth the path into
master.

Yours,
Russ Magee %-)


On Thu, Jan 14, 2016 at 12:45 PM, Russell Keith-Magee <
russell at keith-magee.com> wrote:

>
> 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/20160121/9e85472c/attachment-0001.html>
-------------- next part --------------
From c6dc0f639a5b33a47ccd9a31029a016bc4eb8f05 Mon Sep 17 00:00:00 2001
From: Russell Keith-Magee <russell at keith-magee.com>
Date: Thu, 21 Jan 2016 11:59:04 +0800
Subject: [PATCH 1/4] Modified Python bindings for Python 3 compatibility.

Python 2 compatibility has been preserved in this patch.
---
 bindings/python/clang/cindex.py                    | 119 ++++++++++++---------
 .../python/tests/cindex/test_access_specifiers.py  |   1 +
 bindings/python/tests/cindex/test_cdb.py           |  74 +++++++++----
 .../python/tests/cindex/test_code_completion.py    |   4 +-
 bindings/python/tests/cindex/test_comment.py       |  14 +--
 bindings/python/tests/cindex/test_cursor.py        |   2 +
 bindings/python/tests/cindex/test_cursor_kind.py   |  22 ++--
 bindings/python/tests/cindex/test_diagnostics.py   |   2 +
 bindings/python/tests/cindex/test_file.py          |   2 +
 bindings/python/tests/cindex/test_index.py         |   2 +
 bindings/python/tests/cindex/test_location.py      |   2 +
 bindings/python/tests/cindex/test_token_kind.py    |   2 +
 bindings/python/tests/cindex/test_tokens.py        |   2 +
 .../python/tests/cindex/test_translation_unit.py   |  10 +-
 bindings/python/tests/cindex/test_type.py          |   4 +-
 bindings/python/tests/cindex/util.py               |   1 +
 16 files changed, 174 insertions(+), 89 deletions(-)

diff --git a/bindings/python/clang/cindex.py b/bindings/python/clang/cindex.py
index e4b3876..29ece66 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
@@ -64,6 +65,8 @@ call is efficient.
 
 from ctypes import *
 import collections
+import sys
+
 
 import clang.enumerations
 
@@ -75,6 +78,12 @@ c_object_p = POINTER(c_void_p)
 
 callbacks = {}
 
+# Python 3 type compatibility
+if sys.version_info.major <= 2:
+    BASESTRING = basestring
+else:
+    BASESTRING = str
+
 ### Exception Classes ###
 
 class TranslationUnitLoadError(Exception):
@@ -321,7 +330,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):
@@ -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,7 +389,7 @@ 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>" % (
@@ -398,7 +407,7 @@ 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)
@@ -449,7 +458,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
@@ -512,8 +521,8 @@ 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
@@ -535,7 +544,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 +563,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."""
@@ -1228,7 +1237,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
 
@@ -1242,7 +1251,7 @@ class Cursor(Structure):
         arguments of a class template specialization.
         """
         if not hasattr(self, '_displayname'):
-            self._displayname = conf.lib.clang_getCursorDisplayName(self)
+            self._displayname = conf.lib.clang_getCursorDisplayName(self).decode('utf-8')
 
         return self._displayname
 
@@ -1250,7 +1259,7 @@ class Cursor(Structure):
     def mangled_name(self):
         """Return the mangled name for the entity referenced by this cursor."""
         if not hasattr(self, '_mangled_name'):
-            self._mangled_name = conf.lib.clang_Cursor_getMangling(self)
+            self._mangled_name = conf.lib.clang_Cursor_getMangling(self).decode('utf-8')
 
         return self._mangled_name
 
@@ -1387,7 +1396,7 @@ class Cursor(Structure):
         """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)
+              conf.lib.clang_getDeclObjCTypeEncoding(self).decode('utf-8')
 
         return self._objc_type_encoding
 
@@ -1576,7 +1585,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
@@ -1597,7 +1606,7 @@ class StorageClass(object):
     @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):
@@ -1650,7 +1659,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,)
@@ -1918,7 +1927,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):
         """
@@ -1945,7 +1954,7 @@ class Type(Structure):
     @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):
@@ -2029,7 +2038,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
@@ -2132,10 +2141,11 @@ class CompletionString(ClangObject):
         return _CXString()
 
     def __repr__(self):
+        brief_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: " + brief_comment
 
 availabilityKinds = {
             0: CompletionChunk.Kind("Available"),
@@ -2332,7 +2342,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 +2352,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 +2384,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 +2411,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):
         """
@@ -2520,9 +2534,9 @@ class TranslationUnit(ClangObject):
                     # 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)
@@ -2545,7 +2559,7 @@ 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,
@@ -2580,18 +2594,20 @@ class TranslationUnit(ClangObject):
         if len(unsaved_files):
             unsaved_files_array = (_CXUnsavedFile * len(unsaved_files))()
             for i,(name,value) in enumerate(unsaved_files):
-                if not isinstance(value, str):
+                if not isinstance(value, BASESTRING):
                     # FIXME: It would be great to support an efficient version
                     # of this, one day.
                     value = value.read()
-                    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
+                    print(value)
+                if not isinstance(value, BASESTRING):
+                    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
@@ -2618,12 +2634,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):
@@ -2711,7 +2727,7 @@ 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):
@@ -2763,8 +2779,9 @@ 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))
+            cdb = conf.lib.clang_CompilationDatabase_fromDirectory(
+                buildDir.encode('utf-8'), byref(errorCode)
+            )
         except CompilationDatabaseError as e:
             raise CompilationDatabaseError(int(errorCode.value),
                                            "CompilationDatabase loading failed")
@@ -2776,7 +2793,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 +2823,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):
@@ -3520,7 +3537,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
diff --git a/bindings/python/tests/cindex/test_access_specifiers.py b/bindings/python/tests/cindex/test_access_specifiers.py
index cfa04dc..6d9b1bb 100644
--- a/bindings/python/tests/cindex/test_access_specifiers.py
+++ b/bindings/python/tests/cindex/test_access_specifiers.py
@@ -1,3 +1,4 @@
+from __future__ import unicode_literals
 
 from clang.cindex import AccessSpecifier
 from clang.cindex import Cursor
diff --git a/bindings/python/tests/cindex/test_cdb.py b/bindings/python/tests/cindex/test_cdb.py
index e1f824f..2457632 100644
--- a/bindings/python/tests/cindex/test_cdb.py
+++ b/bindings/python/tests/cindex/test_cdb.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from clang.cindex import CompilationDatabase
 from clang.cindex import CompilationDatabaseError
 from clang.cindex import CompileCommands
@@ -24,7 +26,7 @@ def test_create():
 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"""
@@ -38,16 +40,32 @@ def test_all_compilecommand():
     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']):
@@ -58,9 +76,12 @@ def test_1_compilecommand():
     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
 
@@ -70,13 +91,24 @@ def test_2_compilecommand():
     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']):
diff --git a/bindings/python/tests/cindex/test_code_completion.py b/bindings/python/tests/cindex/test_code_completion.py
index 357d50d..84ba62a 100644
--- a/bindings/python/tests/cindex/test_code_completion.py
+++ b/bindings/python/tests/cindex/test_code_completion.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from clang.cindex import TranslationUnit
 
 def check_completion_results(cr, expected):
@@ -7,7 +9,7 @@ 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', """
diff --git a/bindings/python/tests/cindex/test_comment.py b/bindings/python/tests/cindex/test_comment.py
index d8f3129..f7e1087 100644
--- a/bindings/python/tests/cindex/test_comment.py
+++ b/bindings/python/tests/cindex/test_comment.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from clang.cindex import TranslationUnit
 from tests.cindex.util import get_cursor
 
@@ -22,15 +24,15 @@ void f() {
     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
diff --git a/bindings/python/tests/cindex/test_cursor.py b/bindings/python/tests/cindex/test_cursor.py
index c5ea505..7c8b2cc 100644
--- a/bindings/python/tests/cindex/test_cursor.py
+++ b/bindings/python/tests/cindex/test_cursor.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 import ctypes
 import gc
 
diff --git a/bindings/python/tests/cindex/test_cursor_kind.py b/bindings/python/tests/cindex/test_cursor_kind.py
index 5bac289..1a09f36 100644
--- a/bindings/python/tests/cindex/test_cursor_kind.py
+++ b/bindings/python/tests/cindex/test_cursor_kind.py
@@ -1,7 +1,9 @@
+from __future__ import unicode_literals
+
 from clang.cindex import CursorKind
 
 def test_name():
-    assert CursorKind.UNEXPOSED_DECL.name is 'UNEXPOSED_DECL'
+    assert CursorKind.UNEXPOSED_DECL.name == 'UNEXPOSED_DECL'
 
 def test_get_all_kinds():
     kinds = CursorKind.get_all_kinds()
@@ -38,11 +40,15 @@ def test_kind_groups():
                              'is_statement', 'is_invalid', 'is_attribute')
                  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..15c07ea 100644
--- a/bindings/python/tests/cindex/test_diagnostics.py
+++ b/bindings/python/tests/cindex/test_diagnostics.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from clang.cindex import *
 from .util import get_tu
 
diff --git a/bindings/python/tests/cindex/test_file.py b/bindings/python/tests/cindex/test_file.py
index 146e8c5..d40b5d8 100644
--- a/bindings/python/tests/cindex/test_file.py
+++ b/bindings/python/tests/cindex/test_file.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from clang.cindex import Index, File
 
 def test_file():
diff --git a/bindings/python/tests/cindex/test_index.py b/bindings/python/tests/cindex/test_index.py
index dc173f0..fe6d2bc 100644
--- a/bindings/python/tests/cindex/test_index.py
+++ b/bindings/python/tests/cindex/test_index.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from clang.cindex import *
 import os
 
diff --git a/bindings/python/tests/cindex/test_location.py b/bindings/python/tests/cindex/test_location.py
index 9e9ef48..86c9cb9 100644
--- a/bindings/python/tests/cindex/test_location.py
+++ b/bindings/python/tests/cindex/test_location.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from clang.cindex import Cursor
 from clang.cindex import File
 from clang.cindex import SourceLocation
diff --git a/bindings/python/tests/cindex/test_token_kind.py b/bindings/python/tests/cindex/test_token_kind.py
index 62ec63e..c80d4cf 100644
--- a/bindings/python/tests/cindex/test_token_kind.py
+++ b/bindings/python/tests/cindex/test_token_kind.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from clang.cindex import TokenKind
 from nose.tools import eq_
 from nose.tools import ok_
diff --git a/bindings/python/tests/cindex/test_tokens.py b/bindings/python/tests/cindex/test_tokens.py
index 7074842..9945c7b 100644
--- a/bindings/python/tests/cindex/test_tokens.py
+++ b/bindings/python/tests/cindex/test_tokens.py
@@ -1,3 +1,5 @@
+from __future__ import unicode_literals
+
 from clang.cindex import CursorKind
 from clang.cindex import Index
 from clang.cindex import SourceLocation
diff --git a/bindings/python/tests/cindex/test_translation_unit.py b/bindings/python/tests/cindex/test_translation_unit.py
index be6cd67..483dbe8 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
+from io import StringIO
 import tempfile
 
 from clang.cindex import CursorKind
@@ -59,9 +62,8 @@ int SOME_DEFINE;
     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;'))])
+            ('fake.c', StringIO('int x;'))])
     spellings = [c.spelling for c in tu.cursor.get_children()]
     assert spellings[-1] == 'x'
 
@@ -240,7 +242,7 @@ 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 +250,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..295171d 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
@@ -129,7 +131,7 @@ 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():
diff --git a/bindings/python/tests/cindex/util.py b/bindings/python/tests/cindex/util.py
index c53ba7c..a32d9fe 100644
--- a/bindings/python/tests/cindex/util.py
+++ b/bindings/python/tests/cindex/util.py
@@ -1,4 +1,5 @@
 # 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
-- 
2.2.1


From e57be0a9c984a19f29099690171533cb1eaa5140 Mon Sep 17 00:00:00 2001
From: Russell Keith-Magee <russell at keith-magee.com>
Date: Thu, 21 Jan 2016 12:18:59 +0800
Subject: [PATCH 2/4] Modify code formatting for PEP8 compliance.

These changes are (hopefully) uncontroversial fixes for the
following problems identified by flake8.
* E111 4 space indentation
* E201 Whitespace after (
* E231 Whitespace after comma
* E251 Spaces around keyword/parameter equals
* E261 At least 2 spaces before inline comment
* E302 2 blank lines before a method/class definition
* E303 Too many blank lines
* E502 Redundant \
* E712 Comparison to True should be "is true", not "== True"
* W491 Single blank line at end of file
* Unused imports
* Unused variable assignments
---
 bindings/python/clang/cindex.py                    | 139 +++++++++++++--------
 .../python/tests/cindex/test_access_specifiers.py  |   8 +-
 bindings/python/tests/cindex/test_cdb.py           |  25 ++--
 .../python/tests/cindex/test_code_completion.py    |  19 +--
 bindings/python/tests/cindex/test_comment.py       |   3 +-
 bindings/python/tests/cindex/test_cursor.py        |  41 ++++--
 bindings/python/tests/cindex/test_cursor_kind.py   |   3 +
 bindings/python/tests/cindex/test_diagnostics.py   |  12 +-
 bindings/python/tests/cindex/test_file.py          |  13 +-
 bindings/python/tests/cindex/test_index.py         |   4 +-
 bindings/python/tests/cindex/test_location.py      |  25 ++--
 bindings/python/tests/cindex/test_token_kind.py    |   6 +
 bindings/python/tests/cindex/test_tokens.py        |   4 +-
 .../python/tests/cindex/test_translation_unit.py   |  31 ++++-
 bindings/python/tests/cindex/test_type.py          |  60 ++++++---
 bindings/python/tests/cindex/util.py               |   3 +
 16 files changed, 266 insertions(+), 130 deletions(-)

diff --git a/bindings/python/clang/cindex.py b/bindings/python/clang/cindex.py
index 29ece66..e82e9fa 100644
--- a/bindings/python/clang/cindex.py
+++ b/bindings/python/clang/cindex.py
@@ -84,6 +84,7 @@ if sys.version_info.major <= 2:
 else:
     BASESTRING = str
 
+
 ### Exception Classes ###
 
 class TranslationUnitLoadError(Exception):
@@ -96,6 +97,7 @@ class TranslationUnitLoadError(Exception):
     """
     pass
 
+
 class TranslationUnitSaveError(Exception):
     """Represents an error that occurred when saving a TranslationUnit.
 
@@ -126,6 +128,7 @@ class TranslationUnitSaveError(Exception):
         self.save_error = enumeration
         Exception.__init__(self, 'Error %d: %s' % (enumeration, message))
 
+
 ### Structures and Utility Classes ###
 
 class CachedProperty(object):
@@ -166,6 +169,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.
@@ -237,6 +241,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
@@ -281,7 +286,7 @@ 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
+        elif (self.start.file.name != other.file.name or
                other.file.name != self.end.file.name):
             # same file name
             return False
@@ -301,6 +306,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
@@ -396,7 +402,8 @@ class Diagnostic(object):
             self.severity, self.location, self.spelling)
 
     def from_param(self):
-      return self.ptr
+        return self.ptr
+
 
 class FixIt(object):
     """
@@ -412,6 +419,7 @@ class FixIt(object):
     def __repr__(self):
         return "<FixIt range %r, value %r>" % (self.range, self.value)
 
+
 class TokenGroup(object):
     """Helper class to facilitate token management.
 
@@ -467,10 +475,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."""
@@ -504,7 +513,9 @@ class TokenKind(object):
         TokenKind._value_map[value] = kind
         setattr(TokenKind, name, kind)
 
+
 ### Cursor Kinds ###
+
 class BaseEnumeration(object):
     """
     Common base class for named enumerations held in sync with Index.h values.
@@ -527,7 +538,6 @@ class BaseEnumeration(object):
         self.__class__._kinds[value] = self
         self.__class__._name_map = None
 
-
     def from_param(self):
         return self.value
 
@@ -1129,7 +1139,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
@@ -1146,6 +1158,7 @@ TemplateArgumentKind.DECLARATION = TemplateArgumentKind(2)
 TemplateArgumentKind.NULLPTR = TemplateArgumentKind(3)
 TemplateArgumentKind.INTEGRAL = TemplateArgumentKind(4)
 
+
 ### Cursors ###
 
 class Cursor(Structure):
@@ -1349,7 +1362,7 @@ class Cursor(Structure):
         if not hasattr(self, '_underlying_type'):
             assert self.kind.is_declaration()
             self._underlying_type = \
-              conf.lib.clang_getTypedefDeclUnderlyingType(self)
+                conf.lib.clang_getTypedefDeclUnderlyingType(self)
 
         return self._underlying_type
 
@@ -1386,7 +1399,7 @@ class Cursor(Structure):
                                         TypeKind.ULONGLONG,
                                         TypeKind.UINT128):
                 self._enum_value = \
-                  conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
+                    conf.lib.clang_getEnumConstantDeclUnsignedValue(self)
             else:
                 self._enum_value = conf.lib.clang_getEnumConstantDeclValue(self)
         return self._enum_value
@@ -1396,7 +1409,7 @@ class Cursor(Structure):
         """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).decode('utf-8')
+                conf.lib.clang_getDeclObjCTypeEncoding(self).decode('utf-8')
 
         return self._objc_type_encoding
 
@@ -1491,7 +1504,7 @@ 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)
@@ -1572,6 +1585,7 @@ class Cursor(Structure):
         res._tu = args[0]._tu
         return res
 
+
 class StorageClass(object):
     """
     Describes the storage class of a declaration
@@ -1598,8 +1612,8 @@ 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]
 
@@ -1645,6 +1659,7 @@ AccessSpecifier.PROTECTED = AccessSpecifier(2)
 AccessSpecifier.PRIVATE = AccessSpecifier(3)
 AccessSpecifier.NONE = AccessSpecifier(4)
 
+
 ### Type Kinds ###
 
 class TypeKind(BaseEnumeration):
@@ -1714,6 +1729,7 @@ TypeKind.DEPENDENTSIZEDARRAY = TypeKind(116)
 TypeKind.MEMBERPOINTER = TypeKind(117)
 TypeKind.AUTO = TypeKind(118)
 
+
 class RefQualifierKind(BaseEnumeration):
     """Describes a specific ref-qualifier of a type."""
 
@@ -1731,6 +1747,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.
@@ -1769,7 +1786,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:
@@ -1945,7 +1962,7 @@ 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)
@@ -1965,6 +1982,7 @@ class Type(Structure):
     def __ne__(self, other):
         return not self.__eq__(other)
 
+
 ## CIndex Objects ##
 
 # CIndex objects (derived from ClangObject) are essentially lightweight
@@ -1992,29 +2010,30 @@ class _CXUnsavedFile(Structure):
 # for most symboles, we do not need to perform a function call. Their spelling
 # never changes and is consequently provided by this spelling cache.
 SpellingCache = {
-            # 0: CompletionChunk.Kind("Optional"),
-            # 1: CompletionChunk.Kind("TypedText"),
-            # 2: CompletionChunk.Kind("Text"),
-            # 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"),
-            10: '{',  # CompletionChunk.Kind("LeftBrace"),
-            11: '}',  # CompletionChunk.Kind("RightBrace"),
-            12: '<',  # CompletionChunk.Kind("LeftAngle"),
-            13: '>',  # CompletionChunk.Kind("RightAngle"),
-            14: ', ', # CompletionChunk.Kind("Comma"),
-            # 15: CompletionChunk.Kind("ResultType"),
-            16: ':',  # CompletionChunk.Kind("Colon"),
-            17: ';',  # CompletionChunk.Kind("SemiColon"),
-            18: '=',  # CompletionChunk.Kind("Equal"),
-            19: ' ',  # CompletionChunk.Kind("HorizontalSpace"),
-            # 20: CompletionChunk.Kind("VerticalSpace")
+            # 0:         CompletionChunk.Kind("Optional"),
+            # 1:         CompletionChunk.Kind("TypedText"),
+            # 2:         CompletionChunk.Kind("Text"),
+            # 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"),
+            10: '{',   # CompletionChunk.Kind("LeftBrace"),
+            11: '}',   # CompletionChunk.Kind("RightBrace"),
+            12: '<',   # CompletionChunk.Kind("LeftAngle"),
+            13: '>',   # CompletionChunk.Kind("RightAngle"),
+            14: ', ',  # CompletionChunk.Kind("Comma"),
+            # 15:        CompletionChunk.Kind("ResultType"),
+            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):
@@ -2060,24 +2079,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"),
@@ -2102,6 +2122,7 @@ completionChunkKindMap = {
             19: CompletionChunk.Kind("HorizontalSpace"),
             20: CompletionChunk.Kind("VerticalSpace")}
 
+
 class CompletionString(ClangObject):
     class Availability:
         def __init__(self, name):
@@ -2153,6 +2174,7 @@ availabilityKinds = {
             2: CompletionChunk.Kind("NotAvailable"),
             3: CompletionChunk.Kind("NotAccessible")}
 
+
 class CodeCompletionResult(Structure):
     _fields_ = [('cursorKind', c_int), ('completionString', c_object_p)]
 
@@ -2167,6 +2189,7 @@ class CodeCompletionResult(Structure):
     def string(self):
         return CompletionString(self.completionString)
 
+
 class CCRStructure(Structure):
     _fields_ = [('results', POINTER(CodeCompletionResult)),
                 ('numResults', c_int)]
@@ -2180,6 +2203,7 @@ class CCRStructure(Structure):
 
         return self.results[key]
 
+
 class CodeCompletionResults(ClangObject):
     def __init__(self, ptr):
         assert isinstance(ptr, POINTER(CCRStructure)) and ptr
@@ -2199,11 +2223,11 @@ 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)
@@ -2234,7 +2258,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.
@@ -2250,6 +2274,7 @@ class Index(ClangObject):
         return TranslationUnit.from_source(path, args, unsaved_files, options,
                                            self)
 
+
 class TranslationUnit(ClangObject):
     """Represents a source code translation unit.
 
@@ -2529,7 +2554,7 @@ 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.
@@ -2540,7 +2565,7 @@ class TranslationUnit(ClangObject):
                 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),
+        conf.lib.clang_reparseTranslationUnit(self, len(unsaved_files),
                 unsaved_files_array, options)
 
     def save(self, filename):
@@ -2593,7 +2618,7 @@ 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, BASESTRING):
                     # FIXME: It would be great to support an efficient version
                     # of this, one day.
@@ -2625,6 +2650,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
@@ -2660,6 +2686,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
@@ -2680,6 +2707,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
 
@@ -2705,6 +2733,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):
@@ -2730,6 +2759,7 @@ class CompileCommand(object):
         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
@@ -2756,6 +2786,7 @@ class CompileCommands(object):
             return None
         return CompileCommands(res)
 
+
 class CompilationDatabase(ClangObject):
     """
     The CompilationDatabase is a wrapper class around
@@ -2782,7 +2813,7 @@ class CompilationDatabase(ClangObject):
             cdb = conf.lib.clang_CompilationDatabase_fromDirectory(
                 buildDir.encode('utf-8'), byref(errorCode)
             )
-        except CompilationDatabaseError as e:
+        except CompilationDatabaseError:
             raise CompilationDatabaseError(int(errorCode.value),
                                            "CompilationDatabase loading failed")
         return cdb
@@ -3188,7 +3219,7 @@ functionList = [
 
   ("clang_getFileName",
    [File],
-   _CXString), # TODO go through _CXString.from_result?
+   _CXString),  # TODO go through _CXString.from_result?
 
   ("clang_getFileTime",
    [File],
@@ -3499,6 +3530,7 @@ functionList = [
    c_uint),
 ]
 
+
 class LibclangError(Exception):
     def __init__(self, message):
         self.m = message
@@ -3506,6 +3538,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.
@@ -3527,6 +3560,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.
 
@@ -3555,7 +3589,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
@@ -3564,7 +3598,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
@@ -3588,7 +3622,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
@@ -3638,6 +3672,7 @@ class Config:
 
         return True
 
+
 def register_enumerations():
     for name, value in clang.enumerations.TokenKinds:
         TokenKind.register(value, name)
diff --git a/bindings/python/tests/cindex/test_access_specifiers.py b/bindings/python/tests/cindex/test_access_specifiers.py
index 6d9b1bb..f5a2fef 100644
--- a/bindings/python/tests/cindex/test_access_specifiers.py
+++ b/bindings/python/tests/cindex/test_access_specifiers.py
@@ -1,12 +1,11 @@
 from __future__ import unicode_literals
 
 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"""
 
@@ -19,10 +18,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
@@ -32,4 +31,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 2457632..8fa1d0b 100644
--- a/bindings/python/tests/cindex/test_cdb.py
+++ b/bindings/python/tests/cindex/test_cdb.py
@@ -2,38 +2,41 @@ 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') is None
 
+
 def test_lookup_succeed():
     """Check we get some results if the file exists in the db"""
     cdb = CompilationDatabase.fromDirectory(kInputsDir)
     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)
@@ -71,6 +74,7 @@ def test_all_compilecommand():
         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)
@@ -85,6 +89,7 @@ def test_1_compilecommand():
     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)
@@ -114,6 +119,7 @@ def test_2_compilecommand():
         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)
@@ -122,13 +128,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"""
@@ -138,5 +146,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 84ba62a..f082df5 100644
--- a/bindings/python/tests/cindex/test_code_completion.py
+++ b/bindings/python/tests/cindex/test_code_completion.py
@@ -2,6 +2,7 @@ from __future__ import unicode_literals
 
 from clang.cindex import TranslationUnit
 
+
 def check_completion_results(cr, expected):
     assert cr is not None
     assert len(cr.diagnostics) == 0
@@ -11,6 +12,7 @@ def check_completion_results(cr, expected):
     for c in expected:
         assert c in completions, "Couldn't find '%s'" % c
 
+
 def test_code_complete():
     files = [('fake.c', """
 /// Aaa.
@@ -30,12 +32,13 @@ void f() {
     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 {
@@ -59,11 +62,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 f7e1087..50cc0e2 100644
--- a/bindings/python/tests/cindex/test_comment.py
+++ b/bindings/python/tests/cindex/test_comment.py
@@ -3,6 +3,7 @@ from __future__ import unicode_literals
 from clang.cindex import TranslationUnit
 from tests.cindex.util import get_cursor
 
+
 def test_comment():
     files = [('fake.c', """
 /// Aaa.
@@ -38,5 +39,3 @@ void f() {
     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 7c8b2cc..78dc7f2 100644
--- a/bindings/python/tests/cindex/test_cursor.py
+++ b/bindings/python/tests/cindex/test_cursor.py
@@ -1,6 +1,5 @@
 from __future__ import unicode_literals
 
-import ctypes
 import gc
 
 from clang.cindex import CursorKind
@@ -31,6 +30,7 @@ void f0(int a0, int a1) {
 }
 """
 
+
 def test_get_children():
     tu = get_tu(kInput)
 
@@ -44,7 +44,7 @@ def test_get_children():
     assert tu_nodes[0] != tu_nodes[1]
     assert tu_nodes[0].kind == CursorKind.STRUCT_DECL
     assert tu_nodes[0].spelling == 's0'
-    assert tu_nodes[0].is_definition() == True
+    assert tu_nodes[0].is_definition() is True
     assert tu_nodes[0].location.file.name == 't.c'
     assert tu_nodes[0].location.line == 1
     assert tu_nodes[0].location.column == 8
@@ -63,12 +63,13 @@ def test_get_children():
     assert tu_nodes[1].kind == CursorKind.STRUCT_DECL
     assert tu_nodes[1].spelling == 's1'
     assert tu_nodes[1].displayname == 's1'
-    assert tu_nodes[1].is_definition() == False
+    assert tu_nodes[1].is_definition() is False
 
     assert tu_nodes[2].kind == CursorKind.FUNCTION_DECL
     assert tu_nodes[2].spelling == 'f0'
     assert tu_nodes[2].displayname == 'f0(int, int)'
-    assert tu_nodes[2].is_definition() == True
+    assert tu_nodes[2].is_definition() is True
+
 
 def test_references():
     """Ensure that references to TranslationUnit are kept."""
@@ -85,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; };'
@@ -99,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(); };'
@@ -114,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_; };'
@@ -129,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."""
 
@@ -145,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(); };'
@@ -160,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(); };'
@@ -175,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')
@@ -191,6 +199,8 @@ kParentTest = """\
 
         void C::f() { }
     """
+
+
 def test_semantic_parent():
     tu = get_tu(kParentTest, 'cpp')
     curs = get_cursors(tu, 'f')
@@ -199,6 +209,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')
@@ -208,6 +219,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')
@@ -217,6 +229,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')
@@ -225,6 +238,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')
@@ -232,6 +246,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')
@@ -251,6 +266,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')
@@ -268,6 +284,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")));')
 
@@ -281,6 +298,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')
@@ -289,6 +307,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);')
@@ -299,6 +318,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')
@@ -316,12 +336,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')
@@ -330,25 +352,29 @@ 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')
 
     assert foos[1].get_template_argument_value(0) == -7
-    assert foos[1].get_template_argument_value(2) == True
+    assert foos[1].get_template_argument_value(2) == 1
+
 
 def test_get_template_argument_unsigned_value():
     tu = get_tu(kTemplateArgTest, lang='cpp')
     foos = get_cursors(tu, 'foo')
 
     assert foos[1].get_template_argument_unsigned_value(0) == 2 ** 32 - 7
-    assert foos[1].get_template_argument_unsigned_value(2) == True
+    assert foos[1].get_template_argument_unsigned_value(2) == 1
+
 
 def test_referenced():
     tu = get_tu('void foo(); void bar() { foo(); }')
@@ -359,6 +385,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 1a09f36..93b127d 100644
--- a/bindings/python/tests/cindex/test_cursor_kind.py
+++ b/bindings/python/tests/cindex/test_cursor_kind.py
@@ -2,9 +2,11 @@ from __future__ import unicode_literals
 
 from clang.cindex import CursorKind
 
+
 def test_name():
     assert CursorKind.UNEXPOSED_DECL.name == 'UNEXPOSED_DECL'
 
+
 def test_get_all_kinds():
     kinds = CursorKind.get_all_kinds()
     assert CursorKind.UNEXPOSED_DECL in kinds
@@ -17,6 +19,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."""
 
diff --git a/bindings/python/tests/cindex/test_diagnostics.py b/bindings/python/tests/cindex/test_diagnostics.py
index 15c07ea..8007c4c 100644
--- a/bindings/python/tests/cindex/test_diagnostics.py
+++ b/bindings/python/tests/cindex/test_diagnostics.py
@@ -5,6 +5,7 @@ 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
@@ -14,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')
@@ -27,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
@@ -41,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
@@ -55,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."""
@@ -74,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 d40b5d8..8751429 100644
--- a/bindings/python/tests/cindex/test_file.py
+++ b/bindings/python/tests/cindex/test_file.py
@@ -2,10 +2,11 @@ from __future__ import unicode_literals
 
 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_index.py b/bindings/python/tests/cindex/test_index.py
index fe6d2bc..c5eabbd 100644
--- a/bindings/python/tests/cindex/test_index.py
+++ b/bindings/python/tests/cindex/test_index.py
@@ -5,8 +5,10 @@ import os
 
 kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
 
+
 def test_create():
-    index = Index.create()
+    Index.create()
+
 
 # FIXME: test Index.read
 
diff --git a/bindings/python/tests/cindex/test_location.py b/bindings/python/tests/cindex/test_location.py
index 86c9cb9..85e5b33 100644
--- a/bindings/python/tests/cindex/test_location.py
+++ b/bindings/python/tests/cindex/test_location.py
@@ -7,13 +7,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')
@@ -22,8 +24,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)
@@ -33,16 +35,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
@@ -71,17 +73,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_token_kind.py b/bindings/python/tests/cindex/test_token_kind.py
index c80d4cf..60cd22c 100644
--- a/bindings/python/tests/cindex/test_token_kind.py
+++ b/bindings/python/tests/cindex/test_token_kind.py
@@ -5,6 +5,7 @@ from nose.tools import eq_
 from nose.tools import ok_
 from nose.tools import raises
 
+
 def test_constructor():
     """Ensure TokenKind constructor works as expected."""
 
@@ -13,18 +14,21 @@ def test_constructor():
     eq_(t.value, 5)
     eq_(t.name, 'foo')
 
+
 @raises(ValueError)
 def test_bad_register():
     """Ensure a duplicate value is rejected for registration."""
 
     TokenKind.register(2, 'foo')
 
+
 @raises(ValueError)
 def test_unknown_value():
     """Ensure trying to fetch an unknown value raises."""
 
     TokenKind.from_value(-1)
 
+
 def test_registration():
     """Ensure that items registered appear as class attributes."""
     ok_(hasattr(TokenKind, 'LITERAL'))
@@ -32,12 +36,14 @@ def test_registration():
 
     ok_(isinstance(literal, TokenKind))
 
+
 def test_from_value():
     """Ensure registered values can be obtained from from_value()."""
     t = TokenKind.from_value(3)
     ok_(isinstance(t, TokenKind))
     eq_(t, TokenKind.LITERAL)
 
+
 def test_repr():
     """Ensure repr() works."""
 
diff --git a/bindings/python/tests/cindex/test_tokens.py b/bindings/python/tests/cindex/test_tokens.py
index 9945c7b..adfe071 100644
--- a/bindings/python/tests/cindex/test_tokens.py
+++ b/bindings/python/tests/cindex/test_tokens.py
@@ -1,7 +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
@@ -10,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;')
@@ -24,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."""
 
@@ -39,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 483dbe8..c35739b 100644
--- a/bindings/python/tests/cindex/test_translation_unit.py
+++ b/bindings/python/tests/cindex/test_translation_unit.py
@@ -19,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)
@@ -31,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'])
@@ -38,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'])
@@ -46,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;
@@ -61,22 +66,25 @@ int SOME_DEFINE;
     assert spellings[-2] == 'x'
     assert spellings[-1] == 'y'
 
+
 def test_unsaved_files_2():
-    tu = TranslationUnit.from_source('fake.c', unsaved_files = [
+    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 \
+            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)
@@ -91,6 +99,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.
 
@@ -101,6 +110,7 @@ def save_tu(tu):
 
     return path
 
+
 def test_save():
     """Ensure TranslationUnit.save() works."""
 
@@ -111,6 +121,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."""
 
@@ -126,6 +137,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."""
 
@@ -147,12 +159,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."""
 
@@ -169,6 +183,7 @@ def test_get_file():
     else:
         assert False
 
+
 def test_get_source_location():
     """Ensure tu.get_source_location() works."""
 
@@ -185,19 +200,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
@@ -216,6 +232,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."""
 
@@ -234,7 +251,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')
@@ -244,6 +262,7 @@ def test_fail_from_source():
         tu = None
     assert tu is None
 
+
 def test_fail_from_ast_file():
     path = os.path.join(kInputsDir, 'non-existent.ast')
     try:
diff --git a/bindings/python/tests/cindex/test_type.py b/bindings/python/tests/cindex/test_type.py
index 295171d..30bc620 100644
--- a/bindings/python/tests/cindex/test_type.py
+++ b/bindings/python/tests/cindex/test_type.py
@@ -26,6 +26,7 @@ struct teststruct {
 
 """
 
+
 def test_a_struct():
     tu = get_tu(kInput)
 
@@ -78,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."""
 
@@ -96,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)
 
@@ -115,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;'
@@ -134,6 +140,7 @@ def test_equal():
     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];')
@@ -150,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;')
@@ -158,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);')
@@ -181,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."""
@@ -193,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."""
@@ -202,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."""
@@ -211,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."""
@@ -220,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();')
@@ -232,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, ...);
@@ -253,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];')
@@ -270,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."""
@@ -278,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;')
@@ -295,6 +313,7 @@ def test_element_count():
     except:
         assert True
 
+
 def test_is_volatile_qualified():
     """Ensure Type.is_volatile_qualified works."""
 
@@ -310,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."""
 
@@ -325,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;
@@ -337,12 +358,12 @@ 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')
@@ -354,16 +375,17 @@ struct a {
         assert teststruct.type.get_offset(fields[1].spelling) == a2
         assert teststruct.type.get_offset(fields[2].spelling) == a3
         assert teststruct.type.get_offset(fields[3].spelling) == a4
-        assert fields[0].is_bitfield() == False
-        assert fields[1].is_bitfield() == True
+        assert fields[0].is_bitfield() is False
+        assert fields[1].is_bitfield() is True
         assert fields[1].get_bitfield_width() == 3
-        assert fields[2].is_bitfield() == True
+        assert fields[2].is_bitfield() is True
         assert fields[2].get_bitfield_width() == 4
-        assert fields[3].is_bitfield() == False
+        assert fields[3].is_bitfield() is False
+
 
 def test_offset():
     """Ensure Cursor.get_record_field_offset works in anonymous records"""
-    source="""
+    source = """
 struct Test {
   struct {int a;} typeanon;
   struct {
@@ -374,12 +396,12 @@ 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 a32d9fe..504419a 100644
--- a/bindings/python/tests/cindex/util.py
+++ b/bindings/python/tests/cindex/util.py
@@ -4,6 +4,7 @@ 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.
 
@@ -31,6 +32,7 @@ def get_tu(source, lang='c', all_warnings=False, flags=[]):
     return TranslationUnit.from_source(name, args, unsaved_files=[(name,
                                        source)])
 
+
 def get_cursor(source, spelling):
     """Obtain a cursor from a source object.
 
@@ -49,6 +51,7 @@ def get_cursor(source, spelling):
 
     return None
 
+
 def get_cursors(source, spelling):
     """Obtain all cursors from a source object with a specific spelling.
 
-- 
2.2.1


From 68f020fd69c942b475247e4cbe9e322ad3953edf Mon Sep 17 00:00:00 2001
From: Russell Keith-Magee <russell at keith-magee.com>
Date: Thu, 21 Jan 2016 12:20:25 +0800
Subject: [PATCH 3/4] Added a setup.py file so that the Python bindings can be
 installed.

I would encourage the LLVM maintainers to use this setup.py
to register the package on PyPI, as is the convention for Python tools.
---
 bindings/python/setup.py | 34 ++++++++++++++++++++++++++++++++++
 1 file changed, 34 insertions(+)
 create mode 100644 bindings/python/setup.py

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']
+)
-- 
2.2.1


From 194dadb51ad8c80d8988ad4e8afe0063beb8cedc Mon Sep 17 00:00:00 2001
From: Russell Keith-Magee <russell at keith-magee.com>
Date: Thu, 21 Jan 2016 12:35:33 +0800
Subject: [PATCH 4/4] More controversial PEP8 formatting fixes.

These fixes address E128 Continuation line under-indented for visual indent,
as well as adopting a more Pythonic approach to long lines and data
indentation.
---
 bindings/python/clang/cindex.py                    | 1551 +++++++++++---------
 .../python/tests/cindex/test_code_completion.py    |    7 +-
 bindings/python/tests/cindex/test_comment.py       |    7 +-
 .../python/tests/cindex/test_translation_unit.py   |    6 +-
 bindings/python/tests/cindex/test_type.py          |   20 +-
 5 files changed, 892 insertions(+), 699 deletions(-)

diff --git a/bindings/python/clang/cindex.py b/bindings/python/clang/cindex.py
index e82e9fa..bd857d6 100644
--- a/bindings/python/clang/cindex.py
+++ b/bindings/python/clang/cindex.py
@@ -180,8 +180,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:
@@ -286,8 +287,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
@@ -365,8 +366,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
 
@@ -399,7 +401,8 @@ class Diagnostic(object):
 
     def __repr__(self):
         return "<Diagnostic severity %r, location %r, spelling %r>" % (
-            self.severity, self.location, self.spelling)
+            self.severity, self.location, self.spelling
+        )
 
     def from_param(self):
         return self.ptr
@@ -452,8 +455,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)
 
@@ -533,7 +537,8 @@ class BaseEnumeration(object):
             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))
+                str(self.__class__), value)
+            )
         self.value = value
         self.__class__._kinds[value] = self
         self.__class__._name_map = None
@@ -1166,7 +1171,11 @@ class Cursor(Structure):
     The Cursor class represents a reference to an element within the AST. It
     acts as a kind of iterator.
     """
-    _fields_ = [("_kind_id", c_int), ("xdata", c_int), ("data", c_void_p * 3)]
+    _fields_ = [
+        ("_kind_id", c_int),
+        ("xdata", c_int),
+        ("data", c_void_p * 3)
+    ]
 
     @staticmethod
     def from_location(tu, location):
@@ -1506,8 +1515,9 @@ class Cursor(Structure):
             children.append(child)
             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):
@@ -1626,6 +1636,7 @@ class StorageClass(object):
     def __repr__(self):
         return 'StorageClass.%s' % (self.name,)
 
+
 StorageClass.INVALID = StorageClass(0)
 StorageClass.NONE = StorageClass(1)
 StorageClass.EXTERN = StorageClass(2)
@@ -1653,6 +1664,7 @@ class AccessSpecifier(BaseEnumeration):
     def __repr__(self):
         return 'AccessSpecifier.%s' % (self.name,)
 
+
 AccessSpecifier.INVALID = AccessSpecifier(0)
 AccessSpecifier.PUBLIC = AccessSpecifier(1)
 AccessSpecifier.PROTECTED = AccessSpecifier(2)
@@ -1679,6 +1691,7 @@ class TypeKind(BaseEnumeration):
     def __repr__(self):
         return 'TypeKind.%s' % (self.name,)
 
+
 TypeKind.INVALID = TypeKind(0)
 TypeKind.UNEXPOSED = TypeKind(1)
 TypeKind.VOID = TypeKind(2)
@@ -1743,6 +1756,7 @@ class RefQualifierKind(BaseEnumeration):
     def __repr__(self):
         return 'RefQualifierKind.%s' % (self.name,)
 
+
 RefQualifierKind.NONE = RefQualifierKind(0)
 RefQualifierKind.LVALUE = RefQualifierKind(1)
 RefQualifierKind.RVALUE = RefQualifierKind(2)
@@ -1785,8 +1799,9 @@ class Type(Structure):
                     raise IndexError("Only non-negative indexes are accepted.")
 
                 if key >= len(self):
-                    raise IndexError("Index greater than container length: "
-                                     "%d > %d" % (key, len(self)))
+                    raise IndexError(
+                        "Index greater than container length: %d > %d" % (key, len(self))
+                    )
 
                 result = conf.lib.clang_getArgType(self.parent, key)
                 if result.kind == TypeKind.INVALID:
@@ -1944,7 +1959,9 @@ class Type(Structure):
         """
         Retrieve the offset of a field in the record.
         """
-        return conf.lib.clang_Type_getOffsetOf(self, c_char_p(fieldname.encode('utf-8')))
+        return conf.lib.clang_Type_getOffsetOf(
+            self, c_char_p(fieldname.encode('utf-8'))
+        )
 
     def get_ref_qualifier(self):
         """
@@ -1964,8 +1981,9 @@ class Type(Structure):
             fields.append(field)
             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
@@ -2004,7 +2022,11 @@ class ClangObject(object):
 
 class _CXUnsavedFile(Structure):
     """Helper for passing unsaved file arguments."""
-    _fields_ = [("name", c_char_p), ("contents", c_char_p), ('length', c_ulong)]
+    _fields_ = [
+        ("name", c_char_p),
+        ("contents", c_char_p),
+        ('length', c_ulong)
+    ]
 
 # Functions calls through the python interface are rather slow. Fortunately,
 # for most symboles, we do not need to perform a function call. Their spelling
@@ -2075,8 +2097,7 @@ class CompletionChunk:
 
     @CachedProperty
     def string(self):
-        res = conf.lib.clang_getCompletionChunkCompletionString(self.cs,
-                                                                self.key)
+        res = conf.lib.clang_getCompletionChunkCompletionString(self.cs, self.key)
 
         if (res):
             return CompletionString(res)
@@ -2226,8 +2247,7 @@ class CodeCompletionResults(ClangObject):
                 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)
@@ -2271,8 +2291,7 @@ class Index(ClangObject):
         If an error was encountered during parsing, a TranslationUnitLoadError
         will be raised.
         """
-        return TranslationUnit.from_source(path, args, unsaved_files, options,
-                                           self)
+        return TranslationUnit.from_source(path, args, unsaved_files, options, self)
 
 
 class TranslationUnit(ClangObject):
@@ -2453,8 +2472,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)
 
@@ -2502,15 +2522,18 @@ 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)
 
@@ -2565,8 +2588,9 @@ class TranslationUnit(ClangObject):
                 unsaved_files_array[i].name = name
                 unsaved_files_array[i].contents = value
                 unsaved_files_array[i].length = len(value)
-        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.
@@ -2584,11 +2608,13 @@ 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.encode('utf-8'),
-                                                        options))
+        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,
@@ -2801,8 +2827,7 @@ class CompilationDatabase(ClangObject):
     @staticmethod
     def from_result(res, fn, args):
         if not res:
-            raise CompilationDatabaseError(0,
-                                           "CompilationDatabase loading failed")
+            raise CompilationDatabaseError(0, "CompilationDatabase loading failed")
         return CompilationDatabase(res)
 
     @staticmethod
@@ -2814,8 +2839,10 @@ class CompilationDatabase(ClangObject):
                 buildDir.encode('utf-8'), byref(errorCode)
             )
         except CompilationDatabaseError:
-            raise CompilationDatabaseError(int(errorCode.value),
-                                           "CompilationDatabase loading failed")
+            raise CompilationDatabaseError(
+                int(errorCode.value),
+                "CompilationDatabase loading failed"
+            )
         return cdb
 
     def getCompileCommands(self, filename):
@@ -2823,8 +2850,9 @@ class CompilationDatabase(ClangObject):
         Get an iterable object providing all the CompileCommands available to
         build filename. Returns None if filename is not found in the database.
         """
-        return conf.lib.clang_CompilationDatabase_getCompileCommands(self,
-                                                                     filename.encode('utf-8'))
+        return conf.lib.clang_CompilationDatabase_getCompileCommands(
+            self, filename.encode('utf-8')
+        )
 
     def getAllCompileCommands(self):
         """
@@ -2883,651 +2911,804 @@ 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
+    ),
 ]
 
 
diff --git a/bindings/python/tests/cindex/test_code_completion.py b/bindings/python/tests/cindex/test_code_completion.py
index f082df5..4c11808 100644
--- a/bindings/python/tests/cindex/test_code_completion.py
+++ b/bindings/python/tests/cindex/test_code_completion.py
@@ -26,8 +26,11 @@ 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)
 
diff --git a/bindings/python/tests/cindex/test_comment.py b/bindings/python/tests/cindex/test_comment.py
index 50cc0e2..f644e66 100644
--- a/bindings/python/tests/cindex/test_comment.py
+++ b/bindings/python/tests/cindex/test_comment.py
@@ -18,8 +18,11 @@ 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()
diff --git a/bindings/python/tests/cindex/test_translation_unit.py b/bindings/python/tests/cindex/test_translation_unit.py
index c35739b..7fa4830 100644
--- a/bindings/python/tests/cindex/test_translation_unit.py
+++ b/bindings/python/tests/cindex/test_translation_unit.py
@@ -84,8 +84,10 @@ def normpaths_equal(path1, 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)
 
diff --git a/bindings/python/tests/cindex/test_type.py b/bindings/python/tests/cindex/test_type.py
index 30bc620..5d6d61d 100644
--- a/bindings/python/tests/cindex/test_type.py
+++ b/bindings/python/tests/cindex/test_type.py
@@ -358,10 +358,12 @@ 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
 
@@ -396,10 +398,12 @@ 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
         tu = get_tu(source)
-- 
2.2.1



More information about the cfe-commits mailing list