Skip to main content

Modern template engine for Python 3.14t — AST-native, free-threading ready

Project description

)彡 Kida

PyPI version Build Status Python 3.14+ License: MIT

Modern template engine for Python 3.14t

from kida import Environment

env = Environment()
template = env.from_string("Hello, {{ name }}!")
print(template.render(name="World"))
# Output: Hello, World!

What is Kida?

Kida is a modern template engine for Python 3.14t. It compiles templates to Python AST directly (no string generation), supports streaming and fragment rendering, and is built for free-threading.

What's good about it:

  • AST-native — Compiles to Python AST directly. Structured code manipulation, compile-time optimization, precise error source mapping.
  • Free-threading ready — Safe for Python 3.14t concurrent execution (PEP 703). All public APIs are thread-safe.
  • Dual-mode renderingrender() uses StringBuilder for maximum throughput. render_stream() yields chunks for streaming HTTP and SSE.
  • Modern syntax — Pattern matching, pipeline operator, unified {% end %}, null coalescing, optional chaining.
  • Zero dependencies — Pure Python, includes native Markup implementation.

Installation

pip install kida-templates

Requires Python 3.14+


Quick Start

Function Description
Environment() Create a template environment
env.from_string(src) Compile template from string
env.get_template(name) Load template from filesystem
template.render(**ctx) Render to string (StringBuilder, fastest)
template.render_stream(**ctx) Render as generator (yields chunks)
RenderedTemplate(template, ctx) Lazy iterable wrapper for streaming

Features

Feature Description Docs
Template Syntax Variables, filters, control flow, pattern matching Syntax →
Inheritance Template extends, blocks, includes Inheritance →
Filters & Tests 40+ built-in filters, custom filter registration Filters →
Streaming Statement-level generator rendering via render_stream() Streaming →
Async Support Native async for, await in templates Async →
Caching Fragment caching with TTL support Caching →
Components & Slots {% def %}, {% call %}, default + named {% slot %} Functions →
Partial Evaluation Compile-time evaluation of static expressions Advanced →
Block Recompilation Recompile only changed blocks in live templates Advanced →
Extensibility Custom filters, tests, globals, loaders Extending →

📚 Full documentation: lbliii.github.io/kida


Usage

File-based Templates — Load from filesystem
from kida import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader("templates/"))
template = env.get_template("page.html")
print(template.render(title="Hello", content="World"))
Template Inheritance — Extend base templates

base.html:

<!DOCTYPE html>
<html>
<body>
    {% block content %}{% end %}
</body>
</html>

page.html:

{% extends "base.html" %}
{% block content %}
    <h1>{{ title }}</h1>
    <p>{{ content }}</p>
{% end %}
Control Flow — Conditionals, loops, pattern matching
{% if user.is_active %}
    <p>Welcome, {{ user.name }}!</p>
{% end %}

{% for item in items %}
    <li>{{ item.name }}</li>
{% end %}

{% match status %}
{% case "active" %}
    Active user
{% case "pending" %}
    Pending verification
{% case _ %}
    Unknown status
{% end %}
Components & Named Slots — Reusable UI composition
{% def card(title) %}
<article class="card">
  <h2>{{ title }}</h2>
  <div class="actions">{% slot header_actions %}</div>
  <div class="body">{% slot %}</div>
</article>
{% end %}

{% call card("Settings") %}
  {% slot header_actions %}<button>Save</button>{% end %}
  <p>Body content.</p>
{% end %}

{% slot %} is the default slot. Named slot blocks inside {% call %} map to matching placeholders in {% def %}.

