← retour aux snippets

pprint: affichage compact et lisible

Imprimer des structures complexes de manière stable et lisible.

python util #pprint#debug#format

objectif

Imprimer des structures complexes de manière stable et lisible.

code minimal

from pprint import pformat
data = {"b": [3,2,1], "a": {"x": 1, "y": 2}}
s = pformat(data, width=40, sort_dicts=True, compact=True)
print(isinstance(s, str) and "a" in s and "b" in s)  # attendu: True

utilisation

from pprint import pprint
pprint({"x": list(range(5))}, width=20, compact=True)
print(True)

variante(s) utile(s)

from pprint import pformat
nested = [{"k": i, "v": list(range(i))} for i in range(3)]
print(len(pformat(nested, depth=1)) > 0)

notes

  • pformat retourne une chaîne, pratique pour logs/tests.
  • sort_dicts=True rend l’ordre stable pour des diffs.