|
| 1 | +import builtins |
| 2 | +import string |
| 3 | +from typing import Any, Callable, Generator |
| 4 | + |
| 5 | +from ._base import get, iterate, iterate_result |
| 6 | +from .types import Collection, NO_DEFAULT |
| 7 | + |
| 8 | + |
| 9 | +class _Format(string.Formatter): |
| 10 | + """implements the `format()` function""" |
| 11 | + |
| 12 | + def __init__(self, obj: Collection): |
| 13 | + string.Formatter.__init__(self) |
| 14 | + self._datapath_obj = obj |
| 15 | + |
| 16 | + def get_field(self, field_name, args, kwargs): |
| 17 | + return get(self._datapath_obj, field_name), None |
| 18 | + |
| 19 | + |
| 20 | +def format(obj: Collection, format_string: str) -> str: |
| 21 | + """ |
| 22 | + Given a standard Python format string with {} notation, interpret the identifiers |
| 23 | + as a datapath within `obj`, and apply standard formatting language to the result. |
| 24 | + """ |
| 25 | + return _Format(obj).format(format_string) |
| 26 | + |
| 27 | + |
| 28 | +def _do_format(value: Any, format_spec: str, conversion: str) -> str: |
| 29 | + """do the standard !r / !s / !a format string conversions, followed by builtins.format""" |
| 30 | + if not conversion: |
| 31 | + pass |
| 32 | + elif conversion == 'r': |
| 33 | + value = repr(value) |
| 34 | + elif conversion == 's': |
| 35 | + value = str(value) |
| 36 | + elif conversion == 'a': |
| 37 | + value = ascii(value) |
| 38 | + else: |
| 39 | + raise ValueError(f'unhandled conversion flag {conversion!r}') |
| 40 | + return builtins.format(value, format_spec) |
| 41 | + |
| 42 | + |
| 43 | +def format_iterate(obj: Collection, |
| 44 | + format_string: str, |
| 45 | + default: Any = NO_DEFAULT, |
| 46 | + iter_func: Callable = zip) -> Generator[str, None, None]: |
| 47 | + """ |
| 48 | + Given a standard Python format string with {} notation, interpret the identifiers as iterable datapaths within `obj`. |
| 49 | + One value will be consumed from each iterable path and formatted using the standard language. |
| 50 | +
|
| 51 | + `default` is passed through to all `iterate()` calls, which in turn passes it through to the leaf `get()` calls. |
| 52 | + There is no way to use a different default value for different iterable datapaths in replacement fields. |
| 53 | +
|
| 54 | + By default, the values from the iterators will be obtained with the |
| 55 | + [`zip()` builtin](https://docs.python.org/3/library/functions.html#zip) with `strict=False`, meaning if the different |
| 56 | + iterable format strings produce a differnt number of results, iteration will stop when the shortest one stops, and |
| 57 | + the values will all correspond to the same index from each `iterate()` result. |
| 58 | +
|
| 59 | + Example: |
| 60 | +
|
| 61 | + ``` |
| 62 | + >>> test_obj = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, {'a': 5, 'b': 6}] |
| 63 | + >>> for text in format_iterate(test_obj, 'a {[].a} b {[].b}'): |
| 64 | + ... print(text) |
| 65 | + ... |
| 66 | + a 1 b 2 |
| 67 | + a 3 b 4 |
| 68 | + a 5 b 6 |
| 69 | +
|
| 70 | + ``` |
| 71 | +
|
| 72 | + If different behavior is desired, a different function can be passed: |
| 73 | +
|
| 74 | + `iter_func` must have approximately the same basic signature as `builtins.zip()`, |
| 75 | + [`itertools.product()`](https://docs.python.org/3/library/itertools.html#itertools.product), |
| 76 | + and [`itertools.zip_longest()`](https://docs.python.org/3/library/itertools.html#itertools.zip_longest). |
| 77 | +
|
| 78 | + More specifically, it must accept an arbitrary number of Iterables (specifically the Generator |
| 79 | + returned by `datapath.iterate()`), and yield a Sequence with a value from each one in order when the return |
| 80 | + value is iterated. |
| 81 | +
|
| 82 | + You can supply extra keyword arguments to any function with this signature by utilizing |
| 83 | + [`functools.partial()`](https://docs.python.org/3/library/functools.html#functools.partial). Passing positional |
| 84 | + arguments to a partial will probably not work as expected, and is not recommended. |
| 85 | +
|
| 86 | + Example with a partial and `itertools.zip_longest()`: |
| 87 | +
|
| 88 | + ``` |
| 89 | + >>> import functools, itertools |
| 90 | + >>> test_obj = {'a': list('123'), 'b': list('4567')} |
| 91 | + >>> for text in format_iterate(test_obj, 'a {a[]} b {b[]}', |
| 92 | + ... iter_func=functools.partial(itertools.zip_longest, fillvalue='X')): |
| 93 | + ... print(text) |
| 94 | + a 1 b 4 |
| 95 | + a 2 b 5 |
| 96 | + a 3 b 6 |
| 97 | + a X b 7 |
| 98 | +
|
| 99 | + ``` |
| 100 | + """ |
| 101 | + iterators = [] |
| 102 | + path_formats = [] |
| 103 | + plain_format_string = '' |
| 104 | + for literal_text, field_name, format_spec, conversion in string.Formatter().parse(format_string): |
| 105 | + plain_format_string += literal_text |
| 106 | + if not field_name: |
| 107 | + continue |
| 108 | + plain_format_string += '{}' |
| 109 | + iterators.append(iterate(obj, field_name, default)) |
| 110 | + path_formats.append((format_spec, conversion)) |
| 111 | + |
| 112 | + for results in iter_func(*iterators): |
| 113 | + values = [] |
| 114 | + for index, result in enumerate(results): |
| 115 | + if isinstance(result, iterate_result): |
| 116 | + _, value = result |
| 117 | + else: |
| 118 | + value = result |
| 119 | + format_spec, conversion = path_formats[index] |
| 120 | + values.append(_do_format(value, format_spec, conversion)) |
| 121 | + yield plain_format_string.format(*values) |
0 commit comments