API Reference¶
isort.api¶
- class isort.api.ImportKey(*values)[source]¶
Bases:
EnumDefines how to key an individual import, generally for deduping.
Import keys are defined from less to more specific:
from x.y import z as a
PACKAGE: x MODULE: y ATTRIBUTE: z ALIAS: a
-
ALIAS =
4¶
-
ATTRIBUTE =
3¶
-
MODULE =
2¶
-
PACKAGE =
1¶
-
ALIAS =
-
isort.api.check_code_string(code: str, show_diff: bool | TextIO =
False, extension: str | None =None, config: Config =DEFAULT_CONFIG, file_path: Path | None =None, disregard_skip: bool =False, **config_kwargs: Any) bool[source]¶ 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.
-
isort.api.check_file(filename: str | Path, show_diff: bool | TextIO =
False, config: Config =DEFAULT_CONFIG, file_path: Path | None =None, disregard_skip: bool =True, extension: str | None =None, **config_kwargs: Any) bool[source]¶ 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.
-
isort.api.check_stream(input_stream: TextIO, show_diff: bool | TextIO =
False, extension: str | None =None, config: Config =DEFAULT_CONFIG, file_path: Path | None =None, disregard_skip: bool =False, **config_kwargs: Any) bool[source]¶ 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.
-
isort.api.find_imports_in_code(code: str, config: Config =
DEFAULT_CONFIG, file_path: Path | None =None, unique: bool | ImportKey =False, top_only: bool =False, **config_kwargs: Any) Iterator[Import][source]¶ Finds and returns all imports within the provided code string.
code: The string of code with imports that need to be sorted.
config: The config object to use when sorting imports.
file_path: The disk location where the code string was pulled from.
unique: If True, only the first instance of an import is returned.
top_only: If True, only return imports that occur before the first function or class.
**config_kwargs: Any config modifications.
-
isort.api.find_imports_in_file(filename: str | Path, config: Config =
DEFAULT_CONFIG, file_path: Path | None =None, unique: bool | ImportKey =False, top_only: bool =False, **config_kwargs: Any) Iterator[Import][source]¶ Finds and returns all imports within the provided source file.
filename: The name or Path of the file to look for imports in.
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.
unique: If True, only the first instance of an import is returned.
top_only: If True, only return imports that occur before the first function or class.
**config_kwargs: Any config modifications.
-
isort.api.find_imports_in_paths(paths: Iterator[str | Path], config: Config =
DEFAULT_CONFIG, file_path: Path | None =None, unique: bool | ImportKey =False, top_only: bool =False, **config_kwargs: Any) Iterator[Import][source]¶ Finds and returns all imports within the provided source paths.
paths: A collection of paths to recursively look for imports within.
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.
unique: If True, only the first instance of an import is returned.
top_only: If True, only return imports that occur before the first function or class.
**config_kwargs: Any config modifications.
-
isort.api.find_imports_in_stream(input_stream: TextIO, config: Config =
DEFAULT_CONFIG, file_path: Path | None =None, unique: bool | ImportKey =False, top_only: bool =False, _seen: set[str] | None =None, **config_kwargs: Any) Iterator[Import][source]¶ Finds and returns all imports within the provided code stream.
input_stream: The stream of code with imports that need to be sorted.
config: The config object to use when sorting imports.
file_path: The disk location where the code string was pulled from.
unique: If True, only the first instance of an import is returned.
top_only: If True, only return imports that occur before the first function or class.
_seen: An optional set of imports already seen. Generally meant only for internal use.
**config_kwargs: Any config modifications.
-
isort.api.place_module(name: str, config: Config =
DEFAULT_CONFIG) str¶ Returns the section placement for the given module name.
-
isort.api.place_module_with_reason(name: str, config: Config =
DEFAULT_CONFIG) tuple[str, str]¶ Returns the section placement for the given module name alongside the reasoning.
-
isort.api.sort_code_string(code: str, extension: str | None =
None, config: Config =DEFAULT_CONFIG, file_path: Path | None =None, disregard_skip: bool =False, show_diff: bool | TextIO =False, **config_kwargs: Any) str[source]¶ 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.
-
isort.api.sort_file(filename: str | Path, extension: str | None =
None, config: Config =DEFAULT_CONFIG, file_path: Path | None =None, disregard_skip: bool =True, ask_to_apply: bool =False, show_diff: bool | TextIO =False, write_to_stdout: bool =False, output: TextIO | None =None, **config_kwargs: Any) bool[source]¶ - Sorts and formats any groups of 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.
output: If a TextIO is provided, results will be written there rather than replacing the original file content.
**config_kwargs: Any config modifications.
-
isort.api.sort_stream(input_stream: TextIO, output_stream: TextIO, extension: str | None =
None, config: Config =DEFAULT_CONFIG, file_path: Path | None =None, disregard_skip: bool =False, show_diff: bool | TextIO =False, raise_on_skip: bool =True, **config_kwargs: Any) bool[source]¶ - 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.
isort.identify¶
Fast stream based import identification. Eventually this will likely replace parse.py
- class isort.identify.Import(line_number, indented, module, attribute, alias, cimport, file_path)[source]¶
Bases:
NamedTuple
-
isort.identify.imports(input_stream: TextIO, config: Config =
DEFAULT_CONFIG, file_path: Path | None =None, top_only: bool =False) Iterator[Import][source]¶ Parses a python file taking out and categorizing imports.
isort.main¶
Tool for sorting imports alphabetically, and automatically separated into sections.
- class isort.main.SortAttempt(incorrectly_sorted: bool, skipped: bool, supported_encoding: bool)[source]¶
Bases:
object
-
isort.main.identify_imports_main(argv: Sequence[str] | None =
None, stdin: TextIOWrapper | None =None) None[source]¶
-
isort.main.main(argv: Sequence[str] | None =
None, stdin: TextIOWrapper | None =None) None[source]¶
-
isort.main.sort_imports(file_name: str, config: Config, check: bool =
False, ask_to_apply: bool =False, write_to_stdout: bool =False, **kwargs: Any) SortAttempt | None[source]¶
isort.place¶
Contains all logic related to placing an import within a certain section.
-
isort.place.module(name: str, config: Config =
DEFAULT_CONFIG) str[source]¶ Returns the section placement for the given module name.
-
isort.place.module_with_reason(name: str, config: Config =
DEFAULT_CONFIG) tuple[str, str][source]¶ Returns the section placement for the given module name alongside the reasoning.
isort.wrap_modes¶
Defines all wrap modes that can be used when outputting formatted imports
- class isort.wrap_modes.WrapModes(*values)¶
Bases:
Enum-
BACKSLASH_GRID =
11¶
-
GRID =
0¶
-
HANGING_INDENT =
2¶
-
HANGING_INDENT_WITH_PARENTHESES =
10¶
-
NOQA =
7¶
-
VERTICAL =
1¶
-
VERTICAL_GRID =
4¶
-
VERTICAL_GRID_GROUPED =
5¶
-
VERTICAL_GRID_GROUPED_NO_COMMA =
6¶
-
VERTICAL_HANGING_INDENT =
3¶
-
VERTICAL_HANGING_INDENT_BRACKET =
8¶
-
VERTICAL_PREFIX_FROM_MODULE_IMPORT =
9¶
-
BACKSLASH_GRID =
- isort.wrap_modes.backslash_grid(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.grid(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.hanging_indent(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.hanging_indent_with_parentheses(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.noqa(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.vertical(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.vertical_grid(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.vertical_grid_grouped(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.vertical_grid_grouped_no_comma(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.vertical_hanging_indent(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.vertical_hanging_indent_bracket(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
- isort.wrap_modes.vertical_prefix_from_module_import(statement: str, imports: list[str], white_space: str, indent: str, line_length: int, comments: list[str], line_separator: str, comment_prefix: str, include_trailing_comma: bool, remove_comments: bool) str[source]¶
isort.settings¶
isort/settings.py.
Defines how the default settings for isort should be loaded
-
class isort.settings.Config(settings_file: str =
'', settings_path: str ='', config: _Config | None =None, **config_overrides: Any)[source]¶ Bases:
_Config- _parse_known_pattern(pattern: str) list[str][source]¶
Expand pattern if identified as a directory and return found sub packages
- class isort.settings._Config(py_version: str = '3', force_to_top: frozenset[str] = frozenset({}), skip: frozenset[str] = frozenset({'.bzr', '.direnv', '.eggs', '.git', '.hg', '.mypy_cache', '.nox', '.pants.d', '.pytype', '.svn', '.tox', '.venv', '__pypackages__', '_build', 'buck-out', 'build', 'dist', 'node_modules', 'venv'}), extend_skip: frozenset[str] = frozenset({}), skip_glob: frozenset[str] = frozenset({}), extend_skip_glob: frozenset[str] = frozenset({}), skip_gitignore: bool = False, line_length: int = 79, wrap_length: int = 0, line_ending: str = '', sections: tuple[str, ...] = ('FUTURE', 'STDLIB', 'THIRDPARTY', 'FIRSTPARTY', 'LOCALFOLDER'), no_sections: bool = False, known_future_library: frozenset[str] = frozenset({'__future__'}), known_third_party: frozenset[str] = frozenset({}), known_first_party: frozenset[str] = frozenset({}), known_local_folder: frozenset[str] = frozenset({}), known_standard_library: frozenset[str] = frozenset({}), extra_standard_library: frozenset[str] = frozenset({}), known_other: dict[str, frozenset[str]] = <factory>, multi_line_output: ~isort.wrap_modes.WrapModes = WrapModes.GRID, forced_separate: tuple[str, ...] = (), indent: str = ' ', comment_prefix: str = ' #', length_sort: bool = False, length_sort_straight: bool = False, length_sort_sections: frozenset[str] = frozenset({}), add_imports: frozenset[str] = frozenset({}), remove_imports: frozenset[str] = frozenset({}), append_only: bool = False, reverse_relative: bool = False, force_single_line: bool = False, single_line_exclusions: tuple[str, ...] = (), default_section: str = 'THIRDPARTY', import_headings: dict[str, str] = <factory>, import_footers: dict[str, str] = <factory>, balanced_wrapping: bool = False, use_parentheses: bool = False, order_by_type: bool = True, atomic: bool = False, lines_before_imports: int = -1, lines_after_imports: int = -1, lines_between_sections: int = 1, lines_between_types: int = 0, combine_as_imports: bool = False, combine_star: bool = False, include_trailing_comma: bool = False, from_first: bool = False, verbose: bool = False, quiet: bool = False, force_adds: bool = False, force_alphabetical_sort_within_sections: bool = False, force_alphabetical_sort: bool = False, force_grid_wrap: int = 0, force_sort_within_sections: bool = False, lexicographical: bool = False, group_by_package: bool = False, separate_packages: frozenset[str] = frozenset({}), ignore_whitespace: bool = False, no_lines_before: frozenset[str] = frozenset({}), no_inline_sort: bool = False, ignore_comments: bool = False, case_sensitive: bool = False, sources: tuple[dict[str, ~typing.Any], ...] = (), virtual_env: str = '', conda_env: str = '', ensure_newline_before_comments: bool = False, directory: str = '', profile: str = '', honor_noqa: bool = False, src_paths: tuple[~pathlib.Path, ...] = (), remove_redundant_aliases: bool = False, float_to_top: bool = False, filter_files: bool = False, formatter: str = '', formatting_function: ~collections.abc.Callable[[str, str, object], str] | None = None, color_output: bool = False, treat_comments_as_code: frozenset[str] = frozenset({}), treat_all_comments_as_code: bool = False, supported_extensions: frozenset[str] = frozenset({'pxd', 'py', 'pyi', 'pyx'}), blocked_extensions: frozenset[str] = frozenset({'pex'}), constants: frozenset[str] = frozenset({}), classes: frozenset[str] = frozenset({}), variables: frozenset[str] = frozenset({}), dedup_headings: bool = False, only_sections: bool = False, only_modified: bool = False, combine_straight_imports: bool = False, auto_identify_namespace_packages: bool = True, namespace_packages: frozenset[str] = frozenset({}), follow_links: bool = True, indented_import_headings: bool = True, honor_case_in_force_sorted_sections: bool = False, sort_relative_in_force_sorted_sections: bool = False, overwrite_in_place: bool = False, reverse_sort: bool = False, star_first: bool = False, git_ls_files: dict[~pathlib.Path, set[str]] = <factory>, format_error: str = '{error}: {message}', format_success: str = '{success}: {message}', sort_order: str = 'natural', sort_reexports: bool = False, split_on_trailing_comma: bool = False)[source]¶
Bases:
objectDefines the data schema and defaults used for isort configuration.
NOTE: known lists, such as known_standard_library, are intentionally not complete as they are dynamically determined later on.
- isort.settings._as_bool(value: str) bool[source]¶
Given a string value that represents True or False, returns the Boolean equivalent. Heavily inspired from distutils strtobool.
- isort.settings._get_str_to_type_converter(setting_name: str) Callable[[str], Any] | type[Any][source]¶
- isort.settings.entry_points(group: str) EntryPoints[source]¶
Call entry_point after lazy loading it.
TODO: The reason for lazy loading here are unknown.
- isort.settings.find_all_configs(path: str) Trie[source]¶
Looks for config files in the path provided and in all of its sub-directories. Parses and stores any config file encountered in a trie and returns the root of the trie
isort.utils¶
-
class isort.utils.Trie(config_file: str =
'', config_data: dict[str, Any] | None =None)[source]¶ Bases:
objectA prefix tree to store the paths of all config files and to search the nearest config associated with each file
- insert(config_file: str, config_data: dict[str, Any]) None[source]¶
-
class isort.utils.TrieNode(config_file: str =
'', config_data: dict[str, Any] | None =None)[source]¶ Bases:
object
- isort.utils.exists_case_sensitive(path: str) bool[source]¶
Returns if the given path exists and also matches the case on Windows.
When finding files that can be imported, it is important for the cases to match because while file os.path.exists(“module.py”) and os.path.exists(“MODULE.py”) both return True on Windows, Python can only import using the case of the real file.
isort.exceptions¶
All isort specific exception classes should be defined here
- exception isort.exceptions.AssignmentsFormatMismatch(code: str)[source]¶
Bases:
ISortErrorRaised when isort is told to sort assignments but the format of the assignment section doesn’t match isort’s expectation.
- exception isort.exceptions.ExistingSyntaxErrors(file_path: str)[source]¶
Bases:
ISortErrorRaised when isort is told to sort imports within code that has existing syntax errors
- exception isort.exceptions.FileSkipComment(file_path: str, **kwargs: str)[source]¶
Bases:
FileSkippedRaised when an entire file is skipped due to a isort skip file comment
- exception isort.exceptions.FileSkipSetting(file_path: str, **kwargs: str)[source]¶
Bases:
FileSkippedRaised when an entire file is skipped due to provided isort settings
- exception isort.exceptions.FileSkipped(message: str, file_path: str)[source]¶
Bases:
ISortErrorShould be raised when a file is skipped for any reason
- exception isort.exceptions.FormattingPluginDoesNotExist(formatter: str)[source]¶
Bases:
ISortErrorRaised when a formatting plugin is set by the user that doesn’t exist
- exception isort.exceptions.ISortError[source]¶
Bases:
ExceptionBase isort exception object from which all isort sourced exceptions should inherit
- exception isort.exceptions.IntroducedSyntaxErrors(file_path: str)[source]¶
Bases:
ISortErrorRaised when isort has introduced a syntax error in the process of sorting imports
- exception isort.exceptions.InvalidSettingsPath(settings_path: str)[source]¶
Bases:
ISortErrorRaised when a settings path is provided that is neither a valid file or directory
- exception isort.exceptions.LiteralParsingFailure(code: str, original_error: Exception | type[Exception])[source]¶
Bases:
ISortErrorRaised when one of isorts literal sorting comments is used but isort can’t parse the the given data structure.
- exception isort.exceptions.LiteralSortTypeMismatch(kind: type, expected_kind: type)[source]¶
Bases:
ISortErrorRaised when an isort literal sorting comment is used, with a type that doesn’t match the supplied data structure’s type.
- exception isort.exceptions.MissingSection(import_module: str, section: str)[source]¶
Bases:
ISortErrorRaised when isort encounters an import that matches a section that is not defined
- exception isort.exceptions.ProfileDoesNotExist(profile: str)[source]¶
Bases:
ISortErrorRaised when a profile is set by the user that doesn’t exist
- exception isort.exceptions.SortingFunctionDoesNotExist(sort_order: str, available_sort_orders: list[str])[source]¶
Bases:
ISortErrorRaised when the specified sorting function isn’t available
- exception isort.exceptions.UnsupportedEncoding(filename: str | Path)[source]¶
Bases:
ISortErrorRaised when isort encounters an encoding error while trying to read a file
- exception isort.exceptions.UnsupportedSettings(unsupported_settings: dict[str, dict[str, str]])[source]¶
Bases:
ISortErrorRaised when settings are passed into isort (either from config, CLI, or runtime) that it doesn’t support.