Codebase list isort / 37df17b
New upstream version 5.4.2 Tristan Seligmann 3 years ago
14 changed file(s) with 215 addition(s) and 36 deletion(s). Raw diff Collapse all Expand all
00 Metadata-Version: 2.1
11 Name: isort
2 Version: 5.3.2
2 Version: 5.4.2
33 Summary: A Python utility / library to sort Python imports.
44 Home-page: https://timothycrosley.github.io/isort/
55 License: MIT
289289 ...
290290 ```
291291
292 **8 - Vertical Hanging Indent Bracket**
293
294 Same as Mode 3 - _Vertical Hanging Indent_ but the closing parentheses
295 on the last line is indented.
296
297 ```python
298 from third_party import (
299 lib1,
300 lib2,
301 lib3,
302 lib4,
303 )
304 ```
305
306 **9 - Vertical Prefix From Module Import**
307
308 Starts a new line with the same `from MODULE import ` prefix when lines are longer than the line length limit.
309
310 ```python
311 from third_party import lib1, lib2, lib3
312 from third_party import lib4, lib5, lib6
313 ```
314
315 **10 - Hanging Indent With Parentheses**
316
317 Same as Mode 2 - _Hanging Indent_ but uses parentheses instead of backslash
318 for wrapping long lines.
319
320 ```python
321 from third_party import (
322 lib1, lib2, lib3,
323 lib4, lib5, lib6)
324 ```
325
292326 Note: to change the how constant indents appear - simply change the
293327 indent property with the following accepted formats:
294328
250250 ...
251251 ```
252252
253 **8 - Vertical Hanging Indent Bracket**
254
255 Same as Mode 3 - _Vertical Hanging Indent_ but the closing parentheses
256 on the last line is indented.
257
258 ```python
259 from third_party import (
260 lib1,
261 lib2,
262 lib3,
263 lib4,
264 )
265 ```
266
267 **9 - Vertical Prefix From Module Import**
268
269 Starts a new line with the same `from MODULE import ` prefix when lines are longer than the line length limit.
270
271 ```python
272 from third_party import lib1, lib2, lib3
273 from third_party import lib4, lib5, lib6
274 ```
275
276 **10 - Hanging Indent With Parentheses**
277
278 Same as Mode 2 - _Hanging Indent_ but uses parentheses instead of backslash
279 for wrapping long lines.
280
281 ```python
282 from third_party import (
283 lib1, lib2, lib3,
284 lib4, lib5, lib6)
285 ```
286
253287 Note: to change the how constant indents appear - simply change the
254288 indent property with the following accepted formats:
255289
0 __version__ = "5.3.2"
0 __version__ = "5.4.2"
8484 regexp = "^" + known_pattern.replace("*", ".*").replace("?", ".?") + "$"
8585 self.known_patterns.append((re.compile(regexp), placement))
8686
87 @staticmethod
88 def _parse_known_pattern(pattern: str) -> List[str]:
87 def _parse_known_pattern(self, pattern: str) -> List[str]:
8988 """Expand pattern if identified as a directory and return found sub packages"""
9089 if pattern.endswith(os.path.sep):
9190 patterns = [
9291 filename
93 for filename in os.listdir(pattern)
94 if os.path.isdir(os.path.join(pattern, filename))
92 for filename in os.listdir(os.path.join(self.config.directory, pattern))
93 if os.path.isdir(os.path.join(self.config.directory, pattern, filename))
9594 ]
9695 else:
9796 patterns = [pattern]
327327 action="store_true",
328328 )
329329 parser.add_argument(
330 "--lss",
331 "--length-sort-straight",
332 help="Sort straight imports by their string length.",
333 dest="length_sort_straight",
334 action="store_true",
335 )
336 parser.add_argument(
330337 "-m",
331338 "--multi-line",
332339 dest="multi_line_output",
334341 + [str(mode.value) for mode in WrapModes.__members__.values()],
335342 type=str,
336343 help="Multi line output (0-grid, 1-vertical, 2-hanging, 3-vert-hanging, 4-vert-grid, "
337 "5-vert-grid-grouped, 6-vert-grid-grouped-no-comma).",
344 "5-vert-grid-grouped, 6-vert-grid-grouped-no-comma, 7-noqa, "
345 "8-vertical-hanging-indent-bracket, 9-vertical-prefix-from-module-import, "
346 "10-hanging-indent-with-parentheses).",
338347 )
339348 parser.add_argument(
340349 "-n",
452461 "--skip-gitignore",
453462 action="store_true",
454463 dest="skip_gitignore",
455 help="Treat project as a git respository and ignore files listed in .gitignore",
464 help="Treat project as a git repository and ignore files listed in .gitignore",
456465 )
457466 inline_args_group.add_argument(
458467 "--sl",
735744 arguments["remapped_deprecated_args"] = remapped_deprecated_args
736745 if "dont_order_by_type" in arguments:
737746 arguments["order_by_type"] = False
747 del arguments["dont_order_by_type"]
738748 multi_line_output = arguments.get("multi_line_output", None)
739749 if multi_line_output:
740750 if multi_line_output.isdigit():
5050 for section in sections:
5151 straight_modules = parsed.imports[section]["straight"]
5252 straight_modules = sorting.naturally(
53 straight_modules, key=lambda key: sorting.module_key(key, config, section_name=section)
53 straight_modules,
54 key=lambda key: sorting.module_key(
55 key, config, section_name=section, straight_import=True
56 ),
5457 )
5558 from_modules = parsed.imports[section]["from"]
5659 from_modules = sorting.naturally(
297300 new_section_output.extend(above_comments)
298301
299302 if "*" in from_imports and config.combine_star:
303 if config.combine_as_imports:
304 comments = list(comments or ())
305 comments += parsed.categorized_comments["from"].pop(
306 f"{module}.__combined_as__", []
307 )
300308 import_statement = wrap.line(
301309 with_comments(
302310 comments,
381389 for as_import in as_imports[from_import]
382390 )
383391
384 star_import = False
385392 if "*" in from_imports:
386393 new_section_output.append(
387394 with_comments(
392399 )
393400 )
394401 from_imports.remove("*")
395 star_import = True
396402 comments = None
397403
398404 for from_import in copy.copy(from_imports):
424430 )
425431 ):
426432 from_import_section.append(from_imports.pop(0))
427 if star_import:
428 import_statement = import_start + (", ").join(from_import_section)
429 else:
430 import_statement = with_comments(
431 comments,
432 import_start + (", ").join(from_import_section),
433 removed=config.ignore_comments,
434 comment_prefix=config.comment_prefix,
435 )
433 if config.combine_as_imports:
434 comments = (comments or []) + list(
435 parsed.categorized_comments["from"].pop(f"{module}.__combined_as__", ())
436 )
437 import_statement = with_comments(
438 comments,
439 import_start + (", ").join(from_import_section),
440 removed=config.ignore_comments,
441 comment_prefix=config.comment_prefix,
442 )
436443 if not from_import_section:
437444 import_statement = ""
438445
319319 if "as" in just_imports and (just_imports.index("as") + 1) < len(just_imports):
320320 straight_import = False
321321 while "as" in just_imports:
322 nested_module = None
322323 as_index = just_imports.index("as")
323324 if type_of_import == "from":
324325 nested_module = just_imports[as_index - 1]
325 module = just_imports[0] + "." + nested_module
326 top_level_module = just_imports[0]
327 module = top_level_module + "." + nested_module
326328 as_name = just_imports[as_index + 1]
327329 if nested_module == as_name and config.remove_redundant_aliases:
328330 pass
335337 pass
336338 elif as_name not in as_map["straight"][module]:
337339 as_map["straight"][module].append(as_name)
338 if not config.combine_as_imports:
340
341 if config.combine_as_imports and nested_module:
342 categorized_comments["from"].setdefault(
343 f"{top_level_module}.__combined_as__", []
344 ).extend(comments)
345 comments = []
346 else:
339347 categorized_comments["straight"][module] = comments
340348 comments = []
341349 del just_imports[as_index : as_index + 2]
131131 indent: str = " " * 4
132132 comment_prefix: str = " #"
133133 length_sort: bool = False
134 length_sort_straight: bool = False
134135 length_sort_sections: FrozenSet[str] = frozenset()
135136 add_imports: FrozenSet[str] = frozenset()
136137 remove_imports: FrozenSet[str] = frozenset()
521522 self._section_comments = tuple(f"# {heading}" for heading in self.import_headings.values())
522523 return self._section_comments
523524
524 @staticmethod
525 def _parse_known_pattern(pattern: str) -> List[str]:
525 def _parse_known_pattern(self, pattern: str) -> List[str]:
526526 """Expand pattern if identified as a directory and return found sub packages"""
527527 if pattern.endswith(os.path.sep):
528528 patterns = [
529529 filename
530 for filename in os.listdir(pattern)
531 if os.path.isdir(os.path.join(pattern, filename))
530 for filename in os.listdir(os.path.join(self.directory, pattern))
531 if os.path.isdir(os.path.join(self.directory, pattern, filename))
532532 ]
533533 else:
534534 patterns = [pattern]
652652 float("inf") if max_line_length == "off" else int(max_line_length)
653653 )
654654 settings = {
655 key: value for key, value in settings.items() if key in _DEFAULT_SETTINGS.keys()
655 key: value
656 for key, value in settings.items()
657 if key in _DEFAULT_SETTINGS.keys() or key.startswith(KNOWN_PREFIX)
656658 }
657659
658660 for key, value in settings.items():
1212 sub_imports: bool = False,
1313 ignore_case: bool = False,
1414 section_name: Optional[Any] = None,
15 straight_import: Optional[bool] = False,
1516 ) -> str:
1617 match = re.match(r"^(\.+)\s*(.*)", module_name)
1718 if match:
4041 if not config.case_sensitive:
4142 module_name = module_name.lower()
4243
43 length_sort = config.length_sort or str(section_name).lower() in config.length_sort_sections
44 length_sort = (
45 config.length_sort
46 or (config.length_sort_straight and straight_import)
47 or str(section_name).lower() in config.length_sort_sections
48 )
4449 _length_sort_maybe = length_sort and (str(len(module_name)) + ":" + module_name) or module_name
4550 return f"{module_name in config.force_to_top and 'A' or 'B'}{prefix}{_length_sort_maybe}"
4651
22
33 [tool.poetry]
44 name = "isort"
5 version = "5.3.2"
5 version = "5.4.2"
66 description = "A Python utility / library to sort Python imports."
77 authors = ["Timothy Crosley <timothy.crosley@gmail.com>"]
88 license = "MIT"
2323
2424 setup_kwargs = {
2525 'name': 'isort',
26 'version': '5.3.2',
26 'version': '5.4.2',
2727 'description': 'A Python utility / library to sort Python imports.',
28 'long_description': '[![isort - isort your imports, so you don\'t have to.](https://raw.githubusercontent.com/timothycrosley/isort/develop/art/logo_large.png)](https://timothycrosley.github.io/isort/)\n\n------------------------------------------------------------------------\n\n[![PyPI version](https://badge.fury.io/py/isort.svg)](https://badge.fury.io/py/isort)\n[![Test Status](https://github.com/timothycrosley/isort/workflows/Test/badge.svg?branch=develop)](https://github.com/timothycrosley/isort/actions?query=workflow%3ATest)\n[![Lint Status](https://github.com/timothycrosley/isort/workflows/Lint/badge.svg?branch=develop)](https://github.com/timothycrosley/isort/actions?query=workflow%3ALint)\n[![Code coverage Status](https://codecov.io/gh/timothycrosley/isort/branch/develop/graph/badge.svg)](https://codecov.io/gh/timothycrosley/isort)\n[![Maintainability](https://api.codeclimate.com/v1/badges/060372d3e77573072609/maintainability)](https://codeclimate.com/github/timothycrosley/isort/maintainability)\n[![License](https://img.shields.io/github/license/mashape/apistatus.svg)](https://pypi.org/project/isort/)\n[![Join the chat at https://gitter.im/timothycrosley/isort](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/timothycrosley/isort?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n[![Downloads](https://pepy.tech/badge/isort)](https://pepy.tech/project/isort)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://timothycrosley.github.io/isort/)\n[![DeepSource](https://static.deepsource.io/deepsource-badge-light-mini.svg)](https://deepsource.io/gh/timothycrosley/isort/?ref=repository-badge)\n_________________\n\n[Read Latest Documentation](https://timothycrosley.github.io/isort/) - [Browse GitHub Code Repository](https://github.com/timothycrosley/isort/)\n_________________\n\nisort your imports, so you don\'t have to.\n\nisort is a Python utility / library to sort imports alphabetically, and\nautomatically separated into sections and by type. It provides a command line\nutility, Python library and [plugins for various\neditors](https://github.com/timothycrosley/isort/wiki/isort-Plugins) to\nquickly sort all your imports. It requires Python 3.6+ to run but\nsupports formatting Python 2 code too.\n\n[Try isort now from your browser!](https://timothycrosley.github.io/isort/docs/quick_start/0.-try/)\n\n![Example Usage](https://raw.github.com/timothycrosley/isort/develop/example.gif)\n\nBefore isort:\n\n```python\nfrom my_lib import Object\n\nimport os\n\nfrom my_lib import Object3\n\nfrom my_lib import Object2\n\nimport sys\n\nfrom third_party import lib15, lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, lib11, lib12, lib13, lib14\n\nimport sys\n\nfrom __future__ import absolute_import\n\nfrom third_party import lib3\n\nprint("Hey")\nprint("yo")\n```\n\nAfter isort:\n\n```python\nfrom __future__ import absolute_import\n\nimport os\nimport sys\n\nfrom third_party import (lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8,\n lib9, lib10, lib11, lib12, lib13, lib14, lib15)\n\nfrom my_lib import Object, Object2, Object3\n\nprint("Hey")\nprint("yo")\n```\n\n## Installing isort\n\nInstalling isort is as simple as:\n\n```bash\npip install isort\n```\n\nInstall isort with requirements.txt support:\n\n```bash\npip install isort[requirements_deprecated_finder]\n```\n\nInstall isort with Pipfile support:\n\n```bash\npip install isort[pipfile_deprecated_finder]\n```\n\nInstall isort with both formats support:\n\n```bash\npip install isort[requirements_deprecated_finder,pipfile_deprecated_finder]\n```\n\n## Using isort\n\n**From the command line**:\n\n```bash\nisort mypythonfile.py mypythonfile2.py\n```\n\nor recursively:\n\n```bash\nisort .\n```\n\n*which is equivalent to:*\n\n```bash\nisort **/*.py\n```\n\nor to see the proposed changes without applying them:\n\n```bash\nisort mypythonfile.py --diff\n```\n\nFinally, to atomically run isort against a project, only applying\nchanges if they don\'t introduce syntax errors do:\n\n```bash\nisort --atomic .\n```\n\n(Note: this is disabled by default as it keeps isort from being able to\nrun against code written using a different version of Python)\n\n**From within Python**:\n\n```bash\nimport isort\n\nisort.file("pythonfile.py")\n```\n\nor:\n\n```bash\nimport isort\n\nsorted_code = isort.code("import b\\nimport a\\n")\n```\n\n## Installing isort\'s for your preferred text editor\n\nSeveral plugins have been written that enable to use isort from within a\nvariety of text-editors. You can find a full list of them [on the isort\nwiki](https://github.com/timothycrosley/isort/wiki/isort-Plugins).\nAdditionally, I will enthusiastically accept pull requests that include\nplugins for other text editors and add documentation for them as I am\nnotified.\n\n## Multi line output modes\n\nYou will notice above the \\"multi\\_line\\_output\\" setting. This setting\ndefines how from imports wrap when they extend past the line\\_length\nlimit and has 6 possible settings:\n\n**0 - Grid**\n\n```python\nfrom third_party import (lib1, lib2, lib3,\n lib4, lib5, ...)\n```\n\n**1 - Vertical**\n\n```python\nfrom third_party import (lib1,\n lib2,\n lib3\n lib4,\n lib5,\n ...)\n```\n\n**2 - Hanging Indent**\n\n```python\nfrom third_party import \\\n lib1, lib2, lib3, \\\n lib4, lib5, lib6\n```\n\n**3 - Vertical Hanging Indent**\n\n```python\nfrom third_party import (\n lib1,\n lib2,\n lib3,\n lib4,\n)\n```\n\n**4 - Hanging Grid**\n\n```python\nfrom third_party import (\n lib1, lib2, lib3, lib4,\n lib5, ...)\n```\n\n**5 - Hanging Grid Grouped**\n\n```python\nfrom third_party import (\n lib1, lib2, lib3, lib4,\n lib5, ...\n)\n```\n\n**6 - Hanging Grid Grouped, No Trailing Comma**\n\nIn Mode 5 isort leaves a single extra space to maintain consistency of\noutput when a comma is added at the end. Mode 6 is the same - except\nthat no extra space is maintained leading to the possibility of lines\none character longer. You can enforce a trailing comma by using this in\nconjunction with `-tc` or `include_trailing_comma: True`.\n\n```python\nfrom third_party import (\n lib1, lib2, lib3, lib4,\n lib5\n)\n```\n\n**7 - NOQA**\n\n```python\nfrom third_party import lib1, lib2, lib3, ... # NOQA\n```\n\nAlternatively, you can set `force_single_line` to `True` (`-sl` on the\ncommand line) and every import will appear on its own line:\n\n```python\nfrom third_party import lib1\nfrom third_party import lib2\nfrom third_party import lib3\n...\n```\n\nNote: to change the how constant indents appear - simply change the\nindent property with the following accepted formats:\n\n- Number of spaces you would like. For example: 4 would cause standard\n 4 space indentation.\n- Tab\n- A verbatim string with quotes around it.\n\nFor example:\n\n```python\n" "\n```\n\nis equivalent to 4.\n\nFor the import styles that use parentheses, you can control whether or\nnot to include a trailing comma after the last import with the\n`include_trailing_comma` option (defaults to `False`).\n\n## Intelligently Balanced Multi-line Imports\n\nAs of isort 3.1.0 support for balanced multi-line imports has been\nadded. With this enabled isort will dynamically change the import length\nto the one that produces the most balanced grid, while staying below the\nmaximum import length defined.\n\nExample:\n\n```python\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\n```\n\nWill be produced instead of:\n\n```python\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n```\n\nTo enable this set `balanced_wrapping` to `True` in your config or pass\nthe `-e` option into the command line utility.\n\n## Custom Sections and Ordering\n\nYou can change the section order with `sections` option from the default\nof:\n\n```ini\nFUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER\n```\n\nto your preference:\n\n```ini\nsections=FUTURE,STDLIB,FIRSTPARTY,THIRDPARTY,LOCALFOLDER\n```\n\nYou also can define your own sections and their order.\n\nExample:\n\n```ini\nknown_django=django\nknown_pandas=pandas,numpy\nsections=FUTURE,STDLIB,DJANGO,THIRDPARTY,PANDAS,FIRSTPARTY,LOCALFOLDER\n```\n\nwould create two new sections with the specified known modules.\n\nThe `no_lines_before` option will prevent the listed sections from being\nsplit from the previous section by an empty line.\n\nExample:\n\n```ini\nsections=FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER\nno_lines_before=LOCALFOLDER\n```\n\nwould produce a section with both FIRSTPARTY and LOCALFOLDER modules\ncombined.\n\n**IMPORTANT NOTE**: It is very important to know when setting `known` sections that the naming\ndoes not directly map for historical reasons. For custom settings, the only difference is\ncapitalization (`known_custom=custom` VS `sections=CUSTOM,...`) for all others reference the\nfollowing mapping:\n\n - `known_standard_library` : `STANDARD_LIBRARY`\n - `extra_standard_library` : `STANDARD_LIBRARY` # Like known standard library but appends instead of replacing\n - `known_future_library` : `FUTURE`\n - `known_first_party`: `FIRSTPARTY`\n - `known_third_party`: `THIRDPARTY`\n - `known_local_folder`: `LOCALFOLDER`\n\nThis will likely be changed in isort 6.0.0+ in a backwards compatible way.\n\n## Auto-comment import sections\n\nSome projects prefer to have import sections uniquely titled to aid in\nidentifying the sections quickly when visually scanning. isort can\nautomate this as well. To do this simply set the\n`import_heading_{section_name}` setting for each section you wish to\nhave auto commented - to the desired comment.\n\nFor Example:\n\n```ini\nimport_heading_stdlib=Standard Library\nimport_heading_firstparty=My Stuff\n```\n\nWould lead to output looking like the following:\n\n```python\n# Standard Library\nimport os\nimport sys\n\nimport django.settings\n\n# My Stuff\nimport myproject.test\n```\n\n## Ordering by import length\n\nisort also makes it easy to sort your imports by length, simply by\nsetting the `length_sort` option to `True`. This will result in the\nfollowing output style:\n\n```python\nfrom evn.util import (\n Pool,\n Dict,\n Options,\n Constant,\n DecayDict,\n UnexpectedCodePath,\n)\n```\n\nIt is also possible to opt-in to sorting imports by length for only\nspecific sections by using `length_sort_` followed by the section name\nas a configuration item, e.g.:\n\n length_sort_stdlib=1\n\n## Controlling how isort sections `from` imports\n\nBy default isort places straight (`import y`) imports above from imports (`from x import y`):\n\n```python\nimport b\nfrom a import a # This will always appear below because it is a from import.\n```\n\nHowever, if you prefer to keep strict alphabetical sorting you can set [force sort within sections](https://timothycrosley.github.io/isort/docs/configuration/options/#force-sort-within-sections) to true. Resulting in:\n\n\n```python\nfrom a import a # This will now appear at top because a appears in the alphabet before b\nimport b\n```\n\nYou can even tell isort to always place from imports on top, instead of the default of placing them on bottom, using [from first](https://timothycrosley.github.io/isort/docs/configuration/options/#from-first).\n\n```python\nfrom b import b # If from first is set to True, all from imports will be placed before non-from imports.\nimport a\n```\n\n## Skip processing of imports (outside of configuration)\n\nTo make isort ignore a single import simply add a comment at the end of\nthe import line containing the text `isort:skip`:\n\n```python\nimport module # isort:skip\n```\n\nor:\n\n```python\nfrom xyz import (abc, # isort:skip\n yo,\n hey)\n```\n\nTo make isort skip an entire file simply add `isort:skip_file` to the\nmodule\'s doc string:\n\n```python\n""" my_module.py\n Best module ever\n\n isort:skip_file\n"""\n\nimport b\nimport a\n```\n\n## Adding an import to multiple files\n\nisort makes it easy to add an import statement across multiple files,\nwhile being assured it\'s correctly placed.\n\nTo add an import to all files:\n\n```bash\nisort -a "from __future__ import print_function" *.py\n```\n\nTo add an import only to files that already have imports:\n\n```bash\nisort -a "from __future__ import print_function" --append-only *.py\n```\n\n\n## Removing an import from multiple files\n\nisort also makes it easy to remove an import from multiple files,\nwithout having to be concerned with how it was originally formatted.\n\nFrom the command line:\n\n```bash\nisort --rm "os.system" *.py\n```\n\n## Using isort to verify code\n\nThe `--check-only` option\n-------------------------\n\nisort can also be used to used to verify that code is correctly\nformatted by running it with `-c`. Any files that contain incorrectly\nsorted and/or formatted imports will be outputted to `stderr`.\n\n```bash\nisort **/*.py -c -v\n\nSUCCESS: /home/timothy/Projects/Open_Source/isort/isort_kate_plugin.py Everything Looks Good!\nERROR: /home/timothy/Projects/Open_Source/isort/isort/isort.py Imports are incorrectly sorted.\n```\n\nOne great place this can be used is with a pre-commit git hook, such as\nthis one by \\@acdha:\n\n<https://gist.github.com/acdha/8717683>\n\nThis can help to ensure a certain level of code quality throughout a\nproject.\n\nGit hook\n--------\n\nisort provides a hook function that can be integrated into your Git\npre-commit script to check Python code before committing.\n\nTo cause the commit to fail if there are isort errors (strict mode),\ninclude the following in `.git/hooks/pre-commit`:\n\n```python\n#!/usr/bin/env python\nimport sys\nfrom isort.hooks import git_hook\n\nsys.exit(git_hook(strict=True, modify=True, lazy=True))\n```\n\nIf you just want to display warnings, but allow the commit to happen\nanyway, call `git_hook` without the strict parameter. If you want to\ndisplay warnings, but not also fix the code, call `git_hook` without the\nmodify parameter.\nThe `lazy` argument is to support users who are "lazy" to add files\nindividually to the index and tend to use `git commit -a` instead.\nSet it to `True` to ensure all tracked files are properly isorted,\nleave it out or set it to `False` to check only files added to your\nindex.\n\n## Setuptools integration\n\nUpon installation, isort enables a `setuptools` command that checks\nPython files declared by your project.\n\nRunning `python setup.py isort` on the command line will check the files\nlisted in your `py_modules` and `packages`. If any warning is found, the\ncommand will exit with an error code:\n\n```bash\n$ python setup.py isort\n```\n\nAlso, to allow users to be able to use the command without having to\ninstall isort themselves, add isort to the setup\\_requires of your\n`setup()` like so:\n\n```python\nsetup(\n name="project",\n packages=["project"],\n\n setup_requires=[\n "isort"\n ]\n)\n```\n\n## Spread the word\n\n[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://timothycrosley.github.io/isort/)\n\nPlace this badge at the top of your repository to let others know your project uses isort.\n\nFor README.md:\n\n```markdown\n[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://timothycrosley.github.io/isort/)\n```\n\nOr README.rst:\n\n```rst\n.. image:: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336\n :target: https://timothycrosley.github.io/isort/\n```\n\n## Security contact information\n\nTo report a security vulnerability, please use the [Tidelift security\ncontact](https://tidelift.com/security). Tidelift will coordinate the\nfix and disclosure.\n\n## Why isort?\n\nisort simply stands for import sort. It was originally called\n"sortImports" however I got tired of typing the extra characters and\ncame to the realization camelCase is not pythonic.\n\nI wrote isort because in an organization I used to work in the manager\ncame in one day and decided all code must have alphabetically sorted\nimports. The code base was huge - and he meant for us to do it by hand.\nHowever, being a programmer - I\\\'m too lazy to spend 8 hours mindlessly\nperforming a function, but not too lazy to spend 16 hours automating it.\nI was given permission to open source sortImports and here we are :)\n\n------------------------------------------------------------------------\n\n[Get professionally supported isort with the Tidelift\nSubscription](https://tidelift.com/subscription/pkg/pypi-isort?utm_source=pypi-isort&utm_medium=referral&utm_campaign=readme)\n\nProfessional support for isort is available as part of the [Tidelift\nSubscription](https://tidelift.com/subscription/pkg/pypi-isort?utm_source=pypi-isort&utm_medium=referral&utm_campaign=readme).\nTidelift gives software development teams a single source for purchasing\nand maintaining their software, with professional grade assurances from\nthe experts who know it best, while seamlessly integrating with existing\ntools.\n\n------------------------------------------------------------------------\n\nThanks and I hope you find isort useful!\n\n~Timothy Crosley\n',
28 'long_description': '[![isort - isort your imports, so you don\'t have to.](https://raw.githubusercontent.com/timothycrosley/isort/develop/art/logo_large.png)](https://timothycrosley.github.io/isort/)\n\n------------------------------------------------------------------------\n\n[![PyPI version](https://badge.fury.io/py/isort.svg)](https://badge.fury.io/py/isort)\n[![Test Status](https://github.com/timothycrosley/isort/workflows/Test/badge.svg?branch=develop)](https://github.com/timothycrosley/isort/actions?query=workflow%3ATest)\n[![Lint Status](https://github.com/timothycrosley/isort/workflows/Lint/badge.svg?branch=develop)](https://github.com/timothycrosley/isort/actions?query=workflow%3ALint)\n[![Code coverage Status](https://codecov.io/gh/timothycrosley/isort/branch/develop/graph/badge.svg)](https://codecov.io/gh/timothycrosley/isort)\n[![Maintainability](https://api.codeclimate.com/v1/badges/060372d3e77573072609/maintainability)](https://codeclimate.com/github/timothycrosley/isort/maintainability)\n[![License](https://img.shields.io/github/license/mashape/apistatus.svg)](https://pypi.org/project/isort/)\n[![Join the chat at https://gitter.im/timothycrosley/isort](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/timothycrosley/isort?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)\n[![Downloads](https://pepy.tech/badge/isort)](https://pepy.tech/project/isort)\n[![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)\n[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://timothycrosley.github.io/isort/)\n[![DeepSource](https://static.deepsource.io/deepsource-badge-light-mini.svg)](https://deepsource.io/gh/timothycrosley/isort/?ref=repository-badge)\n_________________\n\n[Read Latest Documentation](https://timothycrosley.github.io/isort/) - [Browse GitHub Code Repository](https://github.com/timothycrosley/isort/)\n_________________\n\nisort your imports, so you don\'t have to.\n\nisort is a Python utility / library to sort imports alphabetically, and\nautomatically separated into sections and by type. It provides a command line\nutility, Python library and [plugins for various\neditors](https://github.com/timothycrosley/isort/wiki/isort-Plugins) to\nquickly sort all your imports. It requires Python 3.6+ to run but\nsupports formatting Python 2 code too.\n\n[Try isort now from your browser!](https://timothycrosley.github.io/isort/docs/quick_start/0.-try/)\n\n![Example Usage](https://raw.github.com/timothycrosley/isort/develop/example.gif)\n\nBefore isort:\n\n```python\nfrom my_lib import Object\n\nimport os\n\nfrom my_lib import Object3\n\nfrom my_lib import Object2\n\nimport sys\n\nfrom third_party import lib15, lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9, lib10, lib11, lib12, lib13, lib14\n\nimport sys\n\nfrom __future__ import absolute_import\n\nfrom third_party import lib3\n\nprint("Hey")\nprint("yo")\n```\n\nAfter isort:\n\n```python\nfrom __future__ import absolute_import\n\nimport os\nimport sys\n\nfrom third_party import (lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8,\n lib9, lib10, lib11, lib12, lib13, lib14, lib15)\n\nfrom my_lib import Object, Object2, Object3\n\nprint("Hey")\nprint("yo")\n```\n\n## Installing isort\n\nInstalling isort is as simple as:\n\n```bash\npip install isort\n```\n\nInstall isort with requirements.txt support:\n\n```bash\npip install isort[requirements_deprecated_finder]\n```\n\nInstall isort with Pipfile support:\n\n```bash\npip install isort[pipfile_deprecated_finder]\n```\n\nInstall isort with both formats support:\n\n```bash\npip install isort[requirements_deprecated_finder,pipfile_deprecated_finder]\n```\n\n## Using isort\n\n**From the command line**:\n\n```bash\nisort mypythonfile.py mypythonfile2.py\n```\n\nor recursively:\n\n```bash\nisort .\n```\n\n*which is equivalent to:*\n\n```bash\nisort **/*.py\n```\n\nor to see the proposed changes without applying them:\n\n```bash\nisort mypythonfile.py --diff\n```\n\nFinally, to atomically run isort against a project, only applying\nchanges if they don\'t introduce syntax errors do:\n\n```bash\nisort --atomic .\n```\n\n(Note: this is disabled by default as it keeps isort from being able to\nrun against code written using a different version of Python)\n\n**From within Python**:\n\n```bash\nimport isort\n\nisort.file("pythonfile.py")\n```\n\nor:\n\n```bash\nimport isort\n\nsorted_code = isort.code("import b\\nimport a\\n")\n```\n\n## Installing isort\'s for your preferred text editor\n\nSeveral plugins have been written that enable to use isort from within a\nvariety of text-editors. You can find a full list of them [on the isort\nwiki](https://github.com/timothycrosley/isort/wiki/isort-Plugins).\nAdditionally, I will enthusiastically accept pull requests that include\nplugins for other text editors and add documentation for them as I am\nnotified.\n\n## Multi line output modes\n\nYou will notice above the \\"multi\\_line\\_output\\" setting. This setting\ndefines how from imports wrap when they extend past the line\\_length\nlimit and has 6 possible settings:\n\n**0 - Grid**\n\n```python\nfrom third_party import (lib1, lib2, lib3,\n lib4, lib5, ...)\n```\n\n**1 - Vertical**\n\n```python\nfrom third_party import (lib1,\n lib2,\n lib3\n lib4,\n lib5,\n ...)\n```\n\n**2 - Hanging Indent**\n\n```python\nfrom third_party import \\\n lib1, lib2, lib3, \\\n lib4, lib5, lib6\n```\n\n**3 - Vertical Hanging Indent**\n\n```python\nfrom third_party import (\n lib1,\n lib2,\n lib3,\n lib4,\n)\n```\n\n**4 - Hanging Grid**\n\n```python\nfrom third_party import (\n lib1, lib2, lib3, lib4,\n lib5, ...)\n```\n\n**5 - Hanging Grid Grouped**\n\n```python\nfrom third_party import (\n lib1, lib2, lib3, lib4,\n lib5, ...\n)\n```\n\n**6 - Hanging Grid Grouped, No Trailing Comma**\n\nIn Mode 5 isort leaves a single extra space to maintain consistency of\noutput when a comma is added at the end. Mode 6 is the same - except\nthat no extra space is maintained leading to the possibility of lines\none character longer. You can enforce a trailing comma by using this in\nconjunction with `-tc` or `include_trailing_comma: True`.\n\n```python\nfrom third_party import (\n lib1, lib2, lib3, lib4,\n lib5\n)\n```\n\n**7 - NOQA**\n\n```python\nfrom third_party import lib1, lib2, lib3, ... # NOQA\n```\n\nAlternatively, you can set `force_single_line` to `True` (`-sl` on the\ncommand line) and every import will appear on its own line:\n\n```python\nfrom third_party import lib1\nfrom third_party import lib2\nfrom third_party import lib3\n...\n```\n\n**8 - Vertical Hanging Indent Bracket**\n\nSame as Mode 3 - _Vertical Hanging Indent_ but the closing parentheses\non the last line is indented.\n\n```python\nfrom third_party import (\n lib1,\n lib2,\n lib3,\n lib4,\n )\n```\n\n**9 - Vertical Prefix From Module Import**\n\nStarts a new line with the same `from MODULE import ` prefix when lines are longer than the line length limit.\n\n```python\nfrom third_party import lib1, lib2, lib3\nfrom third_party import lib4, lib5, lib6\n```\n\n**10 - Hanging Indent With Parentheses**\n\nSame as Mode 2 - _Hanging Indent_ but uses parentheses instead of backslash\nfor wrapping long lines.\n\n```python\nfrom third_party import (\n lib1, lib2, lib3,\n lib4, lib5, lib6)\n```\n\nNote: to change the how constant indents appear - simply change the\nindent property with the following accepted formats:\n\n- Number of spaces you would like. For example: 4 would cause standard\n 4 space indentation.\n- Tab\n- A verbatim string with quotes around it.\n\nFor example:\n\n```python\n" "\n```\n\nis equivalent to 4.\n\nFor the import styles that use parentheses, you can control whether or\nnot to include a trailing comma after the last import with the\n`include_trailing_comma` option (defaults to `False`).\n\n## Intelligently Balanced Multi-line Imports\n\nAs of isort 3.1.0 support for balanced multi-line imports has been\nadded. With this enabled isort will dynamically change the import length\nto the one that produces the most balanced grid, while staying below the\nmaximum import length defined.\n\nExample:\n\n```python\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\n```\n\nWill be produced instead of:\n\n```python\nfrom __future__ import (absolute_import, division, print_function,\n unicode_literals)\n```\n\nTo enable this set `balanced_wrapping` to `True` in your config or pass\nthe `-e` option into the command line utility.\n\n## Custom Sections and Ordering\n\nYou can change the section order with `sections` option from the default\nof:\n\n```ini\nFUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER\n```\n\nto your preference:\n\n```ini\nsections=FUTURE,STDLIB,FIRSTPARTY,THIRDPARTY,LOCALFOLDER\n```\n\nYou also can define your own sections and their order.\n\nExample:\n\n```ini\nknown_django=django\nknown_pandas=pandas,numpy\nsections=FUTURE,STDLIB,DJANGO,THIRDPARTY,PANDAS,FIRSTPARTY,LOCALFOLDER\n```\n\nwould create two new sections with the specified known modules.\n\nThe `no_lines_before` option will prevent the listed sections from being\nsplit from the previous section by an empty line.\n\nExample:\n\n```ini\nsections=FUTURE,STDLIB,THIRDPARTY,FIRSTPARTY,LOCALFOLDER\nno_lines_before=LOCALFOLDER\n```\n\nwould produce a section with both FIRSTPARTY and LOCALFOLDER modules\ncombined.\n\n**IMPORTANT NOTE**: It is very important to know when setting `known` sections that the naming\ndoes not directly map for historical reasons. For custom settings, the only difference is\ncapitalization (`known_custom=custom` VS `sections=CUSTOM,...`) for all others reference the\nfollowing mapping:\n\n - `known_standard_library` : `STANDARD_LIBRARY`\n - `extra_standard_library` : `STANDARD_LIBRARY` # Like known standard library but appends instead of replacing\n - `known_future_library` : `FUTURE`\n - `known_first_party`: `FIRSTPARTY`\n - `known_third_party`: `THIRDPARTY`\n - `known_local_folder`: `LOCALFOLDER`\n\nThis will likely be changed in isort 6.0.0+ in a backwards compatible way.\n\n## Auto-comment import sections\n\nSome projects prefer to have import sections uniquely titled to aid in\nidentifying the sections quickly when visually scanning. isort can\nautomate this as well. To do this simply set the\n`import_heading_{section_name}` setting for each section you wish to\nhave auto commented - to the desired comment.\n\nFor Example:\n\n```ini\nimport_heading_stdlib=Standard Library\nimport_heading_firstparty=My Stuff\n```\n\nWould lead to output looking like the following:\n\n```python\n# Standard Library\nimport os\nimport sys\n\nimport django.settings\n\n# My Stuff\nimport myproject.test\n```\n\n## Ordering by import length\n\nisort also makes it easy to sort your imports by length, simply by\nsetting the `length_sort` option to `True`. This will result in the\nfollowing output style:\n\n```python\nfrom evn.util import (\n Pool,\n Dict,\n Options,\n Constant,\n DecayDict,\n UnexpectedCodePath,\n)\n```\n\nIt is also possible to opt-in to sorting imports by length for only\nspecific sections by using `length_sort_` followed by the section name\nas a configuration item, e.g.:\n\n length_sort_stdlib=1\n\n## Controlling how isort sections `from` imports\n\nBy default isort places straight (`import y`) imports above from imports (`from x import y`):\n\n```python\nimport b\nfrom a import a # This will always appear below because it is a from import.\n```\n\nHowever, if you prefer to keep strict alphabetical sorting you can set [force sort within sections](https://timothycrosley.github.io/isort/docs/configuration/options/#force-sort-within-sections) to true. Resulting in:\n\n\n```python\nfrom a import a # This will now appear at top because a appears in the alphabet before b\nimport b\n```\n\nYou can even tell isort to always place from imports on top, instead of the default of placing them on bottom, using [from first](https://timothycrosley.github.io/isort/docs/configuration/options/#from-first).\n\n```python\nfrom b import b # If from first is set to True, all from imports will be placed before non-from imports.\nimport a\n```\n\n## Skip processing of imports (outside of configuration)\n\nTo make isort ignore a single import simply add a comment at the end of\nthe import line containing the text `isort:skip`:\n\n```python\nimport module # isort:skip\n```\n\nor:\n\n```python\nfrom xyz import (abc, # isort:skip\n yo,\n hey)\n```\n\nTo make isort skip an entire file simply add `isort:skip_file` to the\nmodule\'s doc string:\n\n```python\n""" my_module.py\n Best module ever\n\n isort:skip_file\n"""\n\nimport b\nimport a\n```\n\n## Adding an import to multiple files\n\nisort makes it easy to add an import statement across multiple files,\nwhile being assured it\'s correctly placed.\n\nTo add an import to all files:\n\n```bash\nisort -a "from __future__ import print_function" *.py\n```\n\nTo add an import only to files that already have imports:\n\n```bash\nisort -a "from __future__ import print_function" --append-only *.py\n```\n\n\n## Removing an import from multiple files\n\nisort also makes it easy to remove an import from multiple files,\nwithout having to be concerned with how it was originally formatted.\n\nFrom the command line:\n\n```bash\nisort --rm "os.system" *.py\n```\n\n## Using isort to verify code\n\nThe `--check-only` option\n-------------------------\n\nisort can also be used to used to verify that code is correctly\nformatted by running it with `-c`. Any files that contain incorrectly\nsorted and/or formatted imports will be outputted to `stderr`.\n\n```bash\nisort **/*.py -c -v\n\nSUCCESS: /home/timothy/Projects/Open_Source/isort/isort_kate_plugin.py Everything Looks Good!\nERROR: /home/timothy/Projects/Open_Source/isort/isort/isort.py Imports are incorrectly sorted.\n```\n\nOne great place this can be used is with a pre-commit git hook, such as\nthis one by \\@acdha:\n\n<https://gist.github.com/acdha/8717683>\n\nThis can help to ensure a certain level of code quality throughout a\nproject.\n\nGit hook\n--------\n\nisort provides a hook function that can be integrated into your Git\npre-commit script to check Python code before committing.\n\nTo cause the commit to fail if there are isort errors (strict mode),\ninclude the following in `.git/hooks/pre-commit`:\n\n```python\n#!/usr/bin/env python\nimport sys\nfrom isort.hooks import git_hook\n\nsys.exit(git_hook(strict=True, modify=True, lazy=True))\n```\n\nIf you just want to display warnings, but allow the commit to happen\nanyway, call `git_hook` without the strict parameter. If you want to\ndisplay warnings, but not also fix the code, call `git_hook` without the\nmodify parameter.\nThe `lazy` argument is to support users who are "lazy" to add files\nindividually to the index and tend to use `git commit -a` instead.\nSet it to `True` to ensure all tracked files are properly isorted,\nleave it out or set it to `False` to check only files added to your\nindex.\n\n## Setuptools integration\n\nUpon installation, isort enables a `setuptools` command that checks\nPython files declared by your project.\n\nRunning `python setup.py isort` on the command line will check the files\nlisted in your `py_modules` and `packages`. If any warning is found, the\ncommand will exit with an error code:\n\n```bash\n$ python setup.py isort\n```\n\nAlso, to allow users to be able to use the command without having to\ninstall isort themselves, add isort to the setup\\_requires of your\n`setup()` like so:\n\n```python\nsetup(\n name="project",\n packages=["project"],\n\n setup_requires=[\n "isort"\n ]\n)\n```\n\n## Spread the word\n\n[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://timothycrosley.github.io/isort/)\n\nPlace this badge at the top of your repository to let others know your project uses isort.\n\nFor README.md:\n\n```markdown\n[![Imports: isort](https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336)](https://timothycrosley.github.io/isort/)\n```\n\nOr README.rst:\n\n```rst\n.. image:: https://img.shields.io/badge/%20imports-isort-%231674b1?style=flat&labelColor=ef8336\n :target: https://timothycrosley.github.io/isort/\n```\n\n## Security contact information\n\nTo report a security vulnerability, please use the [Tidelift security\ncontact](https://tidelift.com/security). Tidelift will coordinate the\nfix and disclosure.\n\n## Why isort?\n\nisort simply stands for import sort. It was originally called\n"sortImports" however I got tired of typing the extra characters and\ncame to the realization camelCase is not pythonic.\n\nI wrote isort because in an organization I used to work in the manager\ncame in one day and decided all code must have alphabetically sorted\nimports. The code base was huge - and he meant for us to do it by hand.\nHowever, being a programmer - I\\\'m too lazy to spend 8 hours mindlessly\nperforming a function, but not too lazy to spend 16 hours automating it.\nI was given permission to open source sortImports and here we are :)\n\n------------------------------------------------------------------------\n\n[Get professionally supported isort with the Tidelift\nSubscription](https://tidelift.com/subscription/pkg/pypi-isort?utm_source=pypi-isort&utm_medium=referral&utm_campaign=readme)\n\nProfessional support for isort is available as part of the [Tidelift\nSubscription](https://tidelift.com/subscription/pkg/pypi-isort?utm_source=pypi-isort&utm_medium=referral&utm_campaign=readme).\nTidelift gives software development teams a single source for purchasing\nand maintaining their software, with professional grade assurances from\nthe experts who know it best, while seamlessly integrating with existing\ntools.\n\n------------------------------------------------------------------------\n\nThanks and I hope you find isort useful!\n\n~Timothy Crosley\n',
2929 'author': 'Timothy Crosley',
3030 'author_email': 'timothy.crosley@gmail.com',
3131 'maintainer': None,
2929 indent_size = 4
3030 known_first_party = isort
3131 known_third_party = kate
32 known_something_else = something_entirely_different
33 sections = FUTURE, STDLIB, THIRDPARTY, FIRSTPARTY, LOCALFOLDER, SOMETHING_ELSE
3234 ignore_frosted_errors = E103
3335 skip = build,.tox,venv
3436 balanced_wrapping = true
5153 def default_settings_path(tmpdir_factory) -> Iterator[str]:
5254 config_dir = tmpdir_factory.mktemp("config")
5355 config_file = config_dir.join(".editorconfig").strpath
56
5457 with open(config_file, "w") as editorconfig:
5558 editorconfig.write(TEST_DEFAULT_CONFIG)
59
60 assert Config(config_file).known_other
5661
5762 with config_dir.as_cwd():
5863 yield config_dir.strpath
604609 )
605610
606611
612 def test_length_sort_straight() -> None:
613 """Test setting isort to sort straight imports on length instead of alphabetically."""
614 test_input = (
615 "import medium_sizeeeeeeeeeeeeee\n"
616 "import shortie\n"
617 "import looooooooooooooooooooooooooooooooooooooong\n"
618 "from medium_sizeeeeeeeeeeeeee import b\n"
619 "from shortie import c\n"
620 "from looooooooooooooooooooooooooooooooooooooong import a\n"
621 )
622 test_output = isort.code(test_input, length_sort_straight=True)
623 assert test_output == (
624 "import shortie\n"
625 "import medium_sizeeeeeeeeeeeeee\n"
626 "import looooooooooooooooooooooooooooooooooooooong\n"
627 "from looooooooooooooooooooooooooooooooooooooong import a\n"
628 "from medium_sizeeeeeeeeeeeeee import b\n"
629 "from shortie import c\n"
630 )
631
632
607633 def test_length_sort_section() -> None:
608634 """Test setting isort to sort on length instead of alphabetically for a specific section."""
609635 test_input = (
610636 "import medium_sizeeeeeeeeeeeeee\n"
611637 "import shortie\n"
638 "import datetime\n"
612639 "import sys\n"
613640 "import os\n"
614641 "import looooooooooooooooooooooooooooooooooooooong\n"
618645 assert test_output == (
619646 "import os\n"
620647 "import sys\n"
648 "import datetime\n"
621649 "\n"
622650 "import looooooooooooooooooooooooooooooooooooooong\n"
623651 "import medium_sizeeeeeeeeeeeeea\n"
10431071 assert test_output == "import os\nimport sys\n\nimport profile.test\n"
10441072
10451073
1046 def test_known_pattern_path_expansion() -> None:
1074 def test_known_pattern_path_expansion(tmpdir) -> None:
10471075 """Test to ensure patterns ending with path sep gets expanded
10481076 and nested packages treated as known patterns.
10491077 """
1078 src_dir = tmpdir.mkdir("src")
1079 src_dir.mkdir("foo")
1080 src_dir.mkdir("bar")
10501081 test_input = (
10511082 "from kate_plugin import isort_plugin\n"
10521083 "import sys\n"
1053 "import isort.settings\n"
1084 "from foo import settings\n"
1085 "import bar\n"
10541086 "import this\n"
10551087 "import os\n"
10561088 )
10571089 test_output = isort.code(
10581090 code=test_input,
10591091 default_section="THIRDPARTY",
1060 known_first_party=["./", "this", "kate_plugin", "isort"],
1092 known_first_party=["src/", "this", "kate_plugin"],
1093 directory=str(tmpdir),
10611094 )
10621095 test_output_old_finder = isort.code(
10631096 code=test_input,
10641097 default_section="FIRSTPARTY",
10651098 old_finders=True,
1066 known_first_party=["./", "this", "kate_plugin", "isort"],
1099 known_first_party=["src/", "this", "kate_plugin"],
1100 directory=str(tmpdir),
10671101 )
10681102 assert (
10691103 test_output_old_finder
10721106 "import os\n"
10731107 "import sys\n"
10741108 "\n"
1075 "import isort.settings\n"
1109 "import bar\n"
10761110 "import this\n"
1111 "from foo import settings\n"
10771112 "from kate_plugin import isort_plugin\n"
10781113 )
10791114 )
3838 assert main.parse_args([]) == {}
3939 assert main.parse_args(["--multi-line", "1"]) == {"multi_line_output": WrapModes.VERTICAL}
4040 assert main.parse_args(["--multi-line", "GRID"]) == {"multi_line_output": WrapModes.GRID}
41 assert main.parse_args(["--dont-order-by-type"]) == {"order_by_type": False}
42 assert main.parse_args(["--dt"]) == {"order_by_type": False}
4143
4244
4345 def test_ascii_art(capsys):
491491 assert diff_output.read().endswith(
492492 "-1,5 +1,5 @@\n+import a\r\n import b\r\n" "-import a\r\n \r\n \r\n def func():\r\n"
493493 )
494
495
496 def test_combine_as_does_not_lose_comments_issue_1321():
497 """Test to ensure isort doesn't lose comments when --combine-as is used.
498 See: https://github.com/timothycrosley/isort/issues/1321
499 """
500 test_input = """
501 from foo import * # noqa
502 from foo import bar as quux # other
503 from foo import x as a # noqa
504
505 import operator as op # op comment
506 import datetime as dtime # dtime comment
507
508 from datetime import date as d # dcomm
509 from datetime import datetime as dt # dtcomm
510 """
511
512 expected_output = """
513 import datetime as dtime # dtime comment
514 import operator as op # op comment
515 from datetime import date as d, datetime as dt # dcomm; dtcomm
516
517 from foo import * # noqa
518 from foo import bar as quux, x as a # other; noqa
519 """
520
521 assert isort.code(test_input, combine_as_imports=True) == expected_output
522
523
524 def test_combine_as_does_not_lose_comments_issue_1381():
525 """Test to ensure isort doesn't lose comments when --combine-as is used.
526 See: https://github.com/timothycrosley/isort/issues/1381
527 """
528 test_input = """
529 from smtplib import SMTPConnectError, SMTPNotSupportedError # important comment
530 """
531 assert "# important comment" in isort.code(test_input, combine_as_imports=True)
532
533 test_input = """
534 from appsettings import AppSettings, ObjectSetting, StringSetting # type: ignore
535 """
536 assert "# type: ignore" in isort.code(test_input, combine_as_imports=True)