Black classes

Contents are subject to change.

BracketTracker

class black.BracketTracker(depth=0, bracket_match=NOTHING, delimiters=NOTHING, previous=None)

Keeps track of brackets on a line.

mark(leaf: blib2to3.pytree.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, it receives an opening_bracket field that it forms a pair with. This is a one-directional link to avoid reference cycles.

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.

any_open_brackets() → bool

Return True if there is an yet unmatched open bracket on the line.

max_delimiter_priority(exclude: Iterable[int] = ()) → int

Return the highest priority of a delimiter found on the line.

Values are consistent with what is_delimiter() returns.

EmptyLineTracker

class black.EmptyLineTracker(previous_line=None, previous_after=0, previous_defs=NOTHING)

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: black.Line) → Tuple[int, int]

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), as well as providing an extra empty line after flow control keywords to make them more prominent.

Line

class black.Line(depth=0, leaves=NOTHING, comments=NOTHING, bracket_tracker=NOTHING, inside_brackets=False, has_for=False, for_loop_variable=False)

Holds leaves and comments. Can be printed with str(line).

append(leaf: blib2to3.pytree.Leaf, preformatted: 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: blib2to3.pytree.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.

is_comment

Is this line a standalone comment?

is_decorator

Is this line a decorator?

is_import

Is this an import line?

is_class

Is this line a class definition?

is_def

Is this a function definition? (Also returns True for async defs.)

is_flow_control

Is this line a flow control statement?

Those are return, raise, break, and continue.

is_yield

Is this line a yield statement?

contains_standalone_comments

If so, needs to be split before emitting.

maybe_remove_trailing_comma(closing: blib2to3.pytree.Leaf) → bool

Remove trailing comma if there is one and it’s safe.

maybe_increment_for_loop_variable(leaf: blib2to3.pytree.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: blib2to3.pytree.Leaf) → bool

See maybe_increment_for_loop_variable above for explanation.

append_comment(comment: blib2to3.pytree.Leaf) → bool

Add an inline or standalone comment to the line.

comments_after(leaf: blib2to3.pytree.Leaf) → Iterator[blib2to3.pytree.Leaf]

Generate comments that should appear directly after leaf.

remove_trailing_comma() → None

Remove the trailing comma and moves the comments attached to it.

__str__() → str

Render the line.

__bool__() → bool

Return True if the line has leaves or comments.

LineGenerator

class black.LineGenerator(current_line=NOTHING)

Bases: black.Visitor

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, type: Type[black.Line] = <class 'black.Line'>) → Iterator[black.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(node: Union[blib2to3.pytree.Leaf, blib2to3.pytree.Node]) → Iterator[black.Line]

Main method to visit node and its children.

Yields Line objects.

visit_default(node: Union[blib2to3.pytree.Leaf, blib2to3.pytree.Node]) → Iterator[black.Line]

Default visit_*() implementation. Recurses to children of node.

visit_INDENT(node: blib2to3.pytree.Node) → Iterator[black.Line]

Increase indentation level, maybe yield a line.

visit_DEDENT(node: blib2to3.pytree.Node) → Iterator[black.Line]

Decrease indentation level, maybe yield a line.

visit_stmt(node: blib2to3.pytree.Node, keywords: Set[str]) → Iterator[black.Line]

Visit a statement.

This implementation is shared for if, while, for, try, except, def, with, and class.

The relevant Python language keywords for a given statement will be NAME leaves within it. This methods puts those on a separate line.

visit_simple_stmt(node: blib2to3.pytree.Node) → Iterator[black.Line]

Visit a statement without nested statements.

visit_async_stmt(node: blib2to3.pytree.Node) → Iterator[black.Line]

Visit async def, async for, async with.

visit_decorators(node: blib2to3.pytree.Node) → Iterator[black.Line]

Visit decorators.

visit_SEMI(leaf: blib2to3.pytree.Leaf) → Iterator[black.Line]

Remove a semicolon and put the other statement on a separate line.

visit_ENDMARKER(leaf: blib2to3.pytree.Leaf) → Iterator[black.Line]

End of file. Process outstanding comments and end with a newline.

visit_unformatted(node: Union[blib2to3.pytree.Leaf, blib2to3.pytree.Node]) → Iterator[black.Line]

Used when file contained a # fmt: off.

Report

class black.Report(check=False, change_count=0, same_count=0, failure_count=0)

Provides a reformatting counter. Can be rendered with str(report).

done(src: pathlib.Path, changed: bool) → None

Increment the counter for successful reformatting. Write out a message.

failed(src: pathlib.Path, message: str) → None

Increment the counter for failed reformatting. Write out a message.

return_code

Return the exit code that the app should use.

This considers the current state of changed files and failures: - if there were any failures, return 123; - if any files were changed and –check is being used, return 1; - otherwise return 0.

__str__() → str

Render a color report of the current state.

Use click.unstyle to remove colors.

UnformattedLines

class black.UnformattedLines(depth=0, leaves=NOTHING, comments=NOTHING, bracket_tracker=NOTHING, inside_brackets=False, has_for=False, for_loop_variable=False)

Bases: black.Line

Just like Line but stores lines which aren’t reformatted.

append(leaf: blib2to3.pytree.Leaf, preformatted: bool = True) → None

Just add a new leaf to the end of the lines.

The preformatted argument is ignored.

Keeps track of indentation depth, which is useful when the user says # fmt: on. Otherwise, doesn’t do anything with the leaf.

__str__() → str

Render unformatted lines from leaves which were added with append().

depth is not used for indentation in this case.

append_comment(comment: blib2to3.pytree.Leaf) → bool

Not implemented in this class. Raises NotImplementedError.

maybe_remove_trailing_comma(closing: blib2to3.pytree.Leaf) → bool

Does nothing and returns False.

maybe_increment_for_loop_variable(leaf: blib2to3.pytree.Leaf) → bool

Does nothing and returns False.

Visitor

class black.Visitor

Bases: typing.Generic

Basic lib2to3 visitor that yields things of type T on visit().

visit(node: Union[blib2to3.pytree.Leaf, blib2to3.pytree.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.

visit_default(node: Union[blib2to3.pytree.Leaf, blib2to3.pytree.Node]) → Iterator[T]

Default visit_*() implementation. Recurses to children of node.