Skip to content

Module isort.api

View Source
import shutil

import sys

from io import StringIO

from pathlib import Path

from typing import Optional, TextIO, Union, cast

from warnings import warn

from isort import core

from . import io

from .exceptions import (

    ExistingSyntaxErrors,

    FileSkipComment,

    FileSkipSetting,

    IntroducedSyntaxErrors,

)

from .format import ask_whether_to_apply_changes_to_file, create_terminal_printer, show_unified_diff

from .io import Empty

from .place import module as place_module  # noqa: F401

from .place import module_with_reason as place_module_with_reason  # noqa: F401

from .settings import DEFAULT_CONFIG, Config

def sort_code_string(

    code: str,

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = False,

    show_diff: Union[bool, TextIO] = False,

    **config_kwargs,

):

    """Sorts any imports within the provided code string, returning a new string with them sorted.

    - **code**: The string of code with imports that need to be sorted.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - ****config_kwargs**: Any config modifications.

    """

    input_stream = StringIO(code)

    output_stream = StringIO()

    config = _config(path=file_path, config=config, **config_kwargs)

    sort_stream(

        input_stream,

        output_stream,

        extension=extension,

        config=config,

        file_path=file_path,

        disregard_skip=disregard_skip,

        show_diff=show_diff,

    )

    output_stream.seek(0)

    return output_stream.read()

def check_code_string(

    code: str,

    show_diff: Union[bool, TextIO] = False,

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = False,

    **config_kwargs,

) -> bool:

    """Checks the order, format, and categorization of imports within the provided code string.

    Returns `True` if everything is correct, otherwise `False`.

    - **code**: The string of code with imports that need to be sorted.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - ****config_kwargs**: Any config modifications.

    """

    config = _config(path=file_path, config=config, **config_kwargs)

    return check_stream(

        StringIO(code),

        show_diff=show_diff,

        extension=extension,

        config=config,

        file_path=file_path,

        disregard_skip=disregard_skip,

    )

def sort_stream(

    input_stream: TextIO,

    output_stream: TextIO,

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = False,

    show_diff: Union[bool, TextIO] = False,

    **config_kwargs,

) -> bool:

    """Sorts any imports within the provided code stream, outputs to the provided output stream.

     Returns `True` if anything is modified from the original input stream, otherwise `False`.

    - **input_stream**: The stream of code with imports that need to be sorted.

    - **output_stream**: The stream where sorted imports should be written to.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - ****config_kwargs**: Any config modifications.

    """

    if show_diff:

        _output_stream = StringIO()

        _input_stream = StringIO(input_stream.read())

        changed = sort_stream(

            input_stream=_input_stream,

            output_stream=_output_stream,

            extension=extension,

            config=config,

            file_path=file_path,

            disregard_skip=disregard_skip,

            **config_kwargs,

        )

        _output_stream.seek(0)

        _input_stream.seek(0)

        show_unified_diff(

            file_input=_input_stream.read(),

            file_output=_output_stream.read(),

            file_path=file_path,

            output=output_stream if show_diff is True else cast(TextIO, show_diff),

            color_output=config.color_output,

        )

        return changed

    config = _config(path=file_path, config=config, **config_kwargs)

    content_source = str(file_path or "Passed in content")

    if not disregard_skip:

        if file_path and config.is_skipped(file_path):

            raise FileSkipSetting(content_source)

    _internal_output = output_stream

    if config.atomic:

        try:

            file_content = input_stream.read()

            compile(file_content, content_source, "exec", 0, 1)

            input_stream = StringIO(file_content)

        except SyntaxError:

            raise ExistingSyntaxErrors(content_source)

        if not output_stream.readable():

            _internal_output = StringIO()

    try:

        changed = core.process(

            input_stream,

            _internal_output,

            extension=extension or (file_path and file_path.suffix.lstrip(".")) or "py",

            config=config,

        )

    except FileSkipComment:

        raise FileSkipComment(content_source)

    if config.atomic:

        _internal_output.seek(0)

        try:

            compile(_internal_output.read(), content_source, "exec", 0, 1)

            _internal_output.seek(0)

            if _internal_output != output_stream:

                output_stream.write(_internal_output.read())

        except SyntaxError:  # pragma: no cover

            raise IntroducedSyntaxErrors(content_source)

    return changed

