Black functions¶
Contents are subject to change.
Assertions and checks¶
-
black.
assert_equivalent
(src: str, dst: str) → None¶ Raise AssertionError if src and dst aren’t equivalent.
-
black.
assert_stable
(src: str, dst: str, line_length: int) → None¶ Raise AssertionError if dst reformats differently the second time.
-
black.
is_delimiter
(leaf: blib2to3.pytree.Leaf) → int¶ Return the priority of the leaf delimiter. Return 0 if not delimiter.
Higher numbers are higher priority.
-
black.
is_import
(leaf: blib2to3.pytree.Leaf) → bool¶ Return True if the given leaf starts an import statement.
-
black.
is_python36
(node: blib2to3.pytree.Node) → bool¶ Return True if the current file is using Python 3.6+ features.
Currently looking for: - f-strings; and - trailing commas after * or ** in function signatures.
Formatting¶
-
black.
format_file_contents
(src_contents: str, line_length: int, fast: bool) → str¶ Reformat contents 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. line_length is passed toformat_str()
.
-
black.
format_file_in_place
(src: pathlib.Path, line_length: int, fast: bool, write_back: bool = False) → bool¶ Format file under src path. Return True if changed.
If write_back is True, write reformatted code back to stdout. line_length and fast options are passed to
format_file_contents()
.
-
black.
format_stdin_to_stdout
(line_length: int, fast: bool, write_back: bool = False) → bool¶ Format file on stdin. Return True if changed.
If write_back is True, write reformatted code back to stdout. line_length and fast arguments are passed to
format_file_contents()
.
-
black.
format_str
(src_contents: str, line_length: int) → str¶ Reformat a string and return new contents.
line_length determines how many characters per line are allowed.
-
black.
schedule_formatting
(sources: List[pathlib.Path], line_length: int, write_back: bool, fast: bool, loop: asyncio.base_events.BaseEventLoop, executor: concurrent.futures._base.Executor) → int¶ Run formatting of sources in parallel using the provided executor.
(Use ProcessPoolExecutors for actual parallelism.)
line_length, write_back, and fast options are passed to
format_file_in_place()
.
File operations¶
-
black.
dump_to_file
(*output) → str¶ Dump output to a temporary file. Return path to the file.
-
black.
gen_python_files_in_dir
(path: pathlib.Path) → Iterator[pathlib.Path]¶ Generate all files under path which aren’t under BLACKLISTED_DIRECTORIES and have one of the PYTHON_EXTENSIONS.
Parsing¶
-
black.
lib2to3_parse
(src_txt: str) → blib2to3.pytree.Node¶ Given a string with source, return the lib2to3 Node.
-
black.
lib2to3_unparse
(node: blib2to3.pytree.Node) → str¶ Given a lib2to3 node, return its string representation.
Split functions¶
-
black.
delimiter_split
(line: black.Line, py36: bool = False) → Iterator[black.Line]¶ Split according to delimiters of the highest priority.
If py36 is True, the split will add trailing commas also in function signatures that contain * and **.
-
black.
left_hand_split
(line: black.Line, py36: bool = False) → Iterator[black.Line]¶ Split line into many lines, starting with the first matching bracket pair.
Note: this usually looks weird, only use this for function definitions. Prefer RHS otherwise.
-
black.
right_hand_split
(line: black.Line, py36: bool = False) → Iterator[black.Line]¶ Split line into many lines, starting with the last matching bracket pair.
-
black.
split_line
(line: black.Line, line_length: int, inner: bool = False, py36: bool = False) → Iterator[black.Line]¶ Split a line into potentially many lines.
They should fit in the allotted line_length but might not be able to. inner signifies that there were a pair of brackets somewhere around the current line, possibly transitively. This means we can fallback to splitting by delimiters if the LHS/RHS don’t yield any results.
If py36 is True, splitting may generate syntax that is only compatible with Python 3.6 and later.
-
black.
bracket_split_succeeded_or_raise
(head: black.Line, body: black.Line, tail: black.Line) → None¶ Raise
CannotSplit
if the last left- or right-hand split failed.Do nothing otherwise.
A left- or right-hand split is based on a pair of brackets. Content before (and including) the opening bracket is left on one line, content inside the brackets is put on a separate line, and finally content starting with and following the closing bracket is put on a separate line.
Those are called head, body, and tail, respectively. If the split produced the same line (all content in head) or ended up with an empty body and the tail is just the closing bracket, then it’s considered failed.
Utilities¶
-
black.DebugVisitor.
show
(code: str) → None¶ Pretty-print the lib2to3 AST of a given string of code.
-
black.
diff
(a: str, b: str, a_name: str, b_name: str) → str¶ Return a unified diff string between strings a and b.
-
black.
generate_comments
(leaf: blib2to3.pytree.Leaf) → Iterator[blib2to3.pytree.Leaf]¶ Clean the prefix of the leaf and generate comments from it, if any.
Comments in lib2to3 are shoved into the whitespace prefix. This happens in pgen2/driver.py:Driver.parse_tokens(). This was a brilliant implementation move because it does away with modifying the grammar to include all the possible places in which comments can be placed.
The sad consequence for us though is that comments don’t “belong” anywhere. This is why this function generates simple parentless Leaf objects for comments. We simply don’t know what the correct parent should be.
No matter though, we can live without this. We really only need to differentiate between inline and standalone comments. The latter don’t share the line with any code.
Inline comments are emitted as regular token.COMMENT leaves. Standalone are emitted with a fake STANDALONE_COMMENT token identifier.
-
black.
make_comment
(content: str) → str¶ Return a consistently formatted comment from the given content string.
All comments (except for “##”, “#!”, “#:”) should have a single space between the hash sign and the content.
If content didn’t start with a hash sign, one is provided.
-
black.
normalize_prefix
(leaf: blib2to3.pytree.Leaf, *, inside_brackets: bool) → None¶ Leave existing extra newlines if not inside_brackets. Remove everything else.
Note: don’t use backslashes for formatting or you’ll lose your voting rights.
-
black.
preceding_leaf
(node: Union[blib2to3.pytree.Leaf, blib2to3.pytree.Node, NoneType]) → Union[blib2to3.pytree.Leaf, NoneType]¶ Return the first leaf that precedes node, if any.
-
black.
whitespace
(leaf: blib2to3.pytree.Leaf) → str¶ Return whitespace prefix if needed for the given leaf.