當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。