Skip to content

Module isort.wrap

None

None

View Source
import copy

import re

from typing import List, Optional, Sequence

from .settings import DEFAULT_CONFIG, Config

from .wrap_modes import WrapModes as Modes

from .wrap_modes import formatter_from_string, vertical_hanging_indent

def import_statement(

    import_start: str,

    from_imports: List[str],

    comments: Sequence[str] = (),

    line_separator: str = "\n",

    config: Config = DEFAULT_CONFIG,

    multi_line_output: Optional[Modes] = None,

    explode: bool = False,

) -> str:

    """Returns a multi-line wrapped form of the provided from import statement."""

    if explode:

        formatter = vertical_hanging_indent

        line_length = 1

        include_trailing_comma = True

    else:

        formatter = formatter_from_string((multi_line_output or config.multi_line_output).name)

        line_length = config.wrap_length or config.line_length

        include_trailing_comma = config.include_trailing_comma

    dynamic_indent = " " * (len(import_start) + 1)

    indent = config.indent

    statement = formatter(

        statement=import_start,

        imports=copy.copy(from_imports),

        white_space=dynamic_indent,

        indent=indent,

        line_length=line_length,

        comments=comments,

        line_separator=line_separator,

        comment_prefix=config.comment_prefix,

        include_trailing_comma=include_trailing_comma,

        remove_comments=config.ignore_comments,

    )

    if config.balanced_wrapping:

        lines = statement.split(line_separator)

        line_count = len(lines)

        if len(lines) > 1:

            minimum_length = min(len(line) for line in lines[:-1])

        else:

            minimum_length = 0

        new_import_statement = statement

        while len(lines[-1]) < minimum_length and len(lines) == line_count and line_length > 10:

            statement = new_import_statement

            line_length -= 1

            new_import_statement = formatter(

                statement=import_start,

                imports=copy.copy(from_imports),

                white_space=dynamic_indent,

                indent=indent,

                line_length=line_length,

                comments=comments,

                line_separator=line_separator,

                comment_prefix=config.comment_prefix,

                include_trailing_comma=include_trailing_comma,

                remove_comments=config.ignore_comments,

            )

            lines = new_import_statement.split(line_separator)

    if statement.count(line_separator) == 0:

        return _wrap_line(statement, line_separator, config)

    return statement

def line(content: str, line_separator: str, config: Config = DEFAULT_CONFIG) -> str:

    """Returns a line wrapped to the specified line-length, if possible."""

    wrap_mode = config.multi_line_output

    if len(content) > config.line_length and wrap_mode != Modes.NOQA:  # type: ignore

        line_without_comment = content

        comment = None

        if "#" in content:

            line_without_comment, comment = content.split("#", 1)

        for splitter in ("import ", "cimport ", ".", "as "):

            exp = r"\b" + re.escape(splitter) + r"\b"

            if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(

                splitter

            ):

                line_parts = re.split(exp, line_without_comment)

                if comment and not (config.use_parentheses and "noqa" in comment):

                    _comma_maybe = (

                        ","

                        if (

                            config.include_trailing_comma

                            and config.use_parentheses

                            and not line_without_comment.rstrip().endswith(",")

                        )

                        else ""

                    )

                    line_parts[

                        -1

                    ] = f"{line_parts[-1].strip()}{_comma_maybe}{config.comment_prefix}{comment}"

                next_line = []

                while (len(content) + 2) > (

                    config.wrap_length or config.line_length

                ) and line_parts:

                    next_line.append(line_parts.pop())

                    content = splitter.join(line_parts)

                if not content:

                    content = next_line.pop()

                cont_line = _wrap_line(

                    config.indent + splitter.join(next_line).lstrip(),

                    line_separator,

                    config,

                )

                if config.use_parentheses:

                    if splitter == "as ":

                        output = f"{content}{splitter}{cont_line.lstrip()}"

                    else:

                        _comma = "," if config.include_trailing_comma and not comment else ""

                        if wrap_mode in (

                            Modes.VERTICAL_HANGING_INDENT,  # type: ignore

                            Modes.VERTICAL_GRID_GROUPED,  # type: ignore

                        ):

                            _separator = line_separator

                        else:

                            _separator = ""

                        _comment = ""

                        if comment and "noqa" in comment:

                            _comment = f"{config.comment_prefix}{comment}"

                            cont_line = cont_line.rstrip()

                            _comma = "," if config.include_trailing_comma else ""

                        output = (

                            f"{content}{splitter}({_comment}"

                            f"{line_separator}{cont_line}{_comma}{_separator})"

                        )

                    lines = output.split(line_separator)

                    if config.comment_prefix in lines[-1] and lines[-1].endswith(")"):

                        content, comment = lines[-1].split(config.comment_prefix, 1)

                        lines[-1] = content + ")" + config.comment_prefix + comment[:-1]

                    return line_separator.join(lines)

                return f"{content}{splitter}\\{line_separator}{cont_line}"

    elif len(content) > config.line_length and wrap_mode == Modes.NOQA and "# NOQA" not in content:  # type: ignore

        return f"{content}{config.comment_prefix} NOQA"

    return content

