API reference

class hyperscribe.DocWriter(writer: Writer[str] | Callable[[str], Ignored])[source]

Write escaped HTML fragments to a text stream or a function.

writer is anything with a write(str) method, such as an open file or a io.StringIO, or a function that is called with each piece of text instead, such as the append method of a list. Only the write method is kept, so a writer that has one is never called itself.

tags: _TagBuilder

Tags by name, as in doc.tags.div, or doc.tags["my-element"].

voids: _Voids

Void elements by name, as in doc.voids.br().

property parts: tuple[DocWriter, _TagBuilder, _Voids]

Return the writer, its tags and its void elements, for unpacking.

doc, t, v = DocWriter(output).parts gives short local names.

__call__(value: TrustedContent) → None[source]

Write trusted content verbatim, preserving the current indentation.

Strings with non-literal provenance must be passed to escape(). Objects implementing __html__ contribute their trusted HTML string; literal strings and primitive numeric values are also written verbatim. Tag content, as in doc.tags.p(...), is handled the same way.

inline() → AbstractContextManager[None][source]

Suppress line breaks and indentation for the markup written in the block.

The block is indented and ends its line like any other tag, so with doc.inline(), doc.tags.div: renders the whole div on one line. Blocks may be nested; formatting resumes once the outermost one exits.

comment(text: str) → None[source]

Write an HTML comment on its own line.

The text is written as given, so it must not be able to end the comment early. A ValueError is raised if it contains --.

hyperscribe.Ignored

The return type of callbacks whose result hyperscribe does not look at.

It is object, so functions returning anything at all are accepted, such as list.append, which returns None, and a text stream’s write, which returns the number of characters written. Unlike Any, it does not switch off type checking of the result.

hyperscribe.TrustedContent

Represent a union type

E.g. for int | str

hyperscribe.AttributeValue

Represent a union type

E.g. for int | str

Markup

Helpers that turn values into text that is safe to write as HTML.

They are also available from hyperscribe itself.

hyperscribe.markup.escape(value: str) → SafeStr[source]

Escape &, <, > and quotes so the text can be written as HTML.

Quotes are escaped as well, so the result is safe in text and in attribute values.

hyperscribe.markup.escape_silent(value: str | None) → SafeStr[source]

Like escape(), but write None as an empty string.

Use it for optional values, such as a field that may be missing in some data, where an empty result is what the page should show.

hyperscribe.markup.trust(value: str) → SafeStr[source]

Mark a string as safe to write as HTML, without escaping it.

Only use it for content that cannot contain untrusted input.

hyperscribe.markup.tokenlist(*names: str | Mapping[str, object] | Literal[False] | None) → SafeStr | None[source]

Join names into a space-separated list, such as the class attribute.

Each argument is a name, or several separated by spaces, or a mapping from names to whether to include them, so conditional names can be written next to fixed ones:

t.button("Save", class_=tokenlist("btn", {"active": is_active}, extra))
t.a("Docs", href=url, rel=tokenlist("noopener", {"noreferrer": external}))

It is named after the DOM’s DOMTokenList, which element.classList and element.relList are.

None and False are skipped, so is_active and "active" works as an argument too. The names are escaped. If no names are left, None is returned, which leaves the attribute out altogether.

hyperscribe.markup.SafeStr

A string that is safe to write as HTML, returned by escape() and trust().

It only exists for type checkers; at runtime it is a plain str. Attribute values are escaped as usual, whatever their type.

Streaming

Stream documents in chunks, for example to an async web server.

Templates still write synchronously to a DocWriter. What they write is collected in a list, and the document is sent on in chunks at the few places where it is worth it, usually right before the template waits for something slow:

  • AsyncDocWriter sends the buffer when the template calls await doc.drain().

  • aiter_chunks() turns a template written as an async generator into an async iterator of chunks, which most async web frameworks accept as a streaming response body. The document is split at each bare yield.

  • iter_chunks() does the same for synchronous servers, such as WSGI ones, with a template written as a generator.

OutOfOrder works with the async ones. It writes placeholders for slow content, so the rest of the page can be sent first, and fills them in as the content becomes available.

