当前位置: 首页>>代码示例>>Python>>正文


Python black.format_str方法代码示例

本文整理汇总了Python中black.format_str方法的典型用法代码示例。如果您正苦于以下问题:Python black.format_str方法的具体用法?Python black.format_str怎么用?Python black.format_str使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在black的用法示例。


在下文中一共展示了black.format_str方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: format_signature

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def format_signature(
    signature_start: str, signature_end: str, max_line_length: int = 110
):
    """pretty formatting to avoid long signatures on one single line"""

    # first, we make it look like a real function declaration.
    fake_signature_start = 'x' * len(signature_start)
    fake_signature = fake_signature_start + signature_end
    fake_python_code = f'def {fake_signature}:\n    pass\n'

    # we format with black
    mode = black.FileMode(line_length=max_line_length)
    formatted_fake_python_code = black.format_str(fake_python_code, mode=mode)

    # we make the final, multiline signature
    new_signature_end = extract_signature_end(formatted_fake_python_code)
    return signature_start + new_signature_end 
开发者ID:keras-team,项目名称:keras-autodoc,代码行数:19,代码来源:get_signatures.py

示例2: apply_black

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def apply_black(code: str, python_version: PythonVersion) -> str:

    root = black.find_project_root((Path().resolve(),))
    path = root / "pyproject.toml"
    if path.is_file():
        value = str(path)
        pyproject_toml = toml.load(value)
        config = pyproject_toml.get("tool", {}).get("black", {})
    else:
        config = {}

    return black.format_str(
        code,
        mode=black.FileMode(
            target_versions={BLACK_PYTHON_VERSION[python_version]},
            line_length=config.get("line-length", black.DEFAULT_LINE_LENGTH),
            string_normalization=not config.get("skip-string-normalization", True),
        ),
    ) 
开发者ID:koxudaxi,项目名称:datamodel-code-generator,代码行数:21,代码来源:format.py

示例3: format_file

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def format_file(
        filename: str, black_mode: black.FileMode, skip_errors: bool,
) -> int:
    with open(filename, encoding='UTF-8') as f:
        contents = f.read()
    new_contents, errors = format_str(contents, black_mode)
    for error in errors:
        lineno = contents[:error.offset].count('\n') + 1
        print(f'{filename}:{lineno}: code block parse error {error.exc}')
    if errors and not skip_errors:
        return 1
    if contents != new_contents:
        print(f'{filename}: Rewriting...')
        with open(filename, 'w', encoding='UTF-8') as f:
            f.write(new_contents)
        return 1
    else:
        return 0 
开发者ID:asottile,项目名称:blacken-docs,代码行数:20,代码来源:blacken_docs.py

示例4: format_code

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def format_code(self, code: str, notebook: bool, **options) -> str:
        import black

        code = black.format_str(code, **self.handle_options(**options))
        return code 
开发者ID:ryantam626,项目名称:jupyterlab_code_formatter,代码行数:7,代码来源:formatters.py

示例5: black_diff

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def black_diff(src: Path, differ=Differ()) -> Tuple[int, int]:
    src_contents = src.read_text()
    dst_contents = black.format_str(src_contents, mode=mode)
    if src_contents == dst_contents:
        return 0, 0

    counts = Counter(
        line[0]
        for line in differ.compare(src_contents.splitlines(), dst_contents.splitlines())
    )
    return counts['+'], counts['-'] 
开发者ID:theislab,项目名称:scanpy,代码行数:13,代码来源:blackdiff.py

示例6: _format_script

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def _format_script(script):
    try:
        import black
        formatter = partial(
            black.format_str, mode=black.FileMode(line_length=80)
        )
    except ImportError:
        # use autopep8 for python3.5
        import autopep8
        formatter = partial(
            autopep8.fix_code, options={"aggressive": 1}
        )

    return formatter(script) 
开发者ID:pandera-dev,项目名称:pandera,代码行数:16,代码来源:io.py

示例7: _format_code

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def _format_code(code):
        return format_str(src_contents=code, mode=FileMode()) 
开发者ID:dnanhkhoa,项目名称:nb_black,代码行数:4,代码来源:lab_black.py

示例8: black

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def black(self, line, cell):
        """Magic command to format the IPython cell."""
        args = magic_arguments.parse_argstring(self.black, line)
        line_length = args.line_length
        if cell:
            try:
                from black import FileMode
                mode = FileMode(line_length=line_length)
                formatted = format_str(src_contents=cell, mode=mode)
            except TypeError:
                formatted = format_str(src_contents=cell, line_length=line_length)
            if formatted and formatted[-1] == "\n":
                    formatted = formatted[:-1]
            self.shell.set_next_input(formatted, replace=True) 
开发者ID:csurfer,项目名称:blackcellmagic,代码行数:16,代码来源:blackcellmagic.py