def check_stream(

    input_stream: TextIO,

    show_diff: Union[bool, TextIO] = False,

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = False,

    **config_kwargs,

) -> bool:

    """Checks any imports within the provided code stream, returning `False` if any unsorted or

    incorrectly imports are found or `True` if no problems are identified.

    - **input_stream**: The stream of code with imports that need to be sorted.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - ****config_kwargs**: Any config modifications.

    """

    config = _config(path=file_path, config=config, **config_kwargs)

    changed: bool = sort_stream(

        input_stream=input_stream,

        output_stream=Empty,

        extension=extension,

        config=config,

        file_path=file_path,

        disregard_skip=disregard_skip,

    )

    printer = create_terminal_printer(color=config.color_output)

    if not changed:

        if config.verbose:

            printer.success(f"{file_path or ''} Everything Looks Good!")

        return True

    else:

        printer.error(f"{file_path or ''} Imports are incorrectly sorted and/or formatted.")

        if show_diff:

            output_stream = StringIO()

            input_stream.seek(0)

            file_contents = input_stream.read()

            sort_stream(

                input_stream=StringIO(file_contents),

                output_stream=output_stream,

                extension=extension,

                config=config,

                file_path=file_path,

                disregard_skip=disregard_skip,

            )

            output_stream.seek(0)

            show_unified_diff(

                file_input=file_contents,

                file_output=output_stream.read(),

                file_path=file_path,

                output=None if show_diff is True else cast(TextIO, show_diff),

                color_output=config.color_output,

            )

        return False

def check_file(

    filename: Union[str, Path],

    show_diff: Union[bool, TextIO] = False,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = True,

    extension: Optional[str] = None,

    **config_kwargs,

) -> bool:

    """Checks any imports within the provided file, returning `False` if any unsorted or

    incorrectly imports are found or `True` if no problems are identified.

    - **filename**: The name or Path of the file to check.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - ****config_kwargs**: Any config modifications.

    """

    with io.File.read(filename) as source_file:

        return check_stream(

            source_file.stream,

            show_diff=show_diff,

            extension=extension,

            config=config,

            file_path=file_path or source_file.path,

            disregard_skip=disregard_skip,

            **config_kwargs,

        )

