Repository: timothycrosley/isort (python)

Issue:
Update isort to follow pyi (stub files) standards, in similar fashion to black
Currently, isort is unaware of the differences between the established coding standards for `.py` files and `.pyi` files, treating them the same. This ticket represents updating isort to be aware of these differences, in particular for `.pyi` files and follow the appropriate standard for the given file type. https://github.com/python/typeshed/blob/master/CONTRIBUTING.md#stub-file-coding-style provides a good initial intro to the `.pyi` specific standards.

In particular, any resolution to this ticket should resolve the incompatibility with Black outlined here: https://github.com/python/black/issues/837


Pull request:
Issue/942
Fixes #942 

Patch:
diff --git a/CHANGELOG.md b/CHANGELOG.md
index df5ecd4f..9d97c9da 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,6 +1,9 @@
 Changelog
 =========
 
+### 4.3.19 - May 12, 2019 - hot fix release
+- Fixed issue #942 - correctly handle pyi (Python Template Files) to match `black` output
+
 ### 4.3.18 - May 1, 2019 - hot fix release
 - Fixed an issue with parsing files that contain unicode characters in Python 2
 - Fixed issue #924 - Pulling in pip internals causes depreciation warning
diff --git a/isort/__init__.py b/isort/__init__.py
index c080bb9d..581a6ddb 100644
--- a/isort/__init__.py
+++ b/isort/__init__.py
@@ -25,4 +25,4 @@ from __future__ import absolute_import, division, print_function, unicode_litera
 from . import settings  # noqa: F401
 from .isort import SortImports  # noqa: F401
 
-__version__ = "4.3.18"
+__version__ = "4.3.19"
diff --git a/isort/isort.py b/isort/isort.py
index 991aed51..3ab68c2d 100644
--- a/isort/isort.py
+++ b/isort/isort.py
@@ -49,7 +49,7 @@ class SortImports(object):
 
     def __init__(self, file_path=None, file_contents=None, file_=None, write_to_stdout=False, check=False,
                  show_diff=False, settings_path=None, ask_to_apply=False, run_path='', check_skip=True,
-                 **setting_overrides):
+                 extension=None, **setting_overrides):
         if not settings_path and file_path:
             settings_path = os.path.dirname(os.path.abspath(file_path))
         settings_path = settings_path or os.getcwd()
@@ -181,6 +181,11 @@ class SortImports(object):
                 self.in_lines.append(add_import)
         self.number_of_lines = len(self.in_lines)
 
+        if not extension:
+            self.extension = file_name.split('.')[-1] if file_name else "py"
+        else:
+            self.extension = extension
+
         self.out_lines = []
         self.comments = {'from': {}, 'straight': {}, 'nested': {}, 'above': {'straight': {}, 'from': {}}}
         self.imports = OrderedDict()
@@ -672,8 +677,10 @@ class SortImports(object):
 
             if self.config['lines_after_imports'] != -1:
                 self.out_lines[imports_tail:0] = ["" for line in range(self.config['lines_after_imports'])]
-            elif next_construct.startswith("def ") or next_construct.startswith("class ") or \
-               next_construct.startswith("@") or next_construct.startswith("async def"):
+            elif self.extension != "pyi" and (next_construct.startswith("def ") or
+                                              next_construct.startswith("class ") or
+                                              next_construct.startswith("@") or
+                                              next_construct.startswith("async def")):
                 self.out_lines[imports_tail:0] = ["", ""]
             else:
                 self.out_lines[imports_tail:0] = [""]
diff --git a/setup.py b/setup.py
index 1c8cc85f..72a165e2 100755
--- a/setup.py
+++ b/setup.py
@@ -6,7 +6,7 @@ with open('README.rst') as f:
     readme = f.read()
 
 setup(name='isort',
-      version='4.3.18',
+      version='4.3.19',
       description='A Python utility / library to sort Python imports.',
       long_description=readme,
       author='Timothy Crosley',


Test patch:
diff --git a/test_isort.py b/test_isort.py
index 8768a26f..911a5b5e 100644
--- a/test_isort.py
+++ b/test_isort.py
@@ -2994,3 +2994,25 @@ def test_import_heading_issue_905():
                   '# Local imports\n'
                   'from oklib.plot_ok import imagesc\n')
     assert SortImports(file_contents=test_input, **config).output == test_input
+
+
+def test_pyi_formatting_issue_942(tmpdir):
+    test_input = ('import os\n'
+                  '\n'
+                  '\n'
+                  'def my_method():\n')
+    expected_py_output = test_input.splitlines()
+    expected_pyi_output = ('import os\n'
+                           '\n'
+                           'def my_method():\n').splitlines()
+    assert SortImports(file_contents=test_input).output.splitlines() == expected_py_output
+    assert SortImports(file_contents=test_input,
+                       extension="pyi").output.splitlines() == expected_pyi_output
+
+    source_py = tmpdir.join('source.py')
+    source_py.write(test_input)
+    assert SortImports(file_path=str(source_py)).output.splitlines() == expected_py_output
+
+    source_pyi = tmpdir.join('source.pyi')
+    source_pyi.write(test_input)
+    assert SortImports(file_path=str(source_pyi)).output.splitlines() == expected_pyi_output