Repository: timothycrosley/isort
Pull request #514 (2017-05-21 01:16:40)

Feature/fix issue 432


Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 20ea586e..3a2c5ac8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -67,4 +67,5 @@ Changelog
 - Added `--virtual-env` switch command line option
 
 ### 4.2.8 - In progress
-- Fixed issue #299, long lines occasionally not wrapped
+- Fixed issue #299: long lines occasionally not wrapped
+- Fixed issue #432: No longer add import inside class when class starts at top of file after encoding comment
diff --git a/isort/isort.py b/isort/isort.py
index eb89959d..a1f466c2 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -538,7 +538,7 @@ class SortImports(object):
                 section_title = self.config.get('import_heading_' + str(section_name).lower(), '')
                 if section_title:
                     section_comment = "# {0}".format(section_title)
-                    if not section_comment in self.out_lines[0:1]:
+                    if not section_comment in self.out_lines[0:1] and not section_comment in self.in_lines[0:1]:
                         section_output.insert(0, section_comment)
                 output += section_output + ([''] * self.config['lines_between_sections'])
 
@@ -714,7 +714,7 @@ class SortImports(object):
         elif self._in_top_comment:
             if not line.startswith("#"):
                 self._in_top_comment = False
-                self._first_comment_index_end = self.index
+                self._first_comment_index_end = self.index - 1
 
         if '"' in line or "'" in line:
             index = 0
@@ -855,12 +855,12 @@ class SortImports(object):
                     if comments:
                         self.comments['from'].setdefault(import_from, []).extend(comments)
 
-                    if len(self.out_lines) > max(self.import_index, self._first_comment_index_end, 1) - 1:
+                    if len(self.out_lines) > max(self.import_index, self._first_comment_index_end + 1, 1) - 1:
                         last = self.out_lines and self.out_lines[-1].rstrip() or ""
                         while (last.startswith("#") and not last.endswith('"""') and not last.endswith("'''") and not
                                'isort:imports-' in last):
                             self.comments['above']['from'].setdefault(import_from, []).insert(0, self.out_lines.pop(-1))
-                            if len(self.out_lines) > max(self.import_index - 1, self._first_comment_index_end, 1) - 1:
+                            if len(self.out_lines) > max(self.import_index - 1, self._first_comment_index_end + 1, 1) - 1:
                                 last = self.out_lines[-1].rstrip()
                             else:
                                 last = ""


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 72b69d48..827e3c8f 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -1641,6 +1641,7 @@ def test_top_of_line_comments():
                    '\n'
                    'import logging\n')
     output = SortImports(file_contents=test_input).output
+    print(output)
     assert output.startswith('# -*- coding: utf-8 -*-\n')
 
 
@@ -1946,3 +1947,17 @@ def test_long_single_line():
         assert len(line) <= 79
 
 
+def test_import_inside_class_issue_432():
+    """Test to ensure issue 432 is resolved and isort doesn't insert imports in the middle of classes"""
+    test_input = ("# coding=utf-8\n"
+                  "class Foo:\n"
+                  "    def bar(self):\n"
+                  "        pass\n")
+    expected_output = ("# coding=utf-8\n"
+                       "import baz\n"
+                       "\n"
+                       "\n"
+                       "class Foo:\n"
+                       "    def bar(self):\n"
+                       "        pass\n")
+    assert SortImports(file_contents=test_input, add_imports=['import baz']).output == expected_output