|
11 | 11 | ILLEGAL_BASIC_STR_CHARS = frozenset('"\\') | ASCII_CTRL - frozenset("\t") |
12 | 12 | BARE_KEY_CHARS = frozenset(string.ascii_letters + string.digits + "-_") |
13 | 13 | ARRAY_TYPES = (list, tuple) |
14 | | -ARRAY_INDENT = " " * 4 |
15 | 14 | MAX_LINE_LENGTH = 100 |
16 | 15 |
|
17 | 16 | COMPACT_ESCAPES = MappingProxyType( |
|
27 | 26 |
|
28 | 27 |
|
29 | 28 | def dump( |
30 | | - __obj: Mapping[str, Any], __fp: IO[bytes], *, multiline_strings: bool = False |
| 29 | + __obj: Mapping[str, Any], |
| 30 | + __fp: IO[bytes], |
| 31 | + *, |
| 32 | + multiline_strings: bool = False, |
| 33 | + indent: int = 4, |
31 | 34 | ) -> None: |
32 | | - ctx = Context(multiline_strings, {}) |
| 35 | + ctx = Context(multiline_strings, {}, " " * indent) |
33 | 36 | for chunk in gen_table_chunks(__obj, ctx, name=""): |
34 | 37 | __fp.write(chunk.encode()) |
35 | 38 |
|
36 | 39 |
|
37 | | -def dumps(__obj: Mapping[str, Any], *, multiline_strings: bool = False) -> str: |
38 | | - ctx = Context(multiline_strings, {}) |
| 40 | +def dumps( |
| 41 | + __obj: Mapping[str, Any], *, multiline_strings: bool = False, indent: int = 4 |
| 42 | +) -> str: |
| 43 | + ctx = Context(multiline_strings, {}, " " * indent) |
39 | 44 | return "".join(gen_table_chunks(__obj, ctx, name="")) |
40 | 45 |
|
41 | 46 |
|
42 | 47 | class Context(NamedTuple): |
43 | 48 | allow_multiline: bool |
44 | 49 | # cache rendered inline tables (mapping from object id to rendered inline table) |
45 | 50 | inline_table_cache: dict[int, str] |
| 51 | + indent_str: str |
46 | 52 |
|
47 | 53 |
|
48 | 54 | def gen_table_chunks( |
@@ -136,8 +142,8 @@ def format_inline_table(obj: Mapping, ctx: Context) -> str: |
136 | 142 | def format_inline_array(obj: tuple | list, ctx: Context, nest_level: int) -> str: |
137 | 143 | if not obj: |
138 | 144 | return "[]" |
139 | | - item_indent = ARRAY_INDENT * (1 + nest_level) |
140 | | - closing_bracket_indent = ARRAY_INDENT * nest_level |
| 145 | + item_indent = ctx.indent_str * (1 + nest_level) |
| 146 | + closing_bracket_indent = ctx.indent_str * nest_level |
141 | 147 | return ( |
142 | 148 | "[\n" |
143 | 149 | + ",\n".join( |
@@ -197,5 +203,5 @@ def is_aot(obj: Any) -> bool: |
197 | 203 | def is_suitable_inline_table(obj: Mapping, ctx: Context) -> bool: |
198 | 204 | """Use heuristics to decide if the inline-style representation is a good |
199 | 205 | choice for a given table.""" |
200 | | - rendered_inline = f"{ARRAY_INDENT}{format_inline_table(obj, ctx)}," |
| 206 | + rendered_inline = f"{ctx.indent_str}{format_inline_table(obj, ctx)}," |
201 | 207 | return len(rendered_inline) <= MAX_LINE_LENGTH and "\n" not in rendered_inline |
0 commit comments