Skip to main content

A simple document rendering system in Python

Project description

pretty-doc

from __future__ import annotations
from dataclasses import dataclass
import pretty_doc as doc
import json

@dataclass
class Block:
    name: str
    contents: list[Block] | str = ""

    def to_doc(self):
        return to_doc(self)

def to_doc(self: Block) -> doc.Doc:
    if isinstance(self.contents, list):
        return doc.vsep([
            doc.seg(self.name) + doc.seg("{"),
            doc.indent(4, doc.vsep(
                list(map(to_doc, self.contents)))),
            doc.seg("}")
        ])

    return doc.seg(self.name) + doc.seg(json.dumps(self.contents))

doc = Block(
    "A",
    [
        Block("C", "ccc"),
        Block("B",
            [
                Block("C", "ccc"),
            ]
        ),
        Block("C", "ccc"),
        Block("C", "ccc"),
    ]
).to_doc()

print(doc.show())
# out:
A {
    C "ccc"
    B {
        C "ccc"
    }
    C "ccc"
    C "ccc"
}

import sys
doc.render(sys.stdout.write)
# out:
A {
    C "ccc"
    B {
        C "ccc"
    }
    C "ccc"
    C "ccc"
}

Project details


Release history Release notifications | RSS feed

This version

0.3

Download files

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

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distribution

pretty_doc-0.3-py3-none-any.whl (4.1 kB view hashes)

Uploaded Python 3

Supported by

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