Black functions¶
Contents are subject to change.
Assertions and checks¶
Formatting¶
-
black.
format_file_contents
(src_contents: str, *, fast: bool, mode: black.mode.Mode) → str¶ Reformat contents of a file and return new contents.
If fast is False, additionally confirm that the reformatted code is valid by calling
assert_equivalent()
andassert_stable()
on it. mode is passed toformat_str()
.
-
black.
format_file_in_place
(src: pathlib.Path, fast: bool, mode: black.mode.Mode, write_back: black.WriteBack = <WriteBack.NO: 0>, lock: Optional[Any] = None) → bool¶ Format file under src path. Return True if changed.
If write_back is DIFF, write a diff to stdout. If it is YES, write reformatted code to the file. mode and fast options are passed to
format_file_contents()
.
-
black.
format_stdin_to_stdout
(fast: bool, *, write_back: black.WriteBack = <WriteBack.NO: 0>, mode: black.mode.Mode) → bool¶ Format file on stdin. Return True if changed.
If write_back is YES, write reformatted code back to stdout. If it is DIFF, write a diff to stdout. The mode argument is passed to
format_file_contents()
.
-
black.
format_str
(src_contents: str, *, mode: black.mode.Mode) → str¶ Reformat a string and return new contents.
mode determines formatting options, such as how many characters per line are allowed. Example:
>>> import black >>> print(black.format_str("def f(arg:str='')->None:...", mode=black.Mode())) def f(arg: str = "") -> None: ...
A more complex example:
>>> print( ... black.format_str( ... "def f(arg:str='')->None: hey", ... mode=black.Mode( ... target_versions={black.TargetVersion.PY36}, ... line_length=10, ... string_normalization=False, ... is_pyi=False, ... ), ... ), ... ) def f( arg: str = '', ) -> None: hey
-
black.
reformat_one
(src: pathlib.Path, fast: bool, write_back: black.WriteBack, mode: black.mode.Mode, report: black.report.Report) → None¶ Reformat a single file under src without spawning child processes.
fast, write_back, and mode options are passed to
format_file_in_place()
orformat_stdin_to_stdout()
.
-
async
black.
schedule_formatting
(sources: Set[pathlib.Path], fast: bool, write_back: black.WriteBack, mode: black.mode.Mode, report: black.report.Report, loop: asyncio.events.AbstractEventLoop, executor: concurrent.futures._base.Executor) → None¶ Run formatting of sources in parallel using the provided executor.
(Use ProcessPoolExecutors for actual parallelism.)
write_back, fast, and mode options are passed to
format_file_in_place()
.
File operations¶
-
black.
dump_to_file
(*output: str, ensure_final_newline: bool = True) → str¶ Dump output to a temporary file. Return path to the file.
-
black.
find_project_root
(srcs: Sequence[str]) → pathlib.Path¶ Return a directory containing .git, .hg, or pyproject.toml.
That directory will be a common parent of all files and directories passed in srcs.
If no directory in the tree contains a marker that would specify it’s the project root, the root of the file system is returned.
-
black.
gen_python_files
(paths: Iterable[pathlib.Path], root: pathlib.Path, include: Pattern[str], exclude: Pattern[str], extend_exclude: Optional[Pattern[str]], force_exclude: Optional[Pattern[str]], report: black.report.Report, gitignore: Optional[pathspec.pathspec.PathSpec]) → Iterator[pathlib.Path]¶ Generate all files under path whose paths are not excluded by the exclude_regex, extend_exclude, or force_exclude regexes, but are included by the include regex.
Symbolic links pointing outside of the root directory are ignored.
report is where output about exclusions goes.
Parsing¶
Split functions¶
-
black.
transform_line
(line: black.lines.Line, mode: black.mode.Mode, features: Collection[black.mode.Feature] = ()) → Iterator[black.lines.Line]¶ Transform a line, potentially splitting it into many lines.
They should fit in the allotted line_length but might not be able to.
features are syntactical features that may be used in the output.
Caching¶
-
black.
filter_cached
(cache: Dict[str, Tuple[float, int]], sources: Iterable[pathlib.Path]) → Tuple[Set[pathlib.Path], Set[pathlib.Path]]¶ Split an iterable of paths in sources into two sets.
The first contains paths of files that modified on disk or are not in the cache. The other contains paths to non-modified files.
-
black.
get_cache_info
(path: pathlib.Path) → Tuple[float, int]¶ Return the information used to check if a file is already formatted or not.
Utilities¶
-
black.
cancel
(tasks: Iterable[asyncio.Task[Any]]) → None¶ asyncio signal handler that cancels all tasks and reports to stderr.
-
black.
diff
(a: str, b: str, a_name: str, b_name: str) → str¶ Return a unified diff string between strings a and b.
-
black.
get_future_imports
(node: blib2to3.pytree.Node) → Set[str]¶ Return a set of __future__ imports in the file.
-
black.
normalize_fmt_off
(node: blib2to3.pytree.Node) → None¶ Convert content between # fmt: off/# fmt: on into standalone comments.
-
black.
patch_click
() → None¶ Make Click not crash.
On certain misconfigured environments, Python 3 selects the ASCII encoding as the default which restricts paths that it can access during the lifetime of the application. Click refuses to work in this scenario by raising a RuntimeError.
In case of Black the likelihood that non-ASCII characters are going to be used in file paths is minimal since it’s Python source code. Moreover, this crash was spurious on Python 3.7 thanks to PEP 538 and PEP 540.