Is it possible to call Black as an API?

Question:

Say I want to use black as an API, and do something like:

import black

black.format("some python code")

Formatting code by calling the black binary with Popen is an alternative, but that’s not what I’m asking.

Asked By: laike9m

||

Answers:

You could try using format_str:

from black import format_str, FileMode
res = format_str("some python code", mode=FileMode())
print(res)

Use black.format_file_contents.

e.g.

import black

mode = black.FileMode()
fast = False
out = black.format_file_contents("some python code", fast, mode)

https://github.com/psf/black/blob/19.3b0/black.py#L642

Answered By: Oluwafemi Sule

Does Black have an API?

Not yet. Black is fundamentally a command line tool. Many integrations are provided, but a Python interface is not one of them. A simple API is being planned though.

For now, you should call black using subprocess. The other answers which import black are unsupported and likely to break without warning.

Watch issue Black’s public API #779 for possible further developments.

(source: the same question in black’s FAQ page)

Answered By: wim
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.