Skip to main content

printree

Python CI Coverage Status Documentation Status PyPI version PyPI

Tree-like formatting for arbitrary python data structures.

Instalation

pip install printree

Usage

printree aims to be similar to pretty print (pprint) with a format inspired by the tree command:

>>> from printree import ptree, ftree
>>> ptree({"x", len, 42})  # will print to the output console
┐
├── 0: x
├── 1: <built-in function len>
└── 2: 42
>>> ftree({"x", len, 42})  # will return a string representation
'┐\n├── 0: x\n├── 1: <built-in function len>\n└── 2: 42'

Instances of abc.Iterable (with the exception of str & bytes) will be represented as branches. All other objects will be considered leaf nodes:

>>> from printree import ptree
>>> dct = {
...     "foo": [],
...     True: {
...         "uno": {"ABC", "XYZ"},
...         "dos": r"B:\newline\tab\like.ext",
...         "tres": {
...             "leaf": b"bytes",
...             "numbers": (42, -17, 0.01)
...         },
...     },
...     ("tuple", "as", "key"):
...         {"multi\nlined\n\ttabbed key": "multi\nline\n\ttabbed value"}
... }
>>> dct["recursion"] = [1, dct, 2]
>>> ptree(dct)
┐
├── foo
├── True
│   ├── uno
│   │   ├── 0: XYZ
│   │   └── 1: ABC
│   ├── dos: B:\newline\tab\like.ext
│   └── tres
│       ├── leaf: b'bytes'
│       └── numbers
│           ├── 0: 42
│           ├── 1: -17
│           └── 2: 0.01
├── ('tuple', 'as', 'key')
│   └── multi
│       lined
│               tabbed key: multi
│                           line
│                               tabbed value
└── recursion
    ├── 0: 1
    ├── 1: <Recursion on dict with id=2414949505984>
    └── 2: 2

The annotated and depth arguments modify verbosity of the output when creating the tree representation:

>>> ptree(dct, depth=2, annotated=True)
┐ → dict[items=4]
├── foo → list[empty]
├── True → dict[items=3]
│   ├── uno → set[items=2] [...]
│   ├── dos: B:\newline\tab\like.ext
│   └── tres → dict[items=2] [...]
├── ('tuple', 'as', 'key') → dict[items=1]
│   └── multi
│       lined
│               tabbed key: multi
│                           line
│                               tabbed value
└── recursion → list[items=3]
    ├── 0: 1
    ├── 1: <Recursion on dict with id=2414949505984>
    └── 2: 2

Customizing formatting

TreePrinter subclasses can change each of the string representations of the tree. The subclass AsciiPrinter is provided as an example:

>>> from printree import AsciiPrinter
>>> obj = [42, {"foo": (True, False)}]
>>> AsciiPrinter(annotated=True).ptree(obj)
. -> list[items=2]
|-- 0: 42
`-- 1 -> dict[items=1]
    `-- foo -> tuple[items=2]
        |-- 0: True
        `-- 1: False

The main members to override are:

  • ROOT
  • EDGE
  • BRANCH_NEXT
  • BRANCH_LAST
  • ARROW

The level attribute will be automatically set on the printer instance to indicate the current depth in the traversal of the tree.

To print each branch level with a different color, something like the following could be implemented:

from printree import TreePrinter

class ColoredTree(TreePrinter):
    colors = {
        0: '\033[31m',  # red
        1: '\033[32m',  # green
        2: '\033[33m',  # yellow
        3: '\033[36m',  # cyan
        4: '\033[35m',  # magenta
    }
    _RESET = '\033[0m'

    def __getattribute__(self, item):
        if item in ("EDGE", "BRANCH_NEXT", "BRANCH_LAST"):
            return f"{self.color}{getattr(super(), item)}{self._RESET}"
        return super().__getattribute__(item)

    @property
    def color(self):
        return self.colors[self.level % len(self.colors)]

    @property
    def ROOT(self):  # for root (level 0), prefer the color of the children (level 1) 
        return f'{self.colors[1]}{super().ROOT}{self._RESET}'


multiline = {"foo": {False: {"AB\nCD": "xy", 42:len}, True: []}, ("bar",): []}
dct = {"A": multiline, "B": (multiline,), "C\nD": "x\ny", "F": (1, "2")}

import os
os.system("")  # required on windows only

ColoredTree().ptree(dct)

Which outputs:

Metadata

Release files for printree 0.2.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for printree 0.2.1
File Size Uploaded Provenance
printree-0.2.1.tar.gz 8.4 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for printree 0.2.1
File Interpreter ABI Platform
printree-0.2.1-py3-none-any.whl Python 3 none any Details

Total release size: 17.7 kB

Release files / printree-0.2.1.tar.gz

Download URL printree-0.2.1.tar.gz
Size 8.4 kB
Tags Source
SHA-256 checksum
How to use checksums
6c74980256211b9f94abeb77be050d4e5992b5b1e1b147e92d10882ea16947f1
BLAKE2b-256 checksum
How to use checksums
4ac940e508c5539ae7b0e846f20d2b9de88496ed4845b5e27f19c22dcb8c4cf3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.11.9

Release files / printree-0.2.1-py3-none-any.whl

Download URL printree-0.2.1-py3-none-any.whl
Size 9.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
fa86f76a6df9cf43fb9b8e6b7ca588d808ab106f082dc8dc5afe7676eeb52811
BLAKE2b-256 checksum
How to use checksums
bd0eba9a2b70c199b7f0cf374fbe003c4bc36ab8f59f29d89c0559b0bac63f2f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.0.1 CPython/3.11.9

Security for printree 0.2.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page