Black classes#
Contents are subject to change.
BracketTracker
#
- class black.brackets.BracketTracker(depth: int = 0, bracket_match: ~typing.Dict[~typing.Tuple[int, int], ~blib2to3.pytree.Leaf] = <factory>, delimiters: ~typing.Dict[int, int] = <factory>, previous: ~blib2to3.pytree.Leaf | None = None, _for_loop_depths: ~typing.List[int] = <factory>, _lambda_argument_depths: ~typing.List[int] = <factory>, invisible: ~typing.List[~blib2to3.pytree.Leaf] = <factory>)#
Keeps track of brackets on a line.
- mark(leaf: Leaf) None #
Mark leaf with bracket-related metadata. Keep track of delimiters.
All leaves receive an int bracket_depth field that stores how deep within brackets a given leaf is. 0 means there are no enclosing brackets that started on this line.
If a leaf is itself a closing bracket and there is a matching opening bracket earlier, it receives an opening_bracket field with which it forms a pair. This is a one-directional link to avoid reference cycles. Closing bracket without opening happens on lines continued from previous breaks, e.g. ) -> “ReturnType”: as part of a funcdef where we place the return type annotation on its own line of the previous closing RPAR.
If a leaf is a delimiter (a token on which Black can split the line if needed) and it’s on depth 0, its id() is stored in the tracker’s delimiters field.
- max_delimiter_priority(exclude: Iterable[int] = ()) int #
Return the highest priority of a delimiter found on the line.
Values are consistent with what is_split_*_delimiter() return. Raises ValueError on no delimiters.
- delimiter_count_with_priority(priority: int = 0) int #
Return the number of delimiters with the given priority.
If no priority is passed, defaults to max priority on the line.
- maybe_increment_for_loop_variable(leaf: Leaf) bool #
In a for loop, or comprehension, the variables are often unpacks.
To avoid splitting on the comma in this situation, increase the depth of tokens between for and in.
- maybe_decrement_after_for_loop_variable(leaf: Leaf) bool #
See maybe_increment_for_loop_variable above for explanation.
- maybe_increment_lambda_arguments(leaf: Leaf) bool #
In a lambda expression, there might be more than one argument.
To avoid splitting on the comma in this situation, increase the depth of tokens between lambda and :.
Line
#
- class black.lines.Line(mode: ~black.mode.Mode, depth: int = 0, leaves: ~typing.List[~blib2to3.pytree.Leaf] = <factory>, comments: ~typing.Dict[int, ~typing.List[~blib2to3.pytree.Leaf]] = <factory>, bracket_tracker: ~black.brackets.BracketTracker = <factory>, inside_brackets: bool = False, should_split_rhs: bool = False, magic_trailing_comma: ~blib2to3.pytree.Leaf | None = None)#
Holds leaves and comments. Can be printed with str(line).
- append(leaf: Leaf, preformatted: bool = False, track_bracket: bool = False) None #
Add a new leaf to the end of the line.
Unless preformatted is True, the leaf will receive a new consistent whitespace prefix and metadata applied by
BracketTracker
. Trailing commas are maybe removed, unpacked for loop variables are demoted from being delimiters.Inline comments are put aside.
- append_safe(leaf: Leaf, preformatted: bool = False) None #
Like
append()
but disallow invalid standalone comment structure.Raises ValueError when any leaf is appended after a standalone comment or when a standalone comment is not the first leaf on the line.
- property is_class_paren_empty: bool#
Is this a class with no base classes but using parentheses?
Those are unnecessary and should be removed.
- is_fmt_pass_converted(*, first_leaf_matches: Callable[[Leaf], bool] | None = None) bool #
Is this line converted from fmt off/skip code?
If first_leaf_matches is not None, it only returns True if the first leaf of converted code matches.
- contains_standalone_comments(depth_limit: int = 9223372036854775807) bool #
If so, needs to be split before emitting.
- has_magic_trailing_comma(closing: Leaf, ensure_removable: bool = False) bool #
Return True if we have a magic trailing comma, that is when: - there’s a trailing comma here - it’s not a one-tuple - it’s not a single-element subscript Additionally, if ensure_removable: - it’s not from square bracket indexing (specifically, single-element square bracket indexing)
- is_complex_subscript(leaf: Leaf) bool #
Return True iff leaf is part of a slice with non-trivial exprs.
LinesBlock
#
- class black.lines.LinesBlock(mode: ~black.mode.Mode, previous_block: ~black.lines.LinesBlock | None, original_line: ~black.lines.Line, before: int = 0, content_lines: ~typing.List[str] = <factory>, after: int = 0)#
Class that holds information about a block of formatted lines.
This is introduced so that the EmptyLineTracker can look behind the standalone comments and adjust their empty lines for class or def lines.
EmptyLineTracker
#
- class black.lines.EmptyLineTracker(mode: ~black.mode.Mode, previous_line: ~black.lines.Line | None = None, previous_block: ~black.lines.LinesBlock | None = None, previous_defs: ~typing.List[~black.lines.Line] = <factory>, semantic_leading_comment: ~black.lines.LinesBlock | None = None)#
Provides a stateful method that returns the number of potential extra empty lines needed before and after the currently processed line.
Note: this tracker works on lines that haven’t been split yet. It assumes the prefix of the first leaf consists of optional newlines. Those newlines are consumed by maybe_empty_lines() and included in the computation.
- maybe_empty_lines(current_line: Line) LinesBlock #
Return the number of extra empty lines before and after the current_line.
This is for separating def, async def and class with extra empty lines (two on module-level).
LineGenerator
#
- class black.linegen.LineGenerator(mode: Mode, features: Collection[Feature])#
-
Generates reformatted Line objects. Empty lines are not emitted.
Note: destroys the tree it’s visiting by mutating prefixes of its leaves in ways that will no longer stringify to valid Python code on the tree.
- line(indent: int = 0) Iterator[Line] #
Generate a line.
If the line is empty, only emit if it makes sense. If the line is too long, split it first and then generate.
If any lines were generated, set up a new current_line.
- visit_default(node: Leaf | Node) Iterator[Line] #
Default visit_*() implementation. Recurses to children of node.
- visit_stmt(node: Node, keywords: Set[str], parens: Set[str]) Iterator[Line] #
Visit a statement.
This implementation is shared for if, while, for, try, except, def, with, class, assert, and assignments.
The relevant Python language keywords for a given statement will be NAME leaves within it. This methods puts those on a separate line.
parens holds a set of string leaf values immediately after which invisible parens should be put.
- visit_SEMI(leaf: Leaf) Iterator[Line] #
Remove a semicolon and put the other statement on a separate line.
ProtoComment
#
- class black.comments.ProtoComment(type: int, value: str, newlines: int, consumed: int)#
Describes a piece of syntax that is a comment.
It’s not a
blib2to3.pytree.Leaf
so that:it can be cached (Leaf objects should not be reused more than once as they store their lineno, column, prefix, and parent information);
newlines and consumed fields are kept separate from the value. This simplifies handling of special marker comments like
# fmt: off/on
.
Report
#
- class black.report.Report(check: bool = False, diff: bool = False, quiet: bool = False, verbose: bool = False, change_count: int = 0, same_count: int = 0, failure_count: int = 0)#
Provides a reformatting counter. Can be rendered with str(report).
- done(src: Path, changed: Changed) None #
Increment the counter for successful reformatting. Write out a message.
- failed(src: Path, message: str) None #
Increment the counter for failed reformatting. Write out a message.
Visitor
#
- class black.nodes.Visitor(*args, **kwds)#
Bases:
Generic
[T
]Basic lib2to3 visitor that yields things of type T on visit().
- visit(node: Leaf | Node) Iterator[T] #
Main method to visit node and its children.
It tries to find a visit_*() method for the given node.type, like visit_simple_stmt for Node objects or visit_INDENT for Leaf objects. If no dedicated visit_*() method is found, chooses visit_default() instead.
Then yields objects of type T from the selected visitor.
Enums#
Changed
#
Mode
#
- class black.Mode(target_versions: Set[black.mode.TargetVersion] = <factory>, line_length: int = 88, string_normalization: bool = True, is_pyi: bool = False, is_ipynb: bool = False, skip_source_first_line: bool = False, magic_trailing_comma: bool = True, experimental_string_processing: bool = False, python_cell_magics: Set[str] = <factory>, preview: bool = False)#
Bases:
object