def sort_file(

    filename: Union[str, Path],

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = True,

    ask_to_apply: bool = False,

    show_diff: Union[bool, TextIO] = False,

    write_to_stdout: bool = False,

    **config_kwargs,

) -> bool:

    """Sorts and formats any groups of imports imports within the provided file or Path.

     Returns `True` if the file has been changed, otherwise `False`.

    - **filename**: The name or Path of the file to format.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - **ask_to_apply**: If `True`, prompt before applying any changes.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - **write_to_stdout**: If `True`, write to stdout instead of the input file.

    - ****config_kwargs**: Any config modifications.

    """

    with io.File.read(filename) as source_file:

        actual_file_path = file_path or source_file.path

        config = _config(path=actual_file_path, config=config, **config_kwargs)

        changed: bool = False

        try:

            if write_to_stdout:

                changed = sort_stream(

                    input_stream=source_file.stream,

                    output_stream=sys.stdout,

                    config=config,

                    file_path=actual_file_path,

                    disregard_skip=disregard_skip,

                    extension=extension,

                )

            else:

                tmp_file = source_file.path.with_suffix(source_file.path.suffix + ".isorted")

                try:

                    with tmp_file.open(

                        "w", encoding=source_file.encoding, newline=""

                    ) as output_stream:

                        shutil.copymode(filename, tmp_file)

                        changed = sort_stream(

                            input_stream=source_file.stream,

                            output_stream=output_stream,

                            config=config,

                            file_path=actual_file_path,

                            disregard_skip=disregard_skip,

                            extension=extension,

                        )

                    if changed:

                        if show_diff or ask_to_apply:

                            source_file.stream.seek(0)

                            with tmp_file.open(

                                encoding=source_file.encoding, newline=""

                            ) as tmp_out:

                                show_unified_diff(

                                    file_input=source_file.stream.read(),

                                    file_output=tmp_out.read(),

                                    file_path=actual_file_path,

                                    output=None if show_diff is True else cast(TextIO, show_diff),

                                    color_output=config.color_output,

                                )

                                if show_diff or (

                                    ask_to_apply

                                    and not ask_whether_to_apply_changes_to_file(

                                        str(source_file.path)

                                    )

                                ):

                                    return False

                        source_file.stream.close()

                        tmp_file.replace(source_file.path)

                        if not config.quiet:

                            print(f"Fixing {source_file.path}")

                finally:

                    try:  # Python 3.8+: use `missing_ok=True` instead of try except.

                        tmp_file.unlink()

                    except FileNotFoundError:

                        pass

        except ExistingSyntaxErrors:

            warn(f"{actual_file_path} unable to sort due to existing syntax errors")

        except IntroducedSyntaxErrors:  # pragma: no cover

            warn(f"{actual_file_path} unable to sort as isort introduces new syntax errors")

        return changed

def _config(

    path: Optional[Path] = None, config: Config = DEFAULT_CONFIG, **config_kwargs

) -> Config:

    if path:

        if (

            config is DEFAULT_CONFIG

            and "settings_path" not in config_kwargs

            and "settings_file" not in config_kwargs

        ):

            config_kwargs["settings_path"] = path

    if config_kwargs:

        if config is not DEFAULT_CONFIG:

            raise ValueError(

                "You can either specify custom configuration options using kwargs or "

                "passing in a Config object. Not Both!"

            )

        config = Config(**config_kwargs)

    return config

Functions

check_code_string

def check_code_string(
    code: str,
    show_diff: Union[bool, TextIO] = False,
    extension: Union[str, NoneType] = None,
    config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), 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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), 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={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, 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, 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({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), '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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), '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': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, '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, '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': frozenset(), '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', 'pxd', 'pyi'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/home/timothy/Projects/isort', profile='', honor_noqa=False, src_paths=frozenset({PosixPath('/home/timothy/Projects/isort'), PosixPath('/home/timothy/Projects/isort/src')}), 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', 'pxd', 'pyi'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False),
    file_path: Union[pathlib.Path, NoneType] = None,
    disregard_skip: bool = False,
    **config_kwargs
) -> bool

Checks the order, format, and categorization of imports within the provided code string. Returns True if everything is correct, otherwise False.

  • code: The string of code with imports that need to be sorted.
  • show_diff: If True the changes that need to be done will be printed to stdout, if a TextIO stream is provided results will be written to it, otherwise no diff will be computed.
  • extension: The file extension that contains imports. Defaults to filename extension or py.
  • config: The config object to use when sorting imports.
  • file_path: The disk location where the code string was pulled from.
  • disregard_skip: set to True if you want to ignore a skip set in config for this file.
  • **config_kwargs: Any config modifications.
View Source
def check_code_string(

    code: str,

    show_diff: Union[bool, TextIO] = False,

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = False,

    **config_kwargs,

) -> bool:

    """Checks the order, format, and categorization of imports within the provided code string.

    Returns `True` if everything is correct, otherwise `False`.

    - **code**: The string of code with imports that need to be sorted.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - ****config_kwargs**: Any config modifications.

    """

    config = _config(path=file_path, config=config, **config_kwargs)

    return check_stream(

        StringIO(code),

        show_diff=show_diff,

        extension=extension,

        config=config,

        file_path=file_path,

        disregard_skip=disregard_skip,

    )

check_file

