With previous versions, it was possible to just use black.format_str(string) or black.format_str(string, line_length=82).
Now one needs to do:
black.format_str(string, mode=black.FileMode(line_length=82))
It's not a big deal in a module, but format_str was also useful in notebooks to display examples of Python code programmatically generated (for example by astunparse.unparse(tree)).
Therefore, it could be nice to support also black.format_str(string) and black.format_str(string, line_length=82).
The line_length argument is useful when one wants to get code adapted for a presentation (made with Jupyter for example).
In general, maybe we should take a moment to consider the APIs we're "setting in stone" for the first stable release in April.
Dropping in here - I'd like this, but also for formatting an AST for producing nicely formatted generated code (no parse step).
Also having parse_ast as part of the public API would be really helpful since it has improvements/best practices over Python's built in.
Any progress? It would be useful for me as well
For what it's worth, I've stumbled on this issue a number of times trying to find a way to programmatically call black without the use of a shell (i.e., in a CI pipeline). I've found that it's easy enough to do this using result = black.main([".", "--check"], standalone_mode=False) where result is what would have been the black script's exit code.
As for formatting a single string programmatically like this, I don't know how that could be done yet short of creating the file and sending it to black via this call. :thinking:
As somebody who uses black in a code-generation pipeline, being able to hand black a string (instead of a path to a file) is hugely convenient. gofmt has a similar stable API for formatting go code programatically.
A standard, documented API would be wonderful. One of my use cases is a unit test to check that all code is formatted with black. I would much rather do this by calling the API than by using subprocess. (Especially since I just ran into an issue where the installed black was available in the library, but the executable was somehow not on the PATH. Yes that was my problem, but I could have avoided it by not bothering with the executable.)
Most helpful comment
As somebody who uses black in a code-generation pipeline, being able to hand black a string (instead of a path to a file) is hugely convenient.
gofmthas a similar stable API for formatting go code programatically.