class hyperscribe.streaming.AsyncDocWriter(send: Callable[[str], Awaitable[Ignored]])[source]

A writer that keeps what is written until await doc.drain() sends it.

Like asyncio.StreamWriter.drain(), drain() waits until the data written so far has been passed on: send is awaited with each chunk, so a slow client holds the template up instead of letting the buffer grow. It can be a wrapper around an ASGI send callable, or around asyncio.StreamWriter.write() and drain(). Call drain() once more when the template is done, to send whatever it wrote after the last time.

The template sends the chunks itself, so timeouts and cancel scopes in it cover the sending as well, and can be used anywhere, unlike with aiter_chunks().

async drain() → None[source]

Send what has been written since the last drain, if anything.

hyperscribe.streaming.aiter_chunks(template: ~collections.abc.Callable[[~typing.Concatenate[~hyperscribe.DocWriter, ~_P]], ~collections.abc.AsyncIterator[None]], /, *args: ~typing.~_P, **kwargs: ~typing.~_P) → AsyncGenerator[str, None][source]
hyperscribe.streaming.aiter_chunks(template: ~collections.abc.Callable[[~typing.Concatenate[~hyperscribe.DocWriter, ~_P]], ~collections.abc.Iterator[None]], /, *args: ~typing.~_P, **kwargs: ~typing.~_P) → AsyncGenerator[str, None]

Render a generator template in chunks, as an async iterator of strings.

The template is called with a new DocWriter, followed by args and kwargs. It is an async generator, and the document is split each time it yields, so a bare yield sends everything written up to that point. What it yields is ignored, and the rest of the document is sent when it returns. A synchronous generator is accepted as well, as for iter_chunks(), so the same template can be served by synchronous and async servers.

Stopping the iterator early, as servers do when a client disconnects, closes the template, so its finally blocks and with exits run.

The template is paused at each yield while its chunk is sent, in the same task, as with any async generator. So it must not yield inside a block that limits its task, such as asyncio.timeout(), an asyncio.TaskGroup or a Trio cancel scope, which would otherwise limit sending the chunk as well. Use AsyncDocWriter for templates that need such blocks around output.

hyperscribe.streaming.iter_chunks(template: ~collections.abc.Callable[[~typing.Concatenate[~hyperscribe.DocWriter, ~_P]], ~collections.abc.Iterator[None]], /, *args: ~typing.~_P, **kwargs: ~typing.~_P) → Generator[str, None, None][source]

Render a generator template in chunks, as an iterator of strings.

The template is called with a new DocWriter, followed by args and kwargs, and the document is split each time it yields, so a bare yield sends everything written up to that point. What it yields is ignored, and the rest of the document is sent when it returns. This suits synchronous servers that accept an iterator as a response body, such as WSGI ones, which want the chunks encoded as bytes.

Closing the iterator early closes the template, so its finally blocks and with exits run.

class hyperscribe.streaming.OutOfOrder(doc: DocWriter, *, prefix: str = 'hyperscribe-slot', nonce: str | None = None)[source]

Send the rest of the page while slow parts of it are still loading.

It is used in a with statement around the part of the page that contains the placeholders:

with OutOfOrder(doc) as slots:
    t.div("Loading…", id=slots.defer(fetch_articles(), article_list))
    t.footer("Thanks for reading")
    yield
    async for _ in slots.resolve():
        yield

defer() starts waiting for the data of slow content in the background and returns the ID of a placeholder to write in its place. resolve() then renders each part as soon as its data arrives, in whatever order that is, inside a <template> followed by a small script that moves it into place in the browser. It yields after each part, so the template can send it on: with a yield in an async generator template rendered by aiter_chunks(), or with await doc.drain() for an AsyncDocWriter.

If the block ends with an exception, including when the response is stopped because the client disconnected, the parts still loading are cancelled. If it ends without one while parts are still waiting to be resolved, they are cancelled as well and RuntimeError is raised.

Waiting in the background uses asyncio tasks, so unlike the rest of this module it needs asyncio.

__init__(doc: DocWriter, *, prefix: str = 'hyperscribe-slot', nonce: str | None = None) → None[source]

Write the placeholders and parts of doc.