def check_file(
    filename: Union[str, pathlib.Path],
    show_diff: Union[bool, TextIO] = False,
    config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), 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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), 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={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, 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, 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({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), '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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), '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': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, '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, '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': frozenset(), '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', 'pxd', 'pyi'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/home/timothy/Projects/isort', profile='', honor_noqa=False, src_paths=frozenset({PosixPath('/home/timothy/Projects/isort'), PosixPath('/home/timothy/Projects/isort/src')}), 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', 'pxd', 'pyi'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False),
    file_path: Union[pathlib.Path, NoneType] = None,
    disregard_skip: bool = True,
    extension: Union[str, NoneType] = None,
    **config_kwargs
) -> bool

Checks any imports within the provided file, returning False if any unsorted or incorrectly imports are found or True if no problems are identified.

  • filename: The name or Path of the file to check.
  • show_diff: If True the changes that need to be done will be printed to stdout, if a TextIO stream is provided results will be written to it, otherwise no diff will be computed.
  • config: The config object to use when sorting imports.
  • file_path: The disk location where the code string was pulled from.
  • disregard_skip: set to True if you want to ignore a skip set in config for this file.
  • extension: The file extension that contains imports. Defaults to filename extension or py.
  • **config_kwargs: Any config modifications.
View Source
def check_file(

    filename: Union[str, Path],

    show_diff: Union[bool, TextIO] = False,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = True,

    extension: Optional[str] = None,

    **config_kwargs,

) -> bool:

    """Checks any imports within the provided file, returning `False` if any unsorted or

    incorrectly imports are found or `True` if no problems are identified.

    - **filename**: The name or Path of the file to check.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - ****config_kwargs**: Any config modifications.

    """

    with io.File.read(filename) as source_file:

        return check_stream(

            source_file.stream,

            show_diff=show_diff,

            extension=extension,

            config=config,

            file_path=file_path or source_file.path,

            disregard_skip=disregard_skip,

            **config_kwargs,

        )

check_stream

def check_stream(
    input_stream: <class 'TextIO'>,
    show_diff: Union[bool, TextIO] = False,
    extension: Union[str, NoneType] = None,
    config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), 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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), 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={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, 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, 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({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), '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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), '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': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, '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, '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': frozenset(), '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', 'pxd', 'pyi'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/home/timothy/Projects/isort', profile='', honor_noqa=False, src_paths=frozenset({PosixPath('/home/timothy/Projects/isort'), PosixPath('/home/timothy/Projects/isort/src')}), 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', 'pxd', 'pyi'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False),
    file_path: Union[pathlib.Path, NoneType] = None,
    disregard_skip: bool = False,
    **config_kwargs
) -> bool

Checks any imports within the provided code stream, returning False if any unsorted or incorrectly imports are found or True if no problems are identified.

  • input_stream: The stream of code with imports that need to be sorted.
  • show_diff: If True the changes that need to be done will be printed to stdout, if a TextIO stream is provided results will be written to it, otherwise no diff will be computed.
  • extension: The file extension that contains imports. Defaults to filename extension or py.
  • config: The config object to use when sorting imports.
  • file_path: The disk location where the code string was pulled from.
  • disregard_skip: set to True if you want to ignore a skip set in config for this file.
  • **config_kwargs: Any config modifications.
