Wadler-Lindig Pretty Printer
Wadler-Lindig is a Python library that provides a pretty-printer based on the Wadler–Lindig algorithm. It serves as an alternative to the built-in `pprint.pprint`, aiming to produce output that consumes less horizontal space, which is particularly useful for complex custom types, error messages, or nested data structures. The library is characterized by its compact implementation, support for multi-line strings and ANSI escape codes, and zero runtime dependencies. The current version is 0.1.7, and it appears to be actively maintained.
Warnings
- gotcha The `width` argument in `pprint` and `pformat` is a 'best-effort' maximum. It may be exceeded if there are unbroken pieces of text (e.g., long strings) that are inherently wider than the specified width.
- gotcha Customizing pretty-printing for your own types typically uses the `__pdoc__` method, which is specific to this library. For third-party types you don't own, use the `custom` argument in `wl.pprint` or `wl.pformat` instead of `__pdoc__`.
- gotcha This library is designed for pretty-formatting Python *objects* at runtime, similar to the built-in `pprint` module. It is *not* a source code formatter like Black or Rustfmt, and should not be used for reformatting Python source files.
- gotcha Output format differs from Python's built-in `pprint.pprint`. `wadler-lindig` prioritizes reducing horizontal space and often indents more aggressively. It also provides a concise summary for NumPy arrays by default (e.g., `f64[2,3](numpy)`).
Install
-
pip install wadler-lindig
Imports
- pprint
import wadler_lindig as wl wl.pprint(obj)
- pformat
import wadler_lindig as wl formatted_string = wl.pformat(obj)
Quickstart
import dataclasses
import numpy as np
import wadler_lindig as wl
@dataclasses.dataclass
class MyDataclass:
x: list[str]
y: np.ndarray
obj = MyDataclass(
x=["lorem", "ipsum", "dolor sit amet", "consectetur", "adipiscing elit"],
y=np.zeros((2, 3))
)
print("\n--- Default pprint output ---")
print(obj)
print("\n--- wadler_lindig.pprint output (width=30, indent=4) ---")
wl.pprint(obj, width=30, indent=4)
print("\n--- wadler_lindig.pformat output (width=20) ---")
formatted_str = wl.pformat(obj, width=20, indent=2)
print(formatted_str)
# Example of custom pretty-printing for a non-dataclass type
class MyCustomClass:
def __init__(self, value):
self.value = value
def __pdoc__(self, **kwargs) -> wl.AbstractDoc:
return wl.TextDoc(f"<MyCustomClass: {self.value}> ")
def __repr__(self):
return wl.pformat(self, width=80)
custom_obj = MyCustomClass(123)
print("\n--- Custom object with __pdoc__ ---")
wl.pprint(custom_obj)