formate.utils

Utility functions.

Functions:

import_entry_points(hooks)

Given a list of hooks, import the corresponding entry point and return a mapping of entry point names to EntryPoint objects.

normalize(name)

Normalize the given name into lowercase, with underscores replaced by hyphens.

syntaxerror_for_file(filename)

Context manager to catch SyntaxError and set its filename to filename if the current filename is <unknown>.

Classes:

Rewriter(source)

ABC for rewriting Python source files from an AST and a token stream.

SyntaxTracebackHandler([exception])

Subclass of consolekit.tracebacks.TracebackHandler to additionally handle SyntaxError.

import_entry_points(hooks)[source]

Given a list of hooks, import the corresponding entry point and return a mapping of entry point names to EntryPoint objects.

Parameters

hooks (List[Hook])

Raises

HookNotFoundError if no entry point can be found for a hook.

Return type

Dict[str, EntryPoint]

normalize(name)[source]

Normalize the given name into lowercase, with underscores replaced by hyphens.

Parameters

name (str) – The hook name.

Return type

str

syntaxerror_for_file(filename)[source]

Context manager to catch SyntaxError and set its filename to filename if the current filename is <unknown>.

This is useful for syntax errors raised when parsing source into an AST.

Parameters

filename (Union[str, Path, PathLike])

Return type

Iterator

class Rewriter(source)[source]

Bases: NodeVisitor

ABC for rewriting Python source files from an AST and a token stream.

Attributes:

source

The original source.

tokens

The tokenized source.

replacements

The parts of code to replace.

Methods:

rewrite()

Rewrite the source and return the new source.

record_replacement(text_range, new_source)

Record a region of text to be replaced.

source

Type:    str

The original source.

tokens

Type:    ASTTokens

The tokenized source.

replacements

Type:    List[Tuple[Tuple[int, int], str]]

The parts of code to replace.

Each element comprises a tuple of (start char, end char) in source, and the new text to insert between these positions.

rewrite()[source]

Rewrite the source and return the new source.

Return type

str

Returns

The reformatted source.

record_replacement(text_range, new_source)[source]

Record a region of text to be replaced.

Parameters
  • text_range (Tuple[int, int]) – The region of text to be replaced.

  • new_source (str) – The new text for that region.

class SyntaxTracebackHandler(exception=Abort())[source]

Bases: TracebackHandler

Subclass of consolekit.tracebacks.TracebackHandler to additionally handle SyntaxError.