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.
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.
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)
It's not officially supported, but you can call black.format_file_contents as seen in the black.format_stdin_to_stdout function.
When simplified, it's only following few lines:
import black # version: 22.10.0
BLACK_MODE = black.Mode(target_versions={black.TargetVersion.PY311}, line_length=120)
code = ... # some python code to reformat
try:
code = black.format_file_contents(code, fast=False, mode=BLACK_MODE)
except black.NothingChanged:
pass
finally:
# Make sure there's a newline after the content
if code and code[-1] != "\n":
code += "\n"
print(code) # print result
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)