Is it possible to call Black as an API?
Asked Answered
R

4

34

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.

Rang answered 26/8, 2019 at 6:41 Comment(2)
you may certainly need to give black a file. Because it parses the grammar based on the code and take indentation into consideration and stuff. You can see the codeEnenstein
there is blackd, but that's probably even worse than using a subprocess.Vineland
O
31

You could try using format_str:

from black import format_str, FileMode
res = format_str("some python code", mode=FileMode())
print(res)
Once answered 26/8, 2019 at 7:14 Comment(1)
@Rang not that I'm aware, but you can see that it is what is used if you supply the --code command line argument.Once
E
7

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

Evidentiary answered 26/8, 2019 at 7:15 Comment(2)
does not work for me make last line out = black.format_file_contents( "ex_black.py", fast = True , mode = mode )Ouabain
@Ouabain You have to pass the contents of the python module instead of the path of the python module. If you want to format using the path, use the format_file_in_place functionEvidentiary
A
3

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
Agler answered 19/4, 2023 at 9:2 Comment(0)
T
1

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)

Theoretics answered 18/1, 2023 at 21:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.