本文整理汇总了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
示例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),
),
)
示例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
示例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
示例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['-']
示例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)
示例7: _format_code
# 需要导入模块: import black [as 别名]
# 或者: from black import format_str [as 别名]
def _format_code(code):
return format_str(src_contents=code, mode=FileMode())
示例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)
示例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)
示例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())
示例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
示例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))
示例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