Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Data Pretty Printer (โมดูล pprint)

โมดูล pprint (Pretty Printer) จัดรูปแบบข้อมูล Complex ให้อ่านง่าย: เว้นบรรทัด, Indent, Sort Keys ใช้สำหรับ Debug, Logging, REPL

import pprint


ฟังก์ชันหลัก

pprint.pprint(object, stream=None, indent=1, width=80, depth=None, compact=False, sort_dicts=True)

Print สวยไปที่ Stream (Default: stdout)

pprint.pformat(object, indent=1, width=80, depth=None, compact=False, sort_dicts=True)

คืน String ที่จัดรูปแบบแล้ว (ไม่ Print)

pprint.isreadable(object)

ตรวจสอบว่า Object นี้ Pretty-print ได้หรือไม่ (ไม่มี Recursive Reference)

pprint.isrecursive(object)

ตรวจสอบว่า Object มี Recursive Reference หรือไม่

pprint.PrettyPrinter(...)

Class สำหรับสร้าง Printer แบบกำหนดค่าเอง (Reusable)


Parameters

ParameterDefaultคำอธิบาย
indent1Indentation Per Level
width80Max Line Width
depthNoneMax Depth (None = Unlimited, ใส่ตัวเลขเพื่อจำกัด)
compactFalseTrue = ใส่หลาย Items ต่อบรรทัดถ้าพอ
sort_dictsTrueSort Dict Keys (Python 3.8+)
underscore_numbersFalseFormat Numbers ด้วย Underscore (3.10+)

โค้ดตัวอย่าง

import pprint
import json

# โหลด JSON
with open('sample_json.json') as f:
    data = json.load(f)

print("Raw JSON:")
print(data)

print("\nPretty Printed:")
pprint.pprint(data, width=60, sort_dicts=True)

print("\nCompact Mode:")
pprint.pprint(data, compact=True, width=120)

print("\nLimited Depth:")
pprint.pprint(data, depth=1)

# Get String
formatted = pprint.pformat(data, indent=2, width=80)
print("\nAs String:")
print(formatted)

# Check Readable
print(f"\nIs Readable: {pprint.isreadable(data)}")
print(f"Is Recursive: {pprint.isrecursive(data)}")

ผลลัพธ์

Raw JSON:
[{'name': 'Subhas', 'age': 25, 'city': 'Kolkata'}, {'name': 'Palash', 'age': 22, 'city': 'Delhi'}, {'name': 'Vivek', 'age': 23, 'city': 'Bangaluru'}]

Pretty Printed:
[{'age': 25, 'city': 'Kolkata', 'name': 'Subhas'},
 {'age': 22, 'city': 'Delhi', 'name': 'Palash'},
 {'age': 23, 'city': 'Bangaluru', 'name': 'Vivek'}]

Compact Mode:
[{'age': 25, 'city': 'Kolkata', 'name': 'Subhas'}, {'age': 22, 'city': 'Delhi', 'name': 'Palash'}, {'age': 23, 'city': 'Bangaluru', 'name': 'Vivek'}]

Limited Depth:
[{...}, {...}, {...}]

Custom PrettyPrinter

class MyPrettyPrinter(pprint.PrettyPrinter):
    def format(self, obj, context, maxlevels, level):
        if isinstance(obj, set):
            return f'{{{", ".join(sorted(map(str, obj)))}}}', True, False
        return super().format(obj, context, maxlevels, level)

pp = MyPrettyPrinter(indent=2, width=80)
pp.pprint({1, 3, 2, 'a', 'b'})

การประยุกต์ใช้

  • Debug Complex Data Structures (Nested Dicts/Lists)
  • Log Structured Data
  • Config File Display
  • Test Assertion Messages
  • REPL Enhancement (sys.displayhook = pprint.pprint)