_wrap_line = line

Functions

import_statement

def import_statement(
    import_start: str,
    from_imports: List[str],
    comments: Sequence[str] = (),
    line_separator: str = '\n',
    config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'build', '.pants.d', '.mypy_cache', 'buck-out', '.nox', '.eggs', '.git', 'venv', '.tox', '.direnv', 'dist', '.venv', '.hg', '__pypackages__', '.bzr', 'node_modules', '_build', '.svn'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'getopt', 'mailcap', 'imaplib', 'nntplib', 'filecmp', 'threading', 'fnmatch', 'timeit', 'sqlite3', 'configparser', 'bdb', 'runpy', 'chunk', 'curses', 'ntpath', 'posixpath', 'platform', 'html', 'fractions', 'tomllib', 'token', 'zlib', 'code', 'poplib', 'fcntl', 'numbers', 'select', 'codecs', 'binascii', 'weakref', 'zipfile', 'distutils', 'secrets', 'sunau', '_ast', 'smtpd', 'dataclasses', 'http', 'gzip', 'posix', 'functools', 'zoneinfo', 'inspect', 'cgitb', 'symtable', 'pathlib', 'unittest', 'itertools', 'operator', 'fpectl', 'linecache', 'encodings', 'sys', 'resource', 'errno', 'telnetlib', 'traceback', 'idlelib', 'warnings', 'sre', 'io', 'cgi', 'email', 'sre_parse', 'dbm', 'pickletools', 'wsgiref', 'turtledemo', 'optparse', 'concurrent', 'string', 'statistics', 'subprocess', 'modulefinder', 'mailbox', 'lib2to3', 'colorsys', 'signal', 'time', 'shelve', 'calendar', 'pipes', 'importlib', 'unicodedata', 'gc', 'crypt', 'msvcrt', 'csv', 'ossaudiodev', 'msilib', 'pickle', 'hashlib', 'nis', 'aifc', 'hmac', 'winsound', 'graphlib', 'zipapp', 'typing', 'contextvars', 'struct', 'netrc', 'turtle', 'dummy_threading', 'cmath', 'array', 'copy', 'pydoc', 'pstats', 'grp', 'tarfile', 'copyreg', 'uu', 'zipimport', 'tabnanny', 'pyclbr', 'getpass', 'keyword', 'mmap', 'spwd', 'codeop', 'sre_compile', 'dis', 'sysconfig', 'atexit', 'venv', 'argparse', 'syslog', 'rlcompleter', 'xdrlib', 'faulthandler', 'lzma', 'macpath', 'enum', 'abc', 'ctypes', 'pprint', '_dummy_thread', 'test', 'socketserver', 'marshal', 'xml', 'binhex', 'socket', 'sched', 'textwrap', 'asyncio', 'webbrowser', 'urllib', 'pwd', 'bz2', 'cmd', 'ipaddress', 'os', 'xmlrpc', 'plistlib', 'fileinput', 'bisect', 'trace', 'gettext', 'contextlib', 'collections', 'ensurepip', 'mimetypes', 'ast', 'sndhdr', 'asyncore', 'difflib', 'tty', 'multiprocessing', 'site', '_thread', 'pkgutil', 'readline', 'stat', 'tokenize', 'smtplib', 'heapq', 'queue', 'shutil', 'termios', 'quopri', 'types', 'profile', 'tkinter', 'symbol', 'cProfile', 'sre_constants', 'formatter', 'locale', 'ssl', 'tempfile', 'stringprep', 'random', 'datetime', 'compileall', 'asynchat', 'tracemalloc', 'imp', 'decimal', 'imghdr', 'py_compile', 'pdb', 'shlex', 'selectors', 'wave', 'reprlib', 'winreg', 'logging', 'math', 'glob', 're', 'audioop', 'ftplib', 'base64', 'parser', 'pty', 'doctest', 'uuid', 'builtins', 'json'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent='    ', comment_prefix='  #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'build', '.pants.d', '.mypy_cache', 'buck-out', '.nox', '.eggs', '.git', 'venv', '.tox', '.direnv', 'dist', '.venv', '.hg', '__pypackages__', '.bzr', 'node_modules', '_build', '.svn'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'getopt', 'mailcap', 'imaplib', 'nntplib', 'filecmp', 'threading', 'fnmatch', 'timeit', 'sqlite3', 'configparser', 'bdb', 'runpy', 'chunk', 'curses', 'ntpath', 'posixpath', 'platform', 'html', 'fractions', 'tomllib', 'token', 'zlib', 'code', 'poplib', 'fcntl', 'numbers', 'select', 'codecs', 'binascii', 'weakref', 'zipfile', 'distutils', 'secrets', 'sunau', '_ast', 'smtpd', 'dataclasses', 'http', 'gzip', 'posix', 'functools', 'zoneinfo', 'inspect', 'cgitb', 'symtable', 'pathlib', 'unittest', 'itertools', 'operator', 'fpectl', 'linecache', 'encodings', 'sys', 'resource', 'errno', 'telnetlib', 'traceback', 'idlelib', 'warnings', 'sre', 'io', 'cgi', 'email', 'sre_parse', 'dbm', 'pickletools', 'wsgiref', 'turtledemo', 'optparse', 'concurrent', 'string', 'statistics', 'subprocess', 'modulefinder', 'mailbox', 'lib2to3', 'colorsys', 'signal', 'time', 'shelve', 'calendar', 'pipes', 'importlib', 'unicodedata', 'gc', 'crypt', 'msvcrt', 'csv', 'ossaudiodev', 'msilib', 'pickle', 'hashlib', 'nis', 'aifc', 'hmac', 'winsound', 'graphlib', 'zipapp', 'typing', 'contextvars', 'struct', 'netrc', 'turtle', 'dummy_threading', 'cmath', 'array', 'copy', 'pydoc', 'pstats', 'grp', 'tarfile', 'copyreg', 'uu', 'zipimport', 'tabnanny', 'pyclbr', 'getpass', 'keyword', 'mmap', 'spwd', 'codeop', 'sre_compile', 'dis', 'sysconfig', 'atexit', 'venv', 'argparse', 'syslog', 'rlcompleter', 'xdrlib', 'faulthandler', 'lzma', 'macpath', 'enum', 'abc', 'ctypes', 'pprint', '_dummy_thread', 'test', 'socketserver', 'marshal', 'xml', 'binhex', 'socket', 'sched', 'textwrap', 'asyncio', 'webbrowser', 'urllib', 'pwd', 'bz2', 'cmd', 'ipaddress', 'os', 'xmlrpc', 'plistlib', 'fileinput', 'bisect', 'trace', 'gettext', 'contextlib', 'collections', 'ensurepip', 'mimetypes', 'ast', 'sndhdr', 'asyncore', 'difflib', 'tty', 'multiprocessing', 'site', '_thread', 'pkgutil', 'readline', 'stat', 'tokenize', 'smtplib', 'heapq', 'queue', 'shutil', 'termios', 'quopri', 'types', 'profile', 'tkinter', 'symbol', 'cProfile', 'sre_constants', 'formatter', 'locale', 'ssl', 'tempfile', 'stringprep', 'random', 'datetime', 'compileall', 'asynchat', 'tracemalloc', 'imp', 'decimal', 'imghdr', 'py_compile', 'pdb', 'shlex', 'selectors', 'wave', 'reprlib', 'winreg', 'logging', 'math', 'glob', 're', 'audioop', 'ftplib', 'base64', 'parser', 'pty', 'doctest', 'uuid', 'builtins', 'json'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': '    ', 'comment_prefix': '  #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'py', 'pyx', 'pyi', 'pxd'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/home/timothycrosley/Projects/isort', profile='', honor_noqa=False, src_paths=(PosixPath('/home/timothycrosley/Projects/isort/src'), PosixPath('/home/timothycrosley/Projects/isort')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'py', 'pyx', 'pyi', 'pxd'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False),
    multi_line_output: Optional[isort.wrap_modes.WrapModes] = None,
    explode: bool = False
) -> str

