Black functions

Contents are subject to change.

Assertions and checks

black.assert_equivalent(src: str, dst: str, *, pass_num: int = 1)None

Raise AssertionError if src and dst aren’t equivalent.

black.assert_stable(src: str, dst: str, mode: black.mode.Mode)None

Raise AssertionError if dst reformats differently the second time.

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() and assert_stable() on it. mode is passed to format_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() or format_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.

black.read_pyproject_toml(ctx: click.core.Context, param: click.core.Parameter, value: Optional[str])Optional[str]

Inject Black configuration from “pyproject.toml” into defaults in ctx.

Returns the path to a successfully found and read configuration file, None otherwise.

Parsing

black.decode_bytes(src: bytes)Tuple[str, str, str]

Return a tuple of (decoded_contents, encoding, newline).

newline is either CRLF or LF but decoded_contents is decoded with universal newlines (i.e. only contains LF).

black.lib2to3_parse(src_txt: str, target_versions: Iterable[black.mode.TargetVersion] = ())blib2to3.pytree.Node

Given a string with source, return the lib2to3 Node.

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.

black.read_cache(mode: black.mode.Mode)Dict[str, Tuple[float, int]]

Read the cache if it exists and is well formed.

If it is not well formed, the call to write_cache later should resolve the issue.

black.write_cache(cache: Dict[str, Tuple[float, int]], sources: Iterable[pathlib.Path], mode: black.mode.Mode)None

Update the cache file.

Utilities

black.DebugVisitor.show(code: str)None

Pretty-print the lib2to3 AST of a given string of code.

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.

black.re_compile_maybe_verbose(regex: str)Pattern[str]

Compile a regular expression string in regex.

If it contains newlines, use verbose mode.

black.shutdown(loop: asyncio.events.AbstractEventLoop)None

Cancel all pending tasks on loop, wait for them, and close the loop.