Skip to main content

No project description provided

Project description

dumpobj

A tiny utility to introspect and pretty-print Python objects as a structured tree.

It walks an object, builds a neutral Node tree (key/props/attrs/value/children), and lets you render it with pluggable formatters (plain, color, json).

  • Zero dependencies, Python 3.10+
  • Handles built-in containers, primitives, classes, instances, exceptions, and ellipsis
  • Controls for depth, item count limits, and recursion handling
  • Hook to register custom type handlers

Installation

pip install dumpobj

Requires Python 3.10 or above.

Quick start

from dumpobj import Dump
from dumpobj.formatter.plain_formatter import PlainFormatter

obj = {
    "a": [1, 2, 3, 4, 5],
    "b": "ABCDEFG",
    "c": {"x": 1, "y": 2},
}

# Configure
d = Dump()
d.set_inline(True)      # detailed tree with children; False -> compact summaries
d.set_head_count(3)     # print only the first 3 items in containers/strings
d.set_depth(5)          # traverse at most 5 levels
d.set_str_if_recur("<recur>")  # or Ellipsis for default

# Choose a formatter (optional; default is PlainFormatter)
d.set_formatter(PlainFormatter())

# Print directly — dump() returns a generator of lines/items
for line in d.dump(obj):
    print(line)

# If you need the raw Node tree for advanced processing:
node = d.dump_raw(obj)

Use JSON output

from dumpobj import Dump
from dumpobj.formatter.json_formatter import JSONFormatter

obj = {"a": 1, "b": [1, 2, 3]}

d = Dump()
d.set_formatter(JSONFormatter())

for chunk in d.dump(obj):
    print(chunk)  # prints a JSON string of the object structure

Notes:

  • The plain formatter prints a lightweight tree. You can implement your own formatter by subclassing Formatter.
  • "More N items..." indicates truncated content when head_count is reached.
  • dump_raw(obj) returns the intermediate Node tree without rendering.

Concepts and data model

The dumper constructs an intermediate tree of Node objects before rendering.

Node fields:

  • key: str — the field/index name (e.g., a dict key or list index like "[0]")
  • props: dict — core descriptors
    • title: e.g., the class name of an object
    • type: e.g., "dict", "list", "str", "int", or a fully-qualified class name
  • attrs: dict[str, Any] — extra attributes collected per type, e.g.:
    • "@": object id in hex
    • "len": container length
    • "sizeof": Python sizeof
    • exceptions include a "msg" field
  • value: Any — leaf value as a string (e.g., numbers, truncated strings, compact container preview when not in detail mode)
  • children: list[Node] — nested nodes

API

Dump

Location: dumpobj._dumpobj.Dump

Purpose: Traverse an object and produce a Node tree that represents its structure.

Handled types (by default):

  • dict, list, tuple, set
  • str, bool, int, float, complex, None, Ellipsis
  • BaseException, type, object (generic fallback)

Key methods and properties:

  • set_inline(in_detail: bool):
    • True: build a full tree with children for containers/objects
    • False: store a compact summary string in value for many types
  • set_head_count(n: int): limit items/characters per container/string; default 100
  • get_head_count() -> int | None
  • set_depth(n: int | None): maximum recursion depth; default 5; None means unlimited
  • get_depth() -> int | None
  • set_str_if_recur(mark: str | Ellipsis | None): customize how recursion is marked
    • Ellipsis: sets the key to "..."
    • str: sets the key to that string
    • None: adds a Ref@ attr pointing to the already-seen object id
  • get_str_if_recur() -> str | Ellipsis | None
  • register_handle(t: type, handle: Callable[[Node, object, int], Node]): add/override type handlers
  • dump_raw(obj: object) -> Node: start a new dump pass and return the root node
  • dump(obj: object) -> Generator[Any, Any, None]: render via the configured formatter, yielding printable lines/items

Attributes collected per type are controlled by an internal attr_config. For example, containers and strings include @, __len__, and __sizeof__.

Recursion: The dumper tracks seen object ids. For value types (numbers/strings/bytes/bool), it does not track ids; for others it detects cycles and marks them according to str_if_recur.

Depth and truncation:

  • Depth limit applies to child traversal when in_detail is True.
  • Item limit applies to containers; strings are shortened to the first head_count characters.

Caveat: head_count must be a positive integer in the current version.

Node

Location: dumpobj.node.Node

Accessor methods:

  • set_key/get_key
  • set_prop/get_prop; PropKeys are "title" | "type"
  • set_attr/set_attrs/get_attr/get_attrs
  • set_value/get_value
  • append_node(iter_children): tree building helpers
  • set_parent/get_parent

Formatter, PlainFormatter, JSONFormatter

  • Base class: dumpobj.formatter.base_formatter.Formatter
    • Override _format_key/_format_props/_format_attrs/_format_value/_format_header
    • Lifecycle hooks: _pre_render/_post_render/_pre_node/_post_node
    • render(node) yields lines (or items) lazily
  • Plain implementation: dumpobj.formatter.plain_formatter.PlainFormatter
    • Config: attr_key_rename dict can rename attribute keys in output
    • Indentation: 4 spaces per level, with +-- tree markers
  • JSON implementation: dumpobj.formatter.json_formatter.JSONFormatter
    • Config: compact, indent, ensure_ascii
    • Produces a JSON string representing the object structure

Example: Rename the "@" attribute key to "@":

pf = PlainFormatter()
pf.config["attr_key_rename"] = {"@": "@"}
for line in pf.render(Dump().dump_raw(obj)):
    print(line)

Custom handlers and error handling

You can override how a type is dumped by registering a handler. Handlers receive the current Node, the object, and the current depth, and should mutate/return the node.

If a user-defined handler raises an exception, it’s captured and represented as an ErrorNode in the output.

from datetime import datetime
from dumpobj import Dump
from dumpobj.node import Node

d = Dump()

def dump_datetime(node: Node, obj: datetime, depth: int) -> Node:
    node.set_prop("type", "datetime")
    node.set_value(obj.isoformat())
    return node

d.register_handle(datetime, dump_datetime)

License

MIT License. See LICENSE for details.

Links

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

dumpobj-0.1.1.tar.gz (21.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

dumpobj-0.1.1-py3-none-any.whl (19.6 kB view details)

Uploaded Python 3

File details

Details for the file dumpobj-0.1.1.tar.gz.

File metadata

  • Download URL: dumpobj-0.1.1.tar.gz
  • Upload date:
  • Size: 21.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.9

File hashes

Hashes for dumpobj-0.1.1.tar.gz
Algorithm Hash digest
SHA256 ab0709c29c5f013a61fdb702031cb064e609c2ba7f130a7c76a694d54ba57cc0
MD5 1635a47273b9068a6b77e7ff4ba73a61
BLAKE2b-256 641cd40b4fe34e23de399e60f3b7290bed56489126b4c013d9addd0276a3f6b0

See more details on using hashes here.

File details

Details for the file dumpobj-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: dumpobj-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 19.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.9

File hashes

Hashes for dumpobj-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 5d1cb0201e10b6b592f6b838caf82d8d7d0445b3e88a2ac0e82adb6d37b6ba35
MD5 944ebb9ef3260705189bb831ccc677a4
BLAKE2b-256 23a50a4a9055c2a4862cd68323a62c5f3dacb01e9efaa7f4a8faf62b172894f2

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page