Returns a multi-line wrapped form of the provided from import statement.

View Source
def import_statement(

    import_start: str,

    from_imports: List[str],

    comments: Sequence[str] = (),

    line_separator: str = "\n",

    config: Config = DEFAULT_CONFIG,

    multi_line_output: Optional[Modes] = None,

    explode: bool = False,

) -> str:

    """Returns a multi-line wrapped form of the provided from import statement."""

    if explode:

        formatter = vertical_hanging_indent

        line_length = 1

        include_trailing_comma = True

    else:

        formatter = formatter_from_string((multi_line_output or config.multi_line_output).name)

        line_length = config.wrap_length or config.line_length

        include_trailing_comma = config.include_trailing_comma

    dynamic_indent = " " * (len(import_start) + 1)

    indent = config.indent

    statement = formatter(

        statement=import_start,

        imports=copy.copy(from_imports),

        white_space=dynamic_indent,

        indent=indent,

        line_length=line_length,

        comments=comments,

        line_separator=line_separator,

        comment_prefix=config.comment_prefix,

        include_trailing_comma=include_trailing_comma,

        remove_comments=config.ignore_comments,

    )

    if config.balanced_wrapping:

        lines = statement.split(line_separator)

        line_count = len(lines)

        if len(lines) > 1:

            minimum_length = min(len(line) for line in lines[:-1])

        else:

            minimum_length = 0

        new_import_statement = statement

        while len(lines[-1]) < minimum_length and len(lines) == line_count and line_length > 10:

            statement = new_import_statement

            line_length -= 1

            new_import_statement = formatter(

                statement=import_start,

                imports=copy.copy(from_imports),

                white_space=dynamic_indent,

                indent=indent,

                line_length=line_length,

                comments=comments,

                line_separator=line_separator,

                comment_prefix=config.comment_prefix,

                include_trailing_comma=include_trailing_comma,

                remove_comments=config.ignore_comments,

            )

            lines = new_import_statement.split(line_separator)

    if statement.count(line_separator) == 0:

        return _wrap_line(statement, line_separator, config)

    return statement

