Formatter allowing Itpl style $foo replacement, for names and attribute access only. Standard {foo} replacement also works, and allows full evaluation of its arguments. Examples -------- :: In [1]: f = DollarFormatter() In [2]: f.format('{n//4}', n=8) Ou
| 521 | |
| 522 | |
| 523 | class DollarFormatter(FullEvalFormatter): |
| 524 | """Formatter allowing Itpl style $foo replacement, for names and attribute |
| 525 | access only. Standard {foo} replacement also works, and allows full |
| 526 | evaluation of its arguments. |
| 527 | |
| 528 | Examples |
| 529 | -------- |
| 530 | :: |
| 531 | |
| 532 | In [1]: f = DollarFormatter() |
| 533 | In [2]: f.format('{n//4}', n=8) |
| 534 | Out[2]: '2' |
| 535 | |
| 536 | In [3]: f.format('23 * 76 is $result', result=23*76) |
| 537 | Out[3]: '23 * 76 is 1748' |
| 538 | |
| 539 | In [4]: f.format('$a or {b}', a=1, b=2) |
| 540 | Out[4]: '1 or 2' |
| 541 | """ |
| 542 | |
| 543 | _dollar_pattern_ignore_single_quote = re.compile( |
| 544 | r"(.*?)\$(\$?[\w\.]+)(?=([^']*'[^']*')*[^']*$)" |
| 545 | ) |
| 546 | |
| 547 | def parse(self, fmt_string: str) -> Iterator[Tuple[Any, Any, Any, Any]]: |
| 548 | for literal_txt, field_name, format_spec, conversion in Formatter.parse( |
| 549 | self, fmt_string |
| 550 | ): |
| 551 | # Find $foo patterns in the literal text. |
| 552 | continue_from = 0 |
| 553 | txt = "" |
| 554 | for m in self._dollar_pattern_ignore_single_quote.finditer(literal_txt): |
| 555 | new_txt, new_field = m.group(1,2) |
| 556 | # $$foo --> $foo |
| 557 | if new_field.startswith("$"): |
| 558 | txt += new_txt + new_field |
| 559 | else: |
| 560 | yield (txt + new_txt, new_field, "", None) |
| 561 | txt = "" |
| 562 | continue_from = m.end() |
| 563 | |
| 564 | # Re-yield the {foo} style pattern |
| 565 | yield (txt + literal_txt[continue_from:], field_name, format_spec, conversion) |
| 566 | |
| 567 | def __repr__(self) -> str: |
| 568 | return "<DollarFormatter>" |
| 569 | |
| 570 | #----------------------------------------------------------------------------- |
| 571 | # Utils to columnize a list of string |
no outgoing calls
no test coverage detected
searching dependent graphs…