Reformat a string and return new contents. `mode` determines formatting options, such as how many characters per line are allowed. Example: >>> import black >>> print(black.format_str("def f(arg:str='')->None:...", mode=black.Mode())) def f(arg: str = "") -> None: ...
(
src_contents: str, *, mode: Mode, lines: Collection[tuple[int, int]] = ()
)
| 1209 | |
| 1210 | |
| 1211 | def format_str( |
| 1212 | src_contents: str, *, mode: Mode, lines: Collection[tuple[int, int]] = () |
| 1213 | ) -> str: |
| 1214 | """Reformat a string and return new contents. |
| 1215 | |
| 1216 | `mode` determines formatting options, such as how many characters per line are |
| 1217 | allowed. Example: |
| 1218 | |
| 1219 | >>> import black |
| 1220 | >>> print(black.format_str("def f(arg:str='')->None:...", mode=black.Mode())) |
| 1221 | def f(arg: str = "") -> None: |
| 1222 | ... |
| 1223 | |
| 1224 | A more complex example: |
| 1225 | |
| 1226 | >>> print( |
| 1227 | ... black.format_str( |
| 1228 | ... "def f(arg:str='')->None: hey", |
| 1229 | ... mode=black.Mode( |
| 1230 | ... target_versions={black.TargetVersion.PY36}, |
| 1231 | ... line_length=10, |
| 1232 | ... string_normalization=False, |
| 1233 | ... is_pyi=False, |
| 1234 | ... ), |
| 1235 | ... ), |
| 1236 | ... ) |
| 1237 | def f( |
| 1238 | arg: str = '', |
| 1239 | ) -> None: |
| 1240 | hey |
| 1241 | |
| 1242 | """ |
| 1243 | if lines: |
| 1244 | lines = sanitized_lines(lines, src_contents) |
| 1245 | if not lines: |
| 1246 | return src_contents # Nothing to format |
| 1247 | dst_contents = _format_str_once(src_contents, mode=mode, lines=lines) |
| 1248 | # Forced second pass to work around optional trailing commas (becoming |
| 1249 | # forced trailing commas on pass 2) interacting differently with optional |
| 1250 | # parentheses. Admittedly ugly. |
| 1251 | if src_contents != dst_contents: |
| 1252 | if lines: |
| 1253 | lines = adjusted_lines(lines, src_contents, dst_contents) |
| 1254 | return _format_str_once(dst_contents, mode=mode, lines=lines) |
| 1255 | return dst_contents |
| 1256 | |
| 1257 | |
| 1258 | def _format_str_once( |
no test coverage detected