line

def line(
    content: str,
    line_separator: str,
    config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'build', '.pants.d', '.mypy_cache', 'buck-out', '.nox', '.eggs', '.git', 'venv', '.tox', '.direnv', 'dist', '.venv', '.hg', '__pypackages__', '.bzr', 'node_modules', '_build', '.svn'}), extend_skip=frozenset(), skip_glob=frozenset(), extend_skip_glob=frozenset(), skip_gitignore=False, line_length=79, wrap_length=0, line_ending='', sections=('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections=False, known_future_library=frozenset({'__future__'}), known_third_party=frozenset(), known_first_party=frozenset(), known_local_folder=frozenset(), known_standard_library=frozenset({'getopt', 'mailcap', 'imaplib', 'nntplib', 'filecmp', 'threading', 'fnmatch', 'timeit', 'sqlite3', 'configparser', 'bdb', 'runpy', 'chunk', 'curses', 'ntpath', 'posixpath', 'platform', 'html', 'fractions', 'tomllib', 'token', 'zlib', 'code', 'poplib', 'fcntl', 'numbers', 'select', 'codecs', 'binascii', 'weakref', 'zipfile', 'distutils', 'secrets', 'sunau', '_ast', 'smtpd', 'dataclasses', 'http', 'gzip', 'posix', 'functools', 'zoneinfo', 'inspect', 'cgitb', 'symtable', 'pathlib', 'unittest', 'itertools', 'operator', 'fpectl', 'linecache', 'encodings', 'sys', 'resource', 'errno', 'telnetlib', 'traceback', 'idlelib', 'warnings', 'sre', 'io', 'cgi', 'email', 'sre_parse', 'dbm', 'pickletools', 'wsgiref', 'turtledemo', 'optparse', 'concurrent', 'string', 'statistics', 'subprocess', 'modulefinder', 'mailbox', 'lib2to3', 'colorsys', 'signal', 'time', 'shelve', 'calendar', 'pipes', 'importlib', 'unicodedata', 'gc', 'crypt', 'msvcrt', 'csv', 'ossaudiodev', 'msilib', 'pickle', 'hashlib', 'nis', 'aifc', 'hmac', 'winsound', 'graphlib', 'zipapp', 'typing', 'contextvars', 'struct', 'netrc', 'turtle', 'dummy_threading', 'cmath', 'array', 'copy', 'pydoc', 'pstats', 'grp', 'tarfile', 'copyreg', 'uu', 'zipimport', 'tabnanny', 'pyclbr', 'getpass', 'keyword', 'mmap', 'spwd', 'codeop', 'sre_compile', 'dis', 'sysconfig', 'atexit', 'venv', 'argparse', 'syslog', 'rlcompleter', 'xdrlib', 'faulthandler', 'lzma', 'macpath', 'enum', 'abc', 'ctypes', 'pprint', '_dummy_thread', 'test', 'socketserver', 'marshal', 'xml', 'binhex', 'socket', 'sched', 'textwrap', 'asyncio', 'webbrowser', 'urllib', 'pwd', 'bz2', 'cmd', 'ipaddress', 'os', 'xmlrpc', 'plistlib', 'fileinput', 'bisect', 'trace', 'gettext', 'contextlib', 'collections', 'ensurepip', 'mimetypes', 'ast', 'sndhdr', 'asyncore', 'difflib', 'tty', 'multiprocessing', 'site', '_thread', 'pkgutil', 'readline', 'stat', 'tokenize', 'smtplib', 'heapq', 'queue', 'shutil', 'termios', 'quopri', 'types', 'profile', 'tkinter', 'symbol', 'cProfile', 'sre_constants', 'formatter', 'locale', 'ssl', 'tempfile', 'stringprep', 'random', 'datetime', 'compileall', 'asynchat', 'tracemalloc', 'imp', 'decimal', 'imghdr', 'py_compile', 'pdb', 'shlex', 'selectors', 'wave', 'reprlib', 'winreg', 'logging', 'math', 'glob', 're', 'audioop', 'ftplib', 'base64', 'parser', 'pty', 'doctest', 'uuid', 'builtins', 'json'}), extra_standard_library=frozenset(), known_other={}, multi_line_output=<WrapModes.GRID: 0>, forced_separate=(), indent='    ', comment_prefix='  #', length_sort=False, length_sort_straight=False, length_sort_sections=frozenset(), add_imports=frozenset(), remove_imports=frozenset(), append_only=False, reverse_relative=False, force_single_line=False, single_line_exclusions=(), default_section='THIRDPARTY', import_headings={}, import_footers={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, lines_before_imports=-1, lines_after_imports=-1, lines_between_sections=1, lines_between_types=0, combine_as_imports=False, combine_star=False, include_trailing_comma=False, from_first=False, verbose=False, quiet=False, force_adds=False, force_alphabetical_sort_within_sections=False, force_alphabetical_sort=False, force_grid_wrap=0, force_sort_within_sections=False, lexicographical=False, group_by_package=False, ignore_whitespace=False, no_lines_before=frozenset(), no_inline_sort=False, ignore_comments=False, case_sensitive=False, sources=({'py_version': 'py3', 'force_to_top': frozenset(), 'skip': frozenset({'build', '.pants.d', '.mypy_cache', 'buck-out', '.nox', '.eggs', '.git', 'venv', '.tox', '.direnv', 'dist', '.venv', '.hg', '__pypackages__', '.bzr', 'node_modules', '_build', '.svn'}), 'extend_skip': frozenset(), 'skip_glob': frozenset(), 'extend_skip_glob': frozenset(), 'skip_gitignore': False, 'line_length': 79, 'wrap_length': 0, 'line_ending': '', 'sections': ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), 'no_sections': False, 'known_future_library': frozenset({'__future__'}), 'known_third_party': frozenset(), 'known_first_party': frozenset(), 'known_local_folder': frozenset(), 'known_standard_library': frozenset({'getopt', 'mailcap', 'imaplib', 'nntplib', 'filecmp', 'threading', 'fnmatch', 'timeit', 'sqlite3', 'configparser', 'bdb', 'runpy', 'chunk', 'curses', 'ntpath', 'posixpath', 'platform', 'html', 'fractions', 'tomllib', 'token', 'zlib', 'code', 'poplib', 'fcntl', 'numbers', 'select', 'codecs', 'binascii', 'weakref', 'zipfile', 'distutils', 'secrets', 'sunau', '_ast', 'smtpd', 'dataclasses', 'http', 'gzip', 'posix', 'functools', 'zoneinfo', 'inspect', 'cgitb', 'symtable', 'pathlib', 'unittest', 'itertools', 'operator', 'fpectl', 'linecache', 'encodings', 'sys', 'resource', 'errno', 'telnetlib', 'traceback', 'idlelib', 'warnings', 'sre', 'io', 'cgi', 'email', 'sre_parse', 'dbm', 'pickletools', 'wsgiref', 'turtledemo', 'optparse', 'concurrent', 'string', 'statistics', 'subprocess', 'modulefinder', 'mailbox', 'lib2to3', 'colorsys', 'signal', 'time', 'shelve', 'calendar', 'pipes', 'importlib', 'unicodedata', 'gc', 'crypt', 'msvcrt', 'csv', 'ossaudiodev', 'msilib', 'pickle', 'hashlib', 'nis', 'aifc', 'hmac', 'winsound', 'graphlib', 'zipapp', 'typing', 'contextvars', 'struct', 'netrc', 'turtle', 'dummy_threading', 'cmath', 'array', 'copy', 'pydoc', 'pstats', 'grp', 'tarfile', 'copyreg', 'uu', 'zipimport', 'tabnanny', 'pyclbr', 'getpass', 'keyword', 'mmap', 'spwd', 'codeop', 'sre_compile', 'dis', 'sysconfig', 'atexit', 'venv', 'argparse', 'syslog', 'rlcompleter', 'xdrlib', 'faulthandler', 'lzma', 'macpath', 'enum', 'abc', 'ctypes', 'pprint', '_dummy_thread', 'test', 'socketserver', 'marshal', 'xml', 'binhex', 'socket', 'sched', 'textwrap', 'asyncio', 'webbrowser', 'urllib', 'pwd', 'bz2', 'cmd', 'ipaddress', 'os', 'xmlrpc', 'plistlib', 'fileinput', 'bisect', 'trace', 'gettext', 'contextlib', 'collections', 'ensurepip', 'mimetypes', 'ast', 'sndhdr', 'asyncore', 'difflib', 'tty', 'multiprocessing', 'site', '_thread', 'pkgutil', 'readline', 'stat', 'tokenize', 'smtplib', 'heapq', 'queue', 'shutil', 'termios', 'quopri', 'types', 'profile', 'tkinter', 'symbol', 'cProfile', 'sre_constants', 'formatter', 'locale', 'ssl', 'tempfile', 'stringprep', 'random', 'datetime', 'compileall', 'asynchat', 'tracemalloc', 'imp', 'decimal', 'imghdr', 'py_compile', 'pdb', 'shlex', 'selectors', 'wave', 'reprlib', 'winreg', 'logging', 'math', 'glob', 're', 'audioop', 'ftplib', 'base64', 'parser', 'pty', 'doctest', 'uuid', 'builtins', 'json'}), 'extra_standard_library': frozenset(), 'known_other': {}, 'multi_line_output': <WrapModes.GRID: 0>, 'forced_separate': (), 'indent': '    ', 'comment_prefix': '  #', 'length_sort': False, 'length_sort_straight': False, 'length_sort_sections': frozenset(), 'add_imports': frozenset(), 'remove_imports': frozenset(), 'append_only': False, 'reverse_relative': False, 'force_single_line': False, 'single_line_exclusions': (), 'default_section': 'THIRDPARTY', 'import_headings': {}, 'import_footers': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, 'lines_before_imports': -1, 'lines_after_imports': -1, 'lines_between_sections': 1, 'lines_between_types': 0, 'combine_as_imports': False, 'combine_star': False, 'include_trailing_comma': False, 'from_first': False, 'verbose': False, 'quiet': False, 'force_adds': False, 'force_alphabetical_sort_within_sections': False, 'force_alphabetical_sort': False, 'force_grid_wrap': 0, 'force_sort_within_sections': False, 'lexicographical': False, 'group_by_package': False, 'ignore_whitespace': False, 'no_lines_before': frozenset(), 'no_inline_sort': False, 'ignore_comments': False, 'case_sensitive': False, 'sources': (), 'virtual_env': '', 'conda_env': '', 'ensure_newline_before_comments': False, 'directory': '', 'profile': '', 'honor_noqa': False, 'src_paths': (), 'old_finders': False, 'remove_redundant_aliases': False, 'float_to_top': False, 'filter_files': False, 'formatter': '', 'formatting_function': None, 'color_output': False, 'treat_comments_as_code': frozenset(), 'treat_all_comments_as_code': False, 'supported_extensions': frozenset({'py', 'pyx', 'pyi', 'pxd'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'only_modified': False, 'combine_straight_imports': False, 'auto_identify_namespace_packages': True, 'namespace_packages': frozenset(), 'follow_links': True, 'indented_import_headings': True, 'honor_case_in_force_sorted_sections': False, 'sort_relative_in_force_sorted_sections': False, 'overwrite_in_place': False, 'reverse_sort': False, 'star_first': False, 'git_ls_files': {}, 'format_error': '{error}: {message}', 'format_success': '{success}: {message}', 'sort_order': 'natural', 'sort_reexports': False, 'split_on_trailing_comma': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/home/timothycrosley/Projects/isort', profile='', honor_noqa=False, src_paths=(PosixPath('/home/timothycrosley/Projects/isort/src'), PosixPath('/home/timothycrosley/Projects/isort')), old_finders=False, remove_redundant_aliases=False, float_to_top=False, filter_files=False, formatter='', formatting_function=None, color_output=False, treat_comments_as_code=frozenset(), treat_all_comments_as_code=False, supported_extensions=frozenset({'py', 'pyx', 'pyi', 'pxd'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False, only_modified=False, combine_straight_imports=False, auto_identify_namespace_packages=True, namespace_packages=frozenset(), follow_links=True, indented_import_headings=True, honor_case_in_force_sorted_sections=False, sort_relative_in_force_sorted_sections=False, overwrite_in_place=False, reverse_sort=False, star_first=False, git_ls_files={}, format_error='{error}: {message}', format_success='{success}: {message}', sort_order='natural', sort_reexports=False, split_on_trailing_comma=False)
) -> str

