How to use the black.format_str function in black

To help you get started, we’ve selected a few black examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Nikoleta-v3 / blackbook / src / blackbook / main.py View on Github external
def format_notebook_content(path: pathlib.Path) -> dict:
    content = path.read_text()
    nb = json.loads(content)

    for cell in nb["cells"]:
        try:
            string = "".join(cell["source"])
            formatted_string = black.format_str(string, line_length=black.DEFAULT_LINE_LENGTH)
            cell["source"] = [s + "\n" for s in formatted_string.split("\n")][:-1]
        except black.InvalidInput:
            pass

    return nb
github MeeseeksBox / MeeseeksDev / meeseeksdev / meeseeksbox / commands.py View on Github external
import os

    print("== pwd", os.getcwd())
    print("== listdir", os.listdir())

    for p in glob.glob("**/*.py", recursive=True):
        print("=== scanning", p, p in whitelist)
        if p not in whitelist:
            # we don't touch files not in this PR.
            continue
        patch = whitelist[p]
        ranges = parsepatch(patch)
        print("patch is:\n", patch)
        p = Path(p)
        old = p.read_text()
        new = black.format_str(old, mode=black.FileMode())
        if new != old:
            nl = new.splitlines()
            ol = old.splitlines()
            s = SequenceMatcher(None, ol, nl)
            for t, a1, a2, b1, b2 in s.get_opcodes():
                if not in_ranges((a1, a2), ranges):
                    print(f"-- we won't be able to suggest a change on {p}:{a1}-{a2}")
                    continue
                if t == "replace":

                    c = "```suggestion\n"

                    for n in nl[b1:b2]:
                        c += n
                        c += "\n"
                    c += "```"
github nipy / nipype / tools / checkspecs.py View on Github external
continue
                        input_fields += "%s=%s,\n    " % (
                            key,
                            self._normalize_repr(value),
                        )
                    input_fields += "),\n    "
                cmd += ["    input_map = dict(%s)" % input_fields]
                cmd += ["    inputs = %s.input_spec()" % c]
                cmd += [
                    """
    for key, metadata in list(input_map.items()):
        for metakey, value in list(metadata.items()):
            assert getattr(inputs.traits()[key], metakey) == value"""
                ]

                fmt_cmd = black.format_str("\n".join(cmd), mode=black.FileMode())
                with open(testfile, "wt") as fp:
                    fp.writelines(fmt_cmd)
            else:
                print("%s has nonautotest" % c)

            for traitname, trait in sorted(
                classinst.input_spec().traits(transient=None).items()
            ):
                for key in sorted(trait.__dict__):
                    if key in in_built:
                        continue
                    parent_metadata = []
                    if "parent" in trait.__dict__:
                        parent_metadata = list(getattr(trait, "parent").__dict__.keys())
                    if (
                        key
github MolSSI / QCElemental / raw_data / dft_data / build_dft_info.py View on Github external
output = f'''
"""
This is a automatically generated file from Psi4's density functional metadata.
Psi4 Version: {psi4.__version__}

File Authors: QCElemental Authors
"""


'''

output += f"data_blob = {json.dumps(dft_info)}".replace("true", "True").replace("false", "False")

output = black.format_str(output, mode=black.FileMode())

fn = "dft_data_blob.py"
with open(fn, "w") as handle:
    handle.write(output)
github Nikoleta-v3 / blackbook / src / blackbook / __init__.py View on Github external
def format_notebook_content(path: pathlib.Path) -> Optional[dict]:
    content = path.read_text()

    try:  # Some ipynb files will not contain json

        nb = json.loads(content)
        modification_found = False

        try:  # Some ipynb files will have no cells

            for cell in nb["cells"]:

                try:  # Some ipynb files will not have valid source code
                    string = "".join(cell["source"])
                    formatted_string = black.format_str(
                        string, mode=black.FileMode()
                    ).strip()  # Remove trailing newlines
                    if formatted_string != string:
                        modification_found = True
                        cell["source"] = formatted_string.splitlines()
                        cell["source"][:-1] = [
                            line + "\n" for line in cell["source"][:-1]
                        ]

                except black.InvalidInput:
                    pass

            if modification_found:
                return nb

        except KeyError:
github jpadilla / black-playground / api / app.py View on Github external
def format_code(source, configuration):
    try:
        mode = black.FileMode(**configuration)
        formatted = black.format_str(source, mode=mode)
    except Exception as exc:
        formatted = f"{exc}"

    return formatted
github ryantam626 / jupyterlab_code_formatter / serverextension / jupyterlab_code_formatter / formatters.py View on Github external
def format_code(self, code: str, **options) -> str:
        import black

        has_semicolon = code.strip().endswith(";")

        code = re.sub(MAGIC_COMMAND_RE, "#%#", code)
        code = black.format_str(code, **self.handle_options(**options))[:-1]
        code = re.sub(COMMENTED_MAGIC_COMMAND_RE, "%", code)

        if has_semicolon:
            code += ";"

        return code
github WinVector / data_algebra / data_algebra / data_ops.py View on Github external
def to_python(self, *, indent=0, strict=True, pretty=False, black_mode=None):
        self.columns_used()  # for table consistency check/raise
        if pretty:
            strict = True
        python_str = self.to_python_implementation(
            indent=indent, strict=strict, print_sources=True
        )
        if pretty:
            if _have_black:
                try:
                    if black_mode is None:
                        black_mode = black.FileMode()
                    python_str = black.format_str(python_str, mode=black_mode)
                except Exception:
                    pass
        return python_str
github tomcatling / black-nb / black_nb.py View on Github external
def format_str(
    src_contents: str,
    line_length: int,
    *,
    mode: black.FileMode = black.FileMode.AUTO_DETECT,
) -> black.FileContent:
    trailing_semi_colon = src_contents.rstrip()[-1] == ";"
    src_contents = hide_magic(src_contents)
    dst_contents = black.format_str(
        src_contents, line_length=line_length, mode=mode
    )
    dst_contents = dst_contents.rstrip()
    if trailing_semi_colon:
        dst_contents = f"{dst_contents};"
    dst_contents = reveal_magic(dst_contents)
    return dst_contents
github tomcatling / black-nb / black_nb / cli.py View on Github external
def format_str(
    src_contents: str, *, mode: black.FileMode = black.FileMode(),
) -> black.FileContent:

    # Strip trailing semicolon because Black removes it, but it is an
    # important feature in notebooks.
    # Only a single trailing semicolon is supported. If the cell contains
    # multiple trailing semicolons black_nb will fail.
    trailing_semi_colon = src_contents.rstrip()[-1] == ";"

    src_contents = hide_magic(src_contents)
    dst_contents = black.format_str(src_contents, mode=mode)
    dst_contents = dst_contents.rstrip()

    # Replace the missing semi colon, except when Black didn't remove it
    # which happens if the last line is a comment
    if trailing_semi_colon and dst_contents.rstrip()[-1] != ";":
        dst_contents = f"{dst_contents};"

    dst_contents = reveal_magic(dst_contents)
    return dst_contents