View Source
def check_stream(

    input_stream: TextIO,

    show_diff: Union[bool, TextIO] = False,

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = False,

    **config_kwargs,

) -> bool:

    """Checks any imports within the provided code stream, returning `False` if any unsorted or

    incorrectly imports are found or `True` if no problems are identified.

    - **input_stream**: The stream of code with imports that need to be sorted.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - ****config_kwargs**: Any config modifications.

    """

    config = _config(path=file_path, config=config, **config_kwargs)

    changed: bool = sort_stream(

        input_stream=input_stream,

        output_stream=Empty,

        extension=extension,

        config=config,

        file_path=file_path,

        disregard_skip=disregard_skip,

    )

    printer = create_terminal_printer(color=config.color_output)

    if not changed:

        if config.verbose:

            printer.success(f"{file_path or ''} Everything Looks Good!")

        return True

    else:

        printer.error(f"{file_path or ''} Imports are incorrectly sorted and/or formatted.")

        if show_diff:

            output_stream = StringIO()

            input_stream.seek(0)

            file_contents = input_stream.read()

            sort_stream(

                input_stream=StringIO(file_contents),

                output_stream=output_stream,

                extension=extension,

                config=config,

                file_path=file_path,

                disregard_skip=disregard_skip,

            )

            output_stream.seek(0)

            show_unified_diff(

                file_input=file_contents,

                file_output=output_stream.read(),

                file_path=file_path,

                output=None if show_diff is True else cast(TextIO, show_diff),

                color_output=config.color_output,

            )

        return False

sort_code_string

def sort_code_string(
    code: str,
    extension: Union[str, NoneType] = None,
    config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), 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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), 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={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, 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, 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({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), '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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), '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': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, '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, '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': frozenset(), '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', 'pxd', 'pyi'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/home/timothy/Projects/isort', profile='', honor_noqa=False, src_paths=frozenset({PosixPath('/home/timothy/Projects/isort'), PosixPath('/home/timothy/Projects/isort/src')}), 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', 'pxd', 'pyi'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False),
    file_path: Union[pathlib.Path, NoneType] = None,
    disregard_skip: bool = False,
    show_diff: Union[bool, TextIO] = False,
    **config_kwargs
)

Sorts any imports within the provided code string, returning a new string with them sorted.

  • code: The string of code with imports that need to be sorted.
  • extension: The file extension that contains imports. Defaults to filename extension or py.
  • config: The config object to use when sorting imports.
  • file_path: The disk location where the code string was pulled from.
  • disregard_skip: set to True if you want to ignore a skip set in config for this file.
  • show_diff: If True the changes that need to be done will be printed to stdout, if a TextIO stream is provided results will be written to it, otherwise no diff will be computed.
  • **config_kwargs: Any config modifications.
View Source
def sort_code_string(

    code: str,

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = False,

    show_diff: Union[bool, TextIO] = False,

    **config_kwargs,

):

    """Sorts any imports within the provided code string, returning a new string with them sorted.

    - **code**: The string of code with imports that need to be sorted.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - ****config_kwargs**: Any config modifications.

    """

    input_stream = StringIO(code)

    output_stream = StringIO()

    config = _config(path=file_path, config=config, **config_kwargs)

    sort_stream(

        input_stream,

        output_stream,

        extension=extension,

        config=config,

        file_path=file_path,

        disregard_skip=disregard_skip,

        show_diff=show_diff,

    )

    output_stream.seek(0)

    return output_stream.read()

sort_file

def sort_file(
    filename: Union[str, pathlib.Path],
    extension: Union[str, NoneType] = None,
    config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), 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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), 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={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, 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, 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({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), '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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), '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': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, '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, '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': frozenset(), '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', 'pxd', 'pyi'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/home/timothy/Projects/isort', profile='', honor_noqa=False, src_paths=frozenset({PosixPath('/home/timothy/Projects/isort'), PosixPath('/home/timothy/Projects/isort/src')}), 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', 'pxd', 'pyi'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False),
    file_path: Union[pathlib.Path, NoneType] = None,
    disregard_skip: bool = True,
    ask_to_apply: bool = False,
    show_diff: Union[bool, TextIO] = False,
    write_to_stdout: bool = False,
    **config_kwargs
) -> bool

Sorts and formats any groups of imports imports within the provided file or Path. Returns True if the file has been changed, otherwise False.

  • filename: The name or Path of the file to format.
  • extension: The file extension that contains imports. Defaults to filename extension or py.
  • config: The config object to use when sorting imports.
  • file_path: The disk location where the code string was pulled from.
  • disregard_skip: set to True if you want to ignore a skip set in config for this file.
  • ask_to_apply: If True, prompt before applying any changes.
  • show_diff: If True the changes that need to be done will be printed to stdout, if a TextIO stream is provided results will be written to it, otherwise no diff will be computed.
  • write_to_stdout: If True, write to stdout instead of the input file.
  • **config_kwargs: Any config modifications.
