Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call Black as an API?

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.

like image 480
laike9m Avatar asked Aug 26 '19 06:08

laike9m


2 Answers

You could try using format_str:

from black import format_str, FileMode
res = format_str("some python code", mode=FileMode())
print(res)
like image 115
Halvor Holsten Strand Avatar answered Oct 23 '22 23:10

Halvor Holsten Strand


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

like image 26
Oluwafemi Sule Avatar answered Oct 24 '22 01:10

Oluwafemi Sule