Filters & Pipelines — Transform values
{# Traditional syntax #}
{{ title | escape | capitalize | truncate(50) }}

{# Pipeline operator #}
{{ title |> escape |> capitalize |> truncate(50) }}

{# Custom filters #}
{{ items | sort(attribute="name") | first }}
Streaming Rendering — Yield chunks as they're ready
from kida import Environment

env = Environment()
template = env.from_string("""
<ul>
{% for item in items %}
    <li>{{ item }}</li>
{% end %}
</ul>
""")

# Generator: yields each statement as a string chunk
for chunk in template.render_stream(items=["a", "b", "c"]):
    print(chunk, end="")

# RenderedTemplate: lazy iterable wrapper
from kida import RenderedTemplate
rendered = RenderedTemplate(template, {"items": ["a", "b", "c"]})
for chunk in rendered:
    send_to_client(chunk)

Works with inheritance ({% extends %}), includes, and all control flow. Blocks like {% capture %} and {% spaceless %} buffer internally and yield the processed result.

Async Templates — Await in templates
{% async for item in fetch_items() %}
    {{ item }}
{% end %}

{{ await get_user() }}
Fragment Caching — Cache expensive blocks
{% cache "navigation" %}
    {% for item in nav_items %}
        <a href="{{ item.url }}">{{ item.title }}</a>
    {% end %}
{% end %}

Architecture

Compilation Pipeline — AST-native
Template Source → Lexer → Parser → Kida AST → Compiler → Python AST → exec()

Kida generates ast.Module objects directly. This enables:

  • Structured code manipulation — Transform and optimize AST nodes
  • Compile-time optimization — Dead code elimination, constant folding
  • Precise error source mapping — Exact line/column in template source
Dual-Mode Rendering — StringBuilder + streaming generator
# render() — StringBuilder (fastest, default)
_out.append(...)
return "".join(_out)

# render_stream() — Generator (streaming, chunked HTTP)
yield ...

The compiler generates both modes from a single template. render() uses StringBuilder for maximum throughput. render_stream() uses Python generators for statement-level streaming — ideal for chunked HTTP responses and Server-Sent Events.

Thread Safety — Free-threading ready

All public APIs are thread-safe by design:

  • Template compilation — Idempotent (same input → same output)
  • Rendering — Uses only local state (StringBuilder pattern)
  • Environment — Copy-on-write for filters/tests/globals
  • LRU caches — Atomic operations

Module declares itself GIL-independent via _Py_mod_gil = 0 (PEP 703).


Performance

  • Simple render — ~0.12ms
  • Complex template — ~2.1ms
  • Concurrent (8 threads) — ~0.15ms avg under Python 3.14t free-threading

Documentation

📚 lbliii.github.io/kida

Section Description
Get Started Installation and quickstart
Syntax Template language reference
Usage Loading, rendering, escaping
Extending Custom filters, tests, loaders
Reference Complete API documentation
Tutorials Jinja2 migration, Flask integration

Development

git clone https://github.com/lbliii/kida.git
cd kida
# Uses Python 3.14t by default (.python-version)
uv sync --group dev --python 3.14t
PYTHON_GIL=0 uv run --python 3.14t pytest

The Bengal Ecosystem

A structured reactive stack — every layer written in pure Python for 3.14t free-threading.

ᓚᘏᗢ Bengal Static site generator Docs
∿∿ Purr Content runtime
⌁⌁ Chirp Web framework Docs
=^..^= Pounce ASGI server Docs
)彡 Kida Template engine ← You are here Docs
ฅᨐฅ Patitas Markdown parser Docs
⌾⌾⌾ Rosettes Syntax highlighter Docs

Python-native. Free-threading ready. No npm required.


License

MIT License — see LICENSE for details.

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

kida_templates-0.2.2.tar.gz (327.0 kB view details)

Uploaded Source

Built Distribution

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

kida_templates-0.2.2-py3-none-any.whl (229.8 kB view details)

Uploaded Python 3

File details

Details for the file kida_templates-0.2.2.tar.gz.

File metadata

  • Download URL: kida_templates-0.2.2.tar.gz
  • Upload date:
  • Size: 327.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for kida_templates-0.2.2.tar.gz
Algorithm Hash digest
SHA256 1ea90485882e0e0c6fbaa007d82d2af1a51cfbfbcc5ed423aa707070141c0c70
MD5 027aeeeece6d7615f4c7a5e0e4ae312f
BLAKE2b-256 eea5394b7e13169ea55951bf171c1c27d016ef0f1d2853e57470be927779ac43

See more details on using hashes here.

Provenance

The following attestation bundles were made for kida_templates-0.2.2.tar.gz:

Publisher: python-publish.yml on lbliii/kida

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file kida_templates-0.2.2-py3-none-any.whl.

File metadata

  • Download URL: kida_templates-0.2.2-py3-none-any.whl
  • Upload date:
  • Size: 229.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for kida_templates-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 0bd96f73e1e82ca888f72347f80700e8a57e8f7d7e33ab5a7a29df3167f0505c
MD5 828f6aac5082917266c78b51121915c7
BLAKE2b-256 41777b2f34939bf7b7c00568338c4d6d334b70eb1505c322769dccfc90bd890d

See more details on using hashes here.

Provenance

The following attestation bundles were made for kida_templates-0.2.2-py3-none-any.whl:

Publisher: python-publish.yml on lbliii/kida

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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