View Source
def sort_file(

    filename: Union[str, Path],

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = True,

    ask_to_apply: bool = False,

    show_diff: Union[bool, TextIO] = False,

    write_to_stdout: bool = False,

    **config_kwargs,

) -> bool:

    """Sorts and formats any groups of imports imports within the provided file or Path.

     Returns `True` if the file has been changed, otherwise `False`.

    - **filename**: The name or Path of the file to format.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - **ask_to_apply**: If `True`, prompt before applying any changes.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - **write_to_stdout**: If `True`, write to stdout instead of the input file.

    - ****config_kwargs**: Any config modifications.

    """

    with io.File.read(filename) as source_file:

        actual_file_path = file_path or source_file.path

        config = _config(path=actual_file_path, config=config, **config_kwargs)

        changed: bool = False

        try:

            if write_to_stdout:

                changed = sort_stream(

                    input_stream=source_file.stream,

                    output_stream=sys.stdout,

                    config=config,

                    file_path=actual_file_path,

                    disregard_skip=disregard_skip,

                    extension=extension,

                )

            else:

                tmp_file = source_file.path.with_suffix(source_file.path.suffix + ".isorted")

                try:

                    with tmp_file.open(

                        "w", encoding=source_file.encoding, newline=""

                    ) as output_stream:

                        shutil.copymode(filename, tmp_file)

                        changed = sort_stream(

                            input_stream=source_file.stream,

                            output_stream=output_stream,

                            config=config,

                            file_path=actual_file_path,

                            disregard_skip=disregard_skip,

                            extension=extension,

                        )

                    if changed:

                        if show_diff or ask_to_apply:

                            source_file.stream.seek(0)

                            with tmp_file.open(

                                encoding=source_file.encoding, newline=""

                            ) as tmp_out:

                                show_unified_diff(

                                    file_input=source_file.stream.read(),

                                    file_output=tmp_out.read(),

                                    file_path=actual_file_path,

                                    output=None if show_diff is True else cast(TextIO, show_diff),

                                    color_output=config.color_output,

                                )

                                if show_diff or (

                                    ask_to_apply

                                    and not ask_whether_to_apply_changes_to_file(

                                        str(source_file.path)

                                    )

                                ):

                                    return False

                        source_file.stream.close()

                        tmp_file.replace(source_file.path)

                        if not config.quiet:

                            print(f"Fixing {source_file.path}")

                finally:

                    try:  # Python 3.8+: use `missing_ok=True` instead of try except.

                        tmp_file.unlink()

                    except FileNotFoundError:

                        pass

        except ExistingSyntaxErrors:

            warn(f"{actual_file_path} unable to sort due to existing syntax errors")

        except IntroducedSyntaxErrors:  # pragma: no cover

            warn(f"{actual_file_path} unable to sort as isort introduces new syntax errors")

        return changed

sort_stream