Returns a line wrapped to the specified line-length, if possible.

View Source
def line(content: str, line_separator: str, config: Config = DEFAULT_CONFIG) -> str:

    """Returns a line wrapped to the specified line-length, if possible."""

    wrap_mode = config.multi_line_output

    if len(content) > config.line_length and wrap_mode != Modes.NOQA:  # type: ignore

        line_without_comment = content

        comment = None

        if "#" in content:

            line_without_comment, comment = content.split("#", 1)

        for splitter in ("import ", "cimport ", ".", "as "):

            exp = r"\b" + re.escape(splitter) + r"\b"

            if re.search(exp, line_without_comment) and not line_without_comment.strip().startswith(

                splitter

            ):

                line_parts = re.split(exp, line_without_comment)

                if comment and not (config.use_parentheses and "noqa" in comment):

                    _comma_maybe = (

                        ","

                        if (

                            config.include_trailing_comma

                            and config.use_parentheses

                            and not line_without_comment.rstrip().endswith(",")

                        )

                        else ""

                    )

                    line_parts[

                        -1

                    ] = f"{line_parts[-1].strip()}{_comma_maybe}{config.comment_prefix}{comment}"

                next_line = []

                while (len(content) + 2) > (

                    config.wrap_length or config.line_length

                ) and line_parts:

                    next_line.append(line_parts.pop())

                    content = splitter.join(line_parts)

                if not content:

                    content = next_line.pop()

                cont_line = _wrap_line(

                    config.indent + splitter.join(next_line).lstrip(),

                    line_separator,

                    config,

                )

                if config.use_parentheses:

                    if splitter == "as ":

                        output = f"{content}{splitter}{cont_line.lstrip()}"

                    else:

                        _comma = "," if config.include_trailing_comma and not comment else ""

                        if wrap_mode in (

                            Modes.VERTICAL_HANGING_INDENT,  # type: ignore

                            Modes.VERTICAL_GRID_GROUPED,  # type: ignore

                        ):

                            _separator = line_separator

                        else:

                            _separator = ""

                        _comment = ""

                        if comment and "noqa" in comment:

                            _comment = f"{config.comment_prefix}{comment}"

                            cont_line = cont_line.rstrip()

                            _comma = "," if config.include_trailing_comma else ""

                        output = (

                            f"{content}{splitter}({_comment}"

                            f"{line_separator}{cont_line}{_comma}{_separator})"

                        )

                    lines = output.split(line_separator)

                    if config.comment_prefix in lines[-1] and lines[-1].endswith(")"):

                        content, comment = lines[-1].split(config.comment_prefix, 1)

                        lines[-1] = content + ")" + config.comment_prefix + comment[:-1]

                    return line_separator.join(lines)

                return f"{content}{splitter}\\{line_separator}{cont_line}"

    elif len(content) > config.line_length and wrap_mode == Modes.NOQA and "# NOQA" not in content:  # type: ignore

        return f"{content}{config.comment_prefix} NOQA"

    return content