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.
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)
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)
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)
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)