Python
PHP
var_dump
debugging
programming

What is a Python equivalent of PHP's var_dump?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

PHP var_dump prints type and value details in one call. In Python, there is no exact single built-in equivalent, but several tools provide similar inspection capabilities. The best choice depends on whether you need quick debugging, pretty printing, or structured output.

Quick Inspection with repr and type

For fast checks in scripts, combine type and repr.

python
value = {"name": "Ada", "scores": [91, 88], "active": True}
print(type(value))
print(repr(value))

repr is compact and often enough for small objects.

Pretty Print Nested Structures

Use pprint for readable multi-line output.

python
1from pprint import pprint
2
3payload = {
4    "user": {
5        "id": 42,
6        "roles": ["admin", "editor"],
7        "settings": {"theme": "light", "lang": "en"},
8    },
9    "meta": {"source": "api"},
10}
11
12pprint(payload, width=80, sort_dicts=False)

This is helpful when nested dictionaries become hard to scan.

JSON Formatting for API-Like Data

If data is JSON-serializable, pretty JSON output is often easiest to read.

python
import json

print(json.dumps(payload, indent=2, ensure_ascii=False))

This format is especially useful in logs and HTTP debugging.

Inspect Object Attributes

For custom objects, use vars or dataclass utilities.

python
1from dataclasses import dataclass, asdict
2
3@dataclass
4class User:
5    user_id: int
6    email: str
7
8u = User(7, "[email protected]")
9print(vars(u))
10print(asdict(u))

This is the closest equivalent to object field dumps in dynamic debugging.

Build a Reusable Debug Dump Helper

A small helper can combine type, repr, and optional pretty formatting.

python
1from pprint import pformat
2
3
4def debug_dump(name, value):
5    print(f"name: {name}")
6    print(f"type: {type(value).__name__}")
7    print("value:")
8    print(pformat(value, width=100, sort_dicts=False))
9
10
11debug_dump("payload", payload)

A reusable helper keeps debug output consistent across modules.

Practical Guidance

Use simple output in production logs and detailed dumps only in development or guarded debug mode. Very large dumps can slow programs and expose sensitive data. Redact secrets before printing payloads from external systems.

A disciplined debug strategy keeps logs useful without creating security or performance issues.

Rich Debug Output in Interactive Sessions

For CLI and notebook workflows, richer inspection tools can improve readability. The rich package offers structured, colorized introspection.

python
1from rich import print as rprint
2from rich.pretty import pretty_repr
3
4obj = {
5    "user": "Ada",
6    "items": [1, 2, 3],
7    "active": True,
8}
9
10rprint(pretty_repr(obj))

This is useful during interactive debugging where quick visual parsing matters.

Introspect Unknown Objects Safely

When debugging third-party objects, inspect available attributes without forcing deep representation.

python
1def inspect_object(obj):
2    print("type:", type(obj).__name__)
3    print("has __dict__:", hasattr(obj, "__dict__"))
4    if hasattr(obj, "__dict__"):
5        print("fields:", list(vars(obj).keys()))
6
7inspect_object(obj)

This approach avoids huge dumps while still revealing object structure.

Logging Policy for Dumps

Adopt a policy for where full dumps are allowed. Development logs can include richer output, while production logs should be redacted and size-limited. Structured logging plus controlled dump levels gives useful diagnostics without excessive noise.

A clear policy helps teams debug faster while protecting sensitive information.

Using one shared dump helper across services keeps debug output predictable and easier to search.

Debugging Complex Nested Data

When values contain nested lists, custom objects, and mixed scalar types, combine pprint with selective field extraction. This gives readable output without overwhelming logs.

python
1complex_payload = {
2    "job": "sync",
3    "records": [{"id": 1, "ok": True}, {"id": 2, "ok": False}],
4    "meta": {"retry": 2, "source": "worker-a"},
5}
6
7debug_dump("complex_payload", complex_payload)
8print("record count:", len(complex_payload["records"]))

Selective summaries are often more useful than full raw dumps for day-to-day debugging.

Common Pitfalls

  • Dumping large objects directly in high-volume production paths.
  • Logging sensitive tokens and credentials during debugging.
  • Assuming str output always includes enough structure.
  • Mixing many dump styles and making logs inconsistent.

Summary

  • Python has several var_dump-like options rather than one exact equivalent.
  • Use repr and type for quick checks.
  • Use pprint or JSON formatting for nested data.
  • Build a small helper for consistent, safe debug output.

Course illustration
Course illustration

All Rights Reserved.