def sort_stream(
    input_stream: <class 'TextIO'>,
    output_stream: <class 'TextIO'>,
    extension: Union[str, NoneType] = None,
    config: isort.settings.Config = Config(py_version='py3', force_to_top=frozenset(), skip=frozenset({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), 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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), 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={}, balanced_wrapping=False, use_parentheses=False, order_by_type=True, atomic=False, 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, 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({'venv', 'dist', '.bzr', 'build', 'buck-out', '.eggs', '.venv', '.direnv', '.git', '.nox', '.mypy_cache', '.pants.d', '.hg', '.svn', '_build', '.tox', 'node_modules'}), '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({'errno', 'venv', 're', 'io', 'uu', 'contextlib', 'uuid', 'multiprocessing', 'numbers', 'nis', 'distutils', 'os', 'itertools', 'abc', 'email', 'socketserver', 'secrets', 'atexit', 'plistlib', 'tkinter', 'html', 'select', 'sre_compile', 'posix', 'xmlrpc', 'importlib', 'pipes', 'wave', 'audioop', 'difflib', 'zipimport', 'hashlib', 'sunau', 'trace', 'marshal', 'http', 'sndhdr', 'nntplib', 'textwrap', 'symbol', 'chunk', 'ctypes', 'tokenize', 'msilib', 'mailcap', 'codeop', 'sysconfig', 'posixpath', 'selectors', 'ossaudiodev', 'winsound', 'fcntl', 'hmac', 'syslog', 'macpath', 'enum', 'bz2', 'bisect', 'msvcrt', 'winreg', 'imp', 'reprlib', 'shutil', 'dummy_threading', 'dbm', 'readline', 'binascii', 'sre_constants', 'modulefinder', 'json', 'code', 'compileall', 'cmd', 'turtle', 'curses', '_dummy_thread', 'pyclbr', 'locale', 'random', 'inspect', 'types', 'imaplib', 'shelve', 'urllib', 'zipapp', 'argparse', 'test', 'pkgutil', 'cgitb', 'sys', 'functools', 'grp', 'profile', 'doctest', 'wsgiref', 'unicodedata', 'smtplib', 'site', 'pathlib', 'getpass', 'pydoc', 'optparse', 'stringprep', 'csv', 'smtpd', 'tarfile', 'codecs', 'xml', 'calendar', 'xdrlib', 'cProfile', 'ipaddress', 'copyreg', 'formatter', 'pty', 'cgi', 'zlib', 'resource', 'configparser', 'dis', 'statistics', 'warnings', 'turtledemo', 'sqlite3', 'ast', 'copy', 'spwd', 'mimetypes', 'tty', 'token', 'asyncore', 'bdb', 'py_compile', 'colorsys', 'faulthandler', 'tabnanny', 'tempfile', 'weakref', 'rlcompleter', 'pprint', 'asynchat', 'gc', 'socket', 'datetime', 'ftplib', 'crypt', 'contextvars', 'decimal', 'getopt', 'sre_parse', 'asyncio', 'subprocess', '_thread', 'sched', 'platform', 'quopri', 'operator', 'collections', 'sre', 'stat', 'threading', 'pstats', 'queue', 'symtable', 'ntpath', 'timeit', 'traceback', 'pickletools', 'binhex', 'ensurepip', 'pwd', 'heapq', 'ssl', 'linecache', 'termios', 'tracemalloc', 'fnmatch', 'struct', 'dataclasses', 'time', 'pdb', 'shlex', 'webbrowser', 'builtins', 'glob', 'math', 'typing', 'gettext', 'aifc', 'fractions', 'parser', 'string', 'lib2to3', 'mailbox', 'zipfile', 'netrc', 'lzma', 'keyword', 'imghdr', 'unittest', 'fileinput', 'concurrent', 'fpectl', 'pickle', 'runpy', 'mmap', 'telnetlib', 'signal', 'poplib', 'filecmp', 'base64', 'gzip', 'encodings', 'cmath', 'logging', 'array'}), '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': {}, 'balanced_wrapping': False, 'use_parentheses': False, 'order_by_type': True, 'atomic': False, '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, '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': frozenset(), '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', 'pxd', 'pyi'}), 'blocked_extensions': frozenset({'pex'}), 'constants': frozenset(), 'classes': frozenset(), 'variables': frozenset(), 'dedup_headings': False, 'only_sections': False, 'source': 'defaults'},), virtual_env='', conda_env='', ensure_newline_before_comments=False, directory='/home/timothy/Projects/isort', profile='', honor_noqa=False, src_paths=frozenset({PosixPath('/home/timothy/Projects/isort'), PosixPath('/home/timothy/Projects/isort/src')}), 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', 'pxd', 'pyi'}), blocked_extensions=frozenset({'pex'}), constants=frozenset(), classes=frozenset(), variables=frozenset(), dedup_headings=False, only_sections=False),
    file_path: Union[pathlib.Path, NoneType] = None,
    disregard_skip: bool = False,
    show_diff: Union[bool, TextIO] = False,
    **config_kwargs
) -> bool

