astor icon indicating copy to clipboard operation
astor copied to clipboard

Generate the code as if it was processed by `black`

Open KOLANICH opened this issue 5 years ago • 4 comments

I usually postprocess the generated code with black. It seems to be inefficient and adds a delay. Should the lib generate code, mostly (except of indentation) identical to the one processed by black?

KOLANICH avatar Jun 11 '20 21:06 KOLANICH

How about this?

from astor import to_source
from black import format_str, FileMode


def astor_and_blacken(ast, filename, mode='a', skip_black=False):
    src = to_source(ast)
    if not skip_black:
        src = format_str(src, mode=FileMode(
            target_versions=set(),
            line_length=119,
            is_pyi=False,
            string_normalization=False,
        ))
    with open(filename, mode) as f:
        f.write(src)

SamuelMarks avatar Jul 13 '20 11:07 SamuelMarks

I'd be happy to improve/provide API to make integration with tools such as black is easier, but I have no plans to add support for black by default.

Samuel's snippet looks pretty good to me. Perhaps to_source() could accept a post generation hook that looks similar to it.

berkerpeksag avatar Jul 13 '20 12:07 berkerpeksag

I have no plans to add support for black by default.

I didn't mean actually using black. I mean to generate code running on which black will say that it has nothing to do. At least it needs some double quotes + whitespaces in strategic places. It is easier than to reimplement half of black - black has to keep user's stuff, we don't because we are generating code from scratch.

KOLANICH avatar Jul 13 '20 15:07 KOLANICH

I wonder how far away is astor from producing such code. I've been using it in my structured editor prototype and the generated code can be pretty hard to read sometimes, specially within complex functions, primarily because of the lack of whitespace.

GustavoMF31 avatar Jul 14 '20 10:07 GustavoMF31