示例9: tidy_code

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def tidy_code(self):
        """
        Prettify code with Black.
        """
        tab = self._view.current_tab
        if not tab or sys.version_info[:2] < (3, 6):
            return
        # Only works on Python, so abort.
        if tab.path and not tab.path.endswith(".py"):
            return
        from black import format_str, FileMode, PY36_VERSIONS

        try:
            source_code = tab.text()
            logger.info("Tidy code.")
            logger.info(source_code)
            filemode = FileMode(target_versions=PY36_VERSIONS, line_length=88)
            tidy_code = format_str(source_code, mode=filemode)
            # The following bypasses tab.setText which resets the undo history.
            # Doing it this way means the user can use CTRL-Z to undo the
            # reformatting from black.
            tab.SendScintilla(tab.SCI_SETTEXT, tidy_code.encode("utf-8"))
            self.show_status_message(
                _("Successfully cleaned the code. " "Use CTRL-Z to undo.")
            )
        except Exception as ex:
            # The user's code is problematic. Recover with a modal dialog
            # containing a helpful message.
            logger.error(ex)
            message = _("Your code contains problems.")
            information = _(
                "These must be fixed before tidying will work. "
                "Please use the 'Check' button to highlight "
                "these problems."
            )
            self._view.show_message(message, information) 
开发者ID:mu-editor,项目名称:mu,代码行数:38,代码来源:logic.py

示例10: formatPython

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def formatPython(text):
    try:
        import black
    except ImportError:
        raise RuntimeError(u"install black formatter to format: pip install black")

    return black.format_str(text, mode=black.FileMode()) 
开发者ID:google,项目名称:ci_edit,代码行数:9,代码来源:formatter.py

示例11: _compute_pwd_changes

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def _compute_pwd_changes(whitelist):
    import black
    from difflib import SequenceMatcher
    from pathlib import Path
    import glob

    post_changes = []
    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
        p = Path(p)
        old = p.read_text()
        new = black.format_str(old, mode=black.FileMode())
        if new != old:
            print("will differ")
            nl = new.splitlines()
            ol = old.splitlines()
            s = SequenceMatcher(None, ol, nl)
            for t, a1, a2, b1, b2 in s.get_opcodes():
                if t == "replace":

                    c = "```suggestion\n"

                    for n in nl[b1:b2]:
                        c += n
                        c += "\n"
                    c += "```"
                    ch = (p.as_posix(), a1, a2, c)
                    post_changes.append(ch)
    return post_changes 
开发者ID:MeeseeksBox,项目名称:MeeseeksDev,代码行数:39,代码来源:commands.py

示例12: _format_with_black

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def _format_with_black(self, content):
        return format_str(src_contents=content, mode=FileMode(line_length=120)) 
开发者ID:cognitedata,项目名称:cognite-sdk-python,代码行数:4,代码来源:generator.py

示例13: format_str

# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def format_str(
        src: str, black_mode: black.FileMode,
) -> Tuple[str, Sequence[CodeBlockError]]:
    errors: List[CodeBlockError] = []

    @contextlib.contextmanager
    def _collect_error(match: Match[str]) -> Generator[None, None, None]:
        try:
            yield
        except Exception as e:
            errors.append(CodeBlockError(match.start(), e))

    def _md_match(match: Match[str]) -> str:
        code = textwrap.dedent(match['code'])
        with _collect_error(match):
            code = black.format_str(code, mode=black_mode)
        code = textwrap.indent(code, match['indent'])
        return f'{match["before"]}{code}{match["after"]}'

    def _rst_match(match: Match[str]) -> str:
        min_indent = min(INDENT_RE.findall(match['code']))
        trailing_ws_match = TRAILING_NL_RE.search(match['code'])
        assert trailing_ws_match
        trailing_ws = trailing_ws_match.group()
        code = textwrap.dedent(match['code'])
        with _collect_error(match):
            code = black.format_str(code, mode=black_mode)
        code = textwrap.indent(code, min_indent)
        return f'{match["before"]}{code.rstrip()}{trailing_ws}'

    def _latex_match(match: Match[str]) -> str:
        code = textwrap.dedent(match['code'])
        with _collect_error(match):
            code = black.format_str(code, mode=black_mode)
        code = textwrap.indent(code, match['indent'])
        return f'{match["before"]}{code}{match["after"]}'

    src = MD_RE.sub(_md_match, src)
    src = RST_RE.sub(_rst_match, src)
    src = LATEX_RE.sub(_latex_match, src)
    src = PYTHONTEX_RE.sub(_latex_match, src)
    return src, errors 
开发者ID:asottile,项目名称:blacken-docs,代码行数:44,代码来源:blacken_docs.py


注:本文中的black.format_str方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。