Placeholders without an id of their own get the IDs prefix-1, prefix-2 and so on, so prefix has to be unique within the page. nonce is added to each script, for pages with a content security policy that requires one.

defer(awaitable: Awaitable[_T], render: Callable[[DocWriter, _T], None], /, *, id: str | None = None, keep: bool = False) → SlotId[source]

Return the ID of a placeholder to write now, filled in by render later.

The placeholder is any element with this ID, written like any other, with a loading message for example:

t.div("Loading…", id=slots.defer(fetch_articles(), article_list))

with t.section(id=slots.defer(fetch_articles(), article_list)):
    t.h2("Articles")
    t.p("Loading…")

Once the data has arrived, render(doc, data) is called, and by default the placeholder is replaced as a whole by what it writes. With keep, the element stays and only its content is replaced, so the element becomes the parent of what render writes.

The ID is id if given, which is then up to the caller to keep unique, and made from the prefix otherwise. awaitable starts running right away, so several deferred parts load concurrently.

write_completed() → int[source]

Write the deferred parts whose data has already arrived, without waiting.

Call it before waiting for something slow that is not deferred, and send them on with a yield, or await doc.drain() for an AsyncDocWriter, so the parts that are done are sent first. Returns how many parts were written.

async resolve() → AsyncIterator[None][source]

Render the deferred parts in the order their data arrives.

This yields after writing each part, so the caller can send it on:

async for _ in slots.resolve():
    yield  # or: await doc.drain()

Call it inside the with block, where the parts should be written, usually right before </body>. Parts whose data arrives together are written in the order they were deferred. If rendering a part fails, the parts still loading are cancelled.

cancel() → None[source]

Stop waiting for the deferred parts that have not been written yet.

Their awaitables are cancelled, including tasks and futures that were passed to defer() as they are.

__exit__(exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None) → None[source]

Cancel the parts that have not been written.

If the block ends without an exception while parts are left, resolve() was not called for them, and RuntimeError is raised.

class hyperscribe.streaming.SlotId(target: str)[source]

The ID of a deferred part’s placeholder, from OutOfOrder.defer().

Write it as the id of the element that the part should take the place of, as in t.div("Loading…", id=slot). It is written escaped, and only once, so that OutOfOrder.resolve() can tell whether every placeholder is in the page.

Tag objects

tags is a tag builder, and voids looks up void element builders. They are documented here because they appear in the signatures above, but you normally do not create them yourself.

class hyperscribe._TagBuilder(_doc: DocWriter, _openings: tuple[str, ...], _closings: tuple[str, ...], _children: dict[str, _TagBuilder] | None = None)[source]

Represent a chain of tags, usable directly or with attributes supplied by a call.

Builders are immutable, so they can be cached and nested inside themselves.

__getattr__(name: str) → _TagBuilder[source]

Return a builder for a nested tag, such as main in doc.body.main.

__getitem__(name: str) → _TagBuilder[source]

Return a builder for a nested tag, as in doc.div["x-y"].

__call__(**attrs: AttributeValue) → _TagBuilder[source]
__call__(content: TrustedContent, /, **attrs: AttributeValue) → None

Write a leaf element when given content, else return a builder.

Attributes are added to the innermost tag, after any it was given by an earlier call. The content is handled like that of DocWriter.__call__(): it is written verbatim, so a string that is not a literal has to go through escape() first. None is rejected with a TypeError instead of being mistaken for missing content.

class hyperscribe._Voids(_doc: DocWriter, _builders: dict[str, ~hyperscribe._VoidBuilder]=<factory>)[source]

Look up void elements by name, as in doc.voids.br().

__getattr__(name: str) → _VoidBuilder[source]

Return the void element with this name, such as img.

__getitem__(name: str) → _VoidBuilder[source]

Return the void element with any name, as in doc.voids["x-y"].

class hyperscribe._VoidBuilder(_doc: DocWriter, _opening: str)[source]

Write a void element, such as <br>, on its own line when called.

__call__(**attrs: AttributeValue) → None[source]

Write the element with the given attributes.

Void elements have no content and no closing tag, so there is nothing to pass as content or to enter as a context manager.