Sorts any imports within the provided code stream, outputs to the provided output stream. Returns True if anything is modified from the original input stream, otherwise False.

  • input_stream: The stream of code with imports that need to be sorted.
  • output_stream: The stream where sorted imports should be written to.
  • extension: The file extension that contains imports. Defaults to filename extension or py.
  • config: The config object to use when sorting imports.
  • file_path: The disk location where the code string was pulled from.
  • disregard_skip: set to True if you want to ignore a skip set in config for this file.
  • show_diff: If True the changes that need to be done will be printed to stdout, if a TextIO stream is provided results will be written to it, otherwise no diff will be computed.
  • **config_kwargs: Any config modifications.
View Source
def sort_stream(

    input_stream: TextIO,

    output_stream: TextIO,

    extension: Optional[str] = None,

    config: Config = DEFAULT_CONFIG,

    file_path: Optional[Path] = None,

    disregard_skip: bool = False,

    show_diff: Union[bool, TextIO] = False,

    **config_kwargs,

) -> bool:

    """Sorts any imports within the provided code stream, outputs to the provided output stream.

     Returns `True` if anything is modified from the original input stream, otherwise `False`.

    - **input_stream**: The stream of code with imports that need to be sorted.

    - **output_stream**: The stream where sorted imports should be written to.

    - **extension**: The file extension that contains imports. Defaults to filename extension or py.

    - **config**: The config object to use when sorting imports.

    - **file_path**: The disk location where the code string was pulled from.

    - **disregard_skip**: set to `True` if you want to ignore a skip set in config for this file.

    - **show_diff**: If `True` the changes that need to be done will be printed to stdout, if a

    TextIO stream is provided results will be written to it, otherwise no diff will be computed.

    - ****config_kwargs**: Any config modifications.

    """

    if show_diff:

        _output_stream = StringIO()

        _input_stream = StringIO(input_stream.read())

        changed = sort_stream(

            input_stream=_input_stream,

            output_stream=_output_stream,

            extension=extension,

            config=config,

            file_path=file_path,

            disregard_skip=disregard_skip,

            **config_kwargs,

        )

        _output_stream.seek(0)

        _input_stream.seek(0)

        show_unified_diff(

            file_input=_input_stream.read(),

            file_output=_output_stream.read(),

            file_path=file_path,

            output=output_stream if show_diff is True else cast(TextIO, show_diff),

            color_output=config.color_output,

        )

        return changed

    config = _config(path=file_path, config=config, **config_kwargs)

    content_source = str(file_path or "Passed in content")

    if not disregard_skip:

        if file_path and config.is_skipped(file_path):

            raise FileSkipSetting(content_source)

    _internal_output = output_stream

    if config.atomic:

        try:

            file_content = input_stream.read()

            compile(file_content, content_source, "exec", 0, 1)

            input_stream = StringIO(file_content)

        except SyntaxError:

            raise ExistingSyntaxErrors(content_source)

        if not output_stream.readable():

            _internal_output = StringIO()

    try:

        changed = core.process(

            input_stream,

            _internal_output,

            extension=extension or (file_path and file_path.suffix.lstrip(".")) or "py",

            config=config,

        )

    except FileSkipComment:

        raise FileSkipComment(content_source)

    if config.atomic:

        _internal_output.seek(0)

        try:

            compile(_internal_output.read(), content_source, "exec", 0, 1)

            _internal_output.seek(0)

            if _internal_output != output_stream:

                output_stream.write(_internal_output.read())

        except SyntaxError:  # pragma: no cover

            raise IntroducedSyntaxErrors(content_source)

    return changed