Helper for writing string literals, minimizing escapes. Returns the tuple (string literal to write, possible quote types).
(
self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False
)
| 530 | self.traverse(node.body) |
| 531 | |
| 532 | def _str_literal_helper( |
| 533 | self, string, *, quote_types=_ALL_QUOTES, escape_special_whitespace=False |
| 534 | ): |
| 535 | """Helper for writing string literals, minimizing escapes. |
| 536 | Returns the tuple (string literal to write, possible quote types). |
| 537 | """ |
| 538 | def escape_char(c): |
| 539 | # \n and \t are non-printable, but we only escape them if |
| 540 | # escape_special_whitespace is True |
| 541 | if not escape_special_whitespace and c in "\n\t": |
| 542 | return c |
| 543 | # Always escape backslashes and other non-printable characters |
| 544 | if c == "\\" or not c.isprintable(): |
| 545 | return c.encode("unicode_escape").decode("ascii") |
| 546 | return c |
| 547 | |
| 548 | escaped_string = "".join(map(escape_char, string)) |
| 549 | possible_quotes = quote_types |
| 550 | if "\n" in escaped_string: |
| 551 | possible_quotes = [q for q in possible_quotes if q in _MULTI_QUOTES] |
| 552 | possible_quotes = [q for q in possible_quotes if q not in escaped_string] |
| 553 | if not possible_quotes: |
| 554 | # If there aren't any possible_quotes, fallback to using repr |
| 555 | # on the original string. Try to use a quote from quote_types, |
| 556 | # e.g., so that we use triple quotes for docstrings. |
| 557 | string = repr(string) |
| 558 | quote = next((q for q in quote_types if string[0] in q), string[0]) |
| 559 | return string[1:-1], [quote] |
| 560 | if escaped_string: |
| 561 | # Sort so that we prefer '''"''' over """\"""" |
| 562 | possible_quotes.sort(key=lambda q: q[0] == escaped_string[-1]) |
| 563 | # If we're using triple quotes and we'd need to escape a final |
| 564 | # quote, escape it |
| 565 | if possible_quotes[0][0] == escaped_string[-1]: |
| 566 | assert len(possible_quotes[0]) == 3 |
| 567 | escaped_string = escaped_string[:-1] + "\\" + escaped_string[-1] |
| 568 | return escaped_string, possible_quotes |
| 569 | |
| 570 | def _write_str_avoiding_backslashes(self, string, *, quote_types=_ALL_QUOTES): |
| 571 | """Write string literal value with a best effort attempt to avoid backslashes.""" |
no test coverage detected