Module

template.core

Kida Template — compiled template object ready for rendering.

The Template class wraps a compiled code object and provides therender() API. Templates are immutable and thread-safe for concurrent rendering.

Architecture:

```
Template
├── _env_ref: WeakRef[Environment]  # Prevents circular refs
├── _code: code object              # Compiled Python bytecode
├── _render_func: callable          # Extracted render() function
└── _name, _filename                # For error messages
```

StringBuilder Pattern:

Generated code usesbuf.append() + ''.join(buf): python def render(ctx, _blocks=None): buf = [] _append = buf.append _append("Hello, ") _append(_e(_s(ctx["name"]))) return ''.join(buf) This is O(n) vs O(n²) for string concatenation.

Memory Safety:

Usesweakref.ref(env)to break potential cycles: Template → (weak) → Environment → cache → Template

Thread-Safety:

  • Templates are immutable after construction
  • render()creates only local state (buf list)
  • Multiple threads can callrender()concurrently

Complexity:

  • render(): O(n) where n = output size
  • _escape(): O(n) single-pass via str.translate()

Classes

Template 21
Compiled template ready for rendering. Wraps a compiled code object containing a ``render(ctx, _bl…

Compiled template ready for rendering.

Wraps a compiled code object containing arender(ctx, _blocks)function. Templates are immutable and thread-safe for concurrentrender()calls.

Thread-Safety:

  • Template object is immutable after construction
  • Eachrender()call creates local state only (buf list)
  • Multiple threads can render the same template simultaneously

Memory Safety: Usesweakref.ref(env)to prevent circular reference leaks: Template → (weak) → Environment → _cache → Template

Methods: render(**context): Render template with given variables render_async(**context): Async render for templates with await

Error Enhancement:

Runtime errors are caught and enhanced with template context:

    ```
    TemplateRuntimeError: 'NoneType' has no attribute 'title'
      Location: article.html:15
      Expression: {{ post.title }}
      Values:
        post = None (NoneType)
      Suggestion: Check if 'post' is defined before accessing .title
    ```

Attributes

Name Type Description
name

Template identifier (for error messages)

filename

Source file path (for error messages)

Methods

name 0 str | None
Template name.
property
def name(self) -> str | None
Returns
str | None
filename 0 str | None
Source filename.
property
def filename(self) -> str | None
Returns
str | None
is_async 0 bool
True if this template uses async constructs (async for / await). Part of RFC: …
property
def is_async(self) -> bool

True if this template uses async constructs (async for / await).

Part of RFC: rfc-async-rendering.

Returns
bool
render 2 str
Render template with given context. User context is now CLEAN - no internal ke…
def render(self, *args: Any, **kwargs: Any) -> str

Render template with given context.

User context is now CLEAN - no internal keys injected. Internal state (_template, _line, _include_depth, _cached_blocks, _cached_stats) is managed via RenderContext ContextVar.

Parameters
Name Type Description
*args
**kwargs
Returns
str Rendered template as string
render_block 3 str
Render a single block from the template. Renders just the named block, useful …
def render_block(self, block_name: str, *args: Any, **kwargs: Any) -> str

Render a single block from the template.

Renders just the named block, useful for caching blocks that only depend on site-wide context (e.g., navigation, footer).

Parameters
Name Type Description
block_name

Name of the block to render (e.g., "nav", "footer") *args: Single dict of context variables **kwargs: Context variables as keyword arguments

*args
**kwargs
Returns
str Rendered block HTML as string
render_with_blocks 3 str
Render this template with pre-rendered HTML injected into blocks. Enables prog…
def render_with_blocks(self, block_overrides: dict[str, str], *args: Any, **kwargs: Any) -> str

Render this template with pre-rendered HTML injected into blocks.

Enables programmatic layout composition: render a page's content, then inject it as thecontentblock of a parent layout template, without needing{% extends %}in the template source.

Each key in block_overrides names a block; the value is a pre-rendered HTML string that replaces that block's default content.

Parameters
Name Type Description
block_overrides

Mapping of block name → pre-rendered HTML string. *args: Single dict of context variables. **kwargs: Context variables as keyword arguments.

*args
**kwargs
Returns
str Rendered template as string with block overrides applied.
render_stream 2
Render template as a generator of HTML chunks. Yields chunks at every statemen…
def render_stream(self, *args: Any, **kwargs: Any)

Render template as a generator of HTML chunks.

Yields chunks at every statement boundary, enabling progressive delivery via chunked transfer encoding.

Parameters
Name Type Description
*args
**kwargs
list_blocks 0 list[str]
List all blocks defined in this template.
def list_blocks(self) -> list[str]
Returns
list[str] List of block names available for render_block()
render_async 2 str
Async wrapper for synchronous render. Runs the synchronous ``render()`` method…
async
async def render_async(self, *args: Any, **kwargs: Any) -> str

Async wrapper for synchronous render.

Runs the synchronousrender()method in a thread pool to avoid blocking the event loop.

Parameters
Name Type Description
*args
**kwargs
Returns
str
render_stream_async 2
Render template as an async generator of HTML chunks. For templates with async…
async
async def render_stream_async(self, *args: Any, **kwargs: Any)

Render template as an async generator of HTML chunks.

For templates with async constructs ({% async for %}, {{ await }}), this calls the native async render function. For sync templates, it wraps the sync render_stream() in an async generator.

Parameters
Name Type Description
*args
**kwargs
render_block_stream_async 3
Render a single block as an async stream. Looks up the async streaming block f…
async
async def render_block_stream_async(self, block_name: str, *args: Any, **kwargs: Any)

Render a single block as an async stream.

Looks up the async streaming block function first, falls back to the sync streaming block function wrapped in an async generator.

Parameters
Name Type Description
block_name

Name of the block to render *args: Single dict of context variables **kwargs: Context variables as keyword arguments

*args
**kwargs
Internal Methods 8
_env 0 Environment
Get the Environment (dereferences weak reference).
property
def _env(self) -> Environment
Returns
Environment
__init__ 6
Initialize template with compiled code.
def __init__(self, env: Environment, code: types.CodeType, name: str | None, filename: str | None, optimized_ast: TemplateNode | None = None, source: str | None = None)
Parameters
Name Type Description
env

Parent Environment (stored as weak reference)

code

Compiled Python code object

name

Template name (for error messages)

filename

Source filename (for error messages)

optimized_ast

Optional preserved AST for introspection. If None, introspection methods return empty results.

Default:None
source

Template source for runtime error snippets. Stored for use by _enhance_error() to provide source context in TemplateRuntimeError exceptions.

Default:None
_build_context 3 dict[str, Any]
Build render context from args and kwargs. Shared by render, render_block, ren…
def _build_context(self, args: tuple[Any, ...], kwargs: dict[str, Any], method_name: str) -> dict[str, Any]

Build render context from args and kwargs.

Shared by render, render_block, render_with_blocks, render_stream, render_stream_async, render_block_stream_async.

Parameters
Name Type Description
args
kwargs
method_name
Returns
dict[str, Any]
_enhance_error 2 Exception
Enhance a generic exception with template context from RenderContext. Converts…
def _enhance_error(self, error: Exception, render_ctx: RenderContext) -> Exception

Enhance a generic exception with template context from RenderContext.

Converts generic Python exceptions into TemplateRuntimeError with template name, line number, and source snippet context.

Parameters
Name Type Description
error
render_ctx
Returns
Exception
_escape 1 str
HTML-escape a value. Uses optimized html_escape from utils.html module. Comple…
staticmethod
def _escape(value: Any) -> str

HTML-escape a value.

Uses optimized html_escape from utils.html module. Complexity: O(n) single-pass using str.translate().

Parameters
Name Type Description
value
Returns
str
_safe_getattr 2 Any
Get attribute with dict fallback and None-safe handling. Resolution order: - D…
staticmethod
def _safe_getattr(obj: Any, name: str) -> Any

Get attribute with dict fallback and None-safe handling.

Resolution order:

  • Dicts: subscript first (user data), getattr fallback (methods). This prevents dict method names likeitems, keys, values, getfrom shadowing user data keys.
  • Objects: getattr first, subscript fallback.

None Handling (like Hugo/Go templates):

  • If obj is None, returns UNDEFINED (prevents crashes)
  • If attribute value is None, returns "" (normalizes output)

Not-Found Handling:

  • Returns theUNDEFINEDsentinel when the attribute/key is not found.UNDEFINED stringifies as ""(so template output is unchanged) butis_defined()recognises it as not defined, fixingx.missing is defined→ False.

Complexity: O(1)

Parameters
Name Type Description
obj
name
Returns
Any
_getattr_preserve_none 2 Any
Get attribute with dict fallback, preserving None values. Like _safe_getattr b…
staticmethod
def _getattr_preserve_none(obj: Any, name: str) -> Any

Get attribute with dict fallback, preserving None values.

Like _safe_getattr but preserves None values instead of converting to empty string. Used for optional chaining (?.) so that null coalescing (??) can work correctly.

Resolution order matches _safe_getattr: dicts try subscript first.

Complexity: O(1)

Parameters
Name Type Description
obj
name
Returns
Any
__repr__ 0 str
def __repr__(self) -> str
Returns
str
RenderedTemplate 3
Lazy rendered template with streaming support. Wraps a Template + context pair. Supports both full…

Lazy rendered template with streaming support.

Wraps a Template + context pair. Supports both full rendering viastr() and chunk-by-chunk iteration via for chunk in rt.

Methods

Internal Methods 3
__init__ 2
def __init__(self, template: Template, context: dict[str, Any])
Parameters
Name Type Description
template
context
__str__ 0 str
Render and return full string.
def __str__(self) -> str
Returns
str
__iter__ 0
Iterate over rendered HTML chunks via render_stream().
def __iter__(self)

Functions

_wrap_blocks_if_cached 2 dict[str, Any] | CachedB…
Wrap blocks with CachedBlocksDict if render context has cached blocks.
def _wrap_blocks_if_cached(blocks: dict[str, Any], render_ctx: RenderContext) -> dict[str, Any] | CachedBlocksDict
Parameters
Name Type Description
blocks dict[str, Any]
render_ctx RenderContext
Returns
dict[str, Any] | CachedBlocksDict