Skip to content

Commit 629f1cf

Browse files
committed
extract func pformat_deterministic
1 parent ff337de commit 629f1cf

1 file changed

Lines changed: 14 additions & 10 deletions

File tree

mypyc/codegen/emit.py

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -210,16 +210,7 @@ def object_annotation(self, obj: object, line: str) -> str:
210210
211211
If it contains illegal characters, an empty string is returned."""
212212
line_width = self._indent + len(line)
213-
214-
# temporarily override pprint._safe_key
215-
default_safe_key = pprint._safe_key # type: ignore [attr-defined]
216-
pprint._safe_key = _mypyc_safe_key # type: ignore [attr-defined]
217-
218-
# pretty print the object
219-
formatted = pprint.pformat(obj, compact=True, width=max(90 - line_width, 20))
220-
221-
# replace the _safe_key
222-
pprint._safe_key = default_safe_key # type: ignore [attr-defined]
213+
formatted = pformat_deterministic(obj, line_width)
223214

224215
if any(x in formatted for x in ("/*", "*/", "\0")):
225216
return ""
@@ -1283,6 +1274,19 @@ def native_function_doc_initializer(func: FuncIR) -> str:
12831274
return c_string_initializer(docstring.encode("ascii", errors="backslashreplace"))
12841275

12851276

1277+
def pformat_deterministic(obj: object, line_width: int) -> str:
1278+
"""Pretty-print `obj` with deterministic sorting for mypyc literal types."""
1279+
# Temporarily override pprint._safe_key
1280+
default_safe_key = pprint._safe_key # type: ignore [attr-defined]
1281+
pprint._safe_key = _mypyc_safe_key # type: ignore [attr-defined]
1282+
1283+
try:
1284+
return pprint.pformat(obj, compact=True, width=max(90 - line_width, 20))
1285+
finally:
1286+
# Always restore the original key to avoid affecting other pprint users.
1287+
pprint._safe_key = default_safe_key # type: ignore [attr-defined]
1288+
1289+
12861290
def _mypyc_safe_key(obj: object) -> str:
12871291
"""A custom sort key implementation for pprint that makes the output deterministic
12881292
for all literal types supported by mypyc.

0 commit comments

Comments
 (0)