Module

template.helpers

Pure runtime helper functions injected into the template namespace.

These functions are called by compiled template code at render time. None of them close over Environment state — they are pure functions that use only their parameters and deferred imports.

Thread-Safety: All functions are stateless and safe for concurrent use.

Classes

_Undefined 7
Sentinel for failed attribute access on objects. - ``str(_Undefined())`` returns ``""`` (template …

Sentinel for failed attribute access on objects.

  • str(_Undefined()) returns ""(template output unchanged)
  • bool(_Undefined()) returns False(falsy guard works)
  • is_defined()recognises it as "not defined"

Methods

Internal Methods 7
__str__ 0 str
def __str__(self) -> str
Returns
str
__repr__ 0 str
def __repr__(self) -> str
Returns
str
__bool__ 0 bool
def __bool__(self) -> bool
Returns
bool
__eq__ 1 bool
def __eq__(self, other: object) -> bool
Parameters
Name Type Description
other
Returns
bool
__hash__ 0 int
def __hash__(self) -> int
Returns
int
__iter__ 0
Empty iterator so ``{% for x in missing %}`` silently yields nothing.
def __iter__(self)
__len__ 0 int
def __len__(self) -> int
Returns
int

Functions

record_filter_usage 3 Any
Record filter usage for profiling, returning the result unchanged. Called by c…
def record_filter_usage(acc: Any, name: str, result: Any) -> Any

Record filter usage for profiling, returning the result unchanged.

Called by compiled code for every filter invocation. When profiling is disabled (acc is None), the cost is a single falsy check + return.

Parameters
Name Type Description
acc Any

RenderAccumulator instance, or None when profiling is off

name str

Filter name for recording

result Any

The filter's return value (passed through unchanged)

Returns
Any
record_macro_usage 3 Any
Record macro ({% def %}) call for profiling, returning the result unchanged. C…
def record_macro_usage(acc: Any, name: str, result: Any) -> Any

Record macro ({% def %}) call for profiling, returning the result unchanged.

Called by compiled code for every macro invocation. When profiling is disabled (acc is None), the cost is a single falsy check + return.

Parameters
Name Type Description
acc Any

RenderAccumulator instance, or None when profiling is off

name str

Macro/def name for recording

result Any

The macro's return value (passed through unchanged)

Returns
Any
lookup 2 Any
Look up a variable in strict mode. In strict mode, undefined variables raise U…
def lookup(ctx: dict[str, Any], var_name: str) -> Any

Look up a variable in strict mode.

In strict mode, undefined variables raise UndefinedError instead of silently returning None. This catches typos and missing variables early, improving debugging experience.

Performance:

  • Fast path (defined var): O(1) dict lookup
  • Error path: Raises UndefinedError with template context
Parameters
Name Type Description
ctx dict[str, Any]
var_name str
Returns
Any
lookup_scope 3 Any
Lookup variable in scope stack (top to bottom), then ctx. Checks scopes from i…
def lookup_scope(ctx: dict[str, Any], scope_stack: list[dict[str, Any]], var_name: str) -> Any

Lookup variable in scope stack (top to bottom), then ctx.

Checks scopes from innermost to outermost, then falls back to ctx. Raises UndefinedError if not found (strict mode).

Parameters
Name Type Description
ctx dict[str, Any]
scope_stack list[dict[str, Any]]
var_name str
Returns
Any
default_safe 3 Any
Safe default filter that works with strict mode. In strict mode, the value exp…
def default_safe(value_fn: Callable[[], Any], default_value: Any = '', boolean: bool = False) -> Any

Safe default filter that works with strict mode.

In strict mode, the value expression might raise UndefinedError. This helper catches that and returns the default value.

Parameters
Name Type Description
value_fn Callable[[], Any]

A lambda that evaluates the value expression

default_value Any

The fallback value if undefined or None/falsy

Default:''
boolean bool

If True, check for falsy values; if False, check for None only

Default:False
Returns
Any
is_defined 1 bool
Check if a value is defined in strict mode. In strict mode, we need to catch U…
def is_defined(value_fn: Callable[[], Any]) -> bool

Check if a value is defined in strict mode.

In strict mode, we need to catch UndefinedError to determine if a variable is defined.

A value is considered undefined when:

  • The variable doesn't exist (raises UndefinedError)
  • The value isNone
  • The value is the_Undefinedsentinel (failed attribute access)

This meansobj.missing_attr is definedcorrectly returns False even whenobj itself exists, because _safe_getattrreturns theUNDEFINEDsentinel for missing attributes.

Parameters
Name Type Description
value_fn Callable[[], Any]

A lambda that evaluates the value expression

Returns
bool
null_coalesce 2 Any
Safe null coalescing that handles undefined variables. In strict mode, the lef…
def null_coalesce(left_fn: Callable[[], Any], right_fn: Callable[[], Any]) -> Any

Safe null coalescing that handles undefined variables.

In strict mode, the left expression might raise UndefinedError. This helper catches that and returns the right value.

Unlike the default filter:

  • Returns right ONLY if left is None or undefined
  • Does NOT treat falsy values (0, '', False, []) as needing replacement
Parameters
Name Type Description
left_fn Callable[[], Any]

A lambda that evaluates the left expression

right_fn Callable[[], Any]

A lambda that evaluates the right expression (lazy)

Returns
Any
spaceless 1 str
Remove whitespace between HTML tags. RFC: kida-modern-syntax-features
def spaceless(html: str) -> str
Parameters
Name Type Description
html str
Returns
str
coerce_numeric 1 int | float
Coerce value to numeric type for arithmetic operations. Handles Markup objects…
def coerce_numeric(value: Any) -> int | float

Coerce value to numeric type for arithmetic operations.

Handles Markup objects (from macros) and strings that represent numbers. This prevents string multiplication when doing arithmetic with macro results.

Parameters
Name Type Description
value Any

Any value, typically Markup from macro or filter result

Returns
int | float
str_safe 1 str
Convert value to string, treating None as empty string. This is used for templ…
def str_safe(value: Any) -> str

Convert value to string, treating None as empty string.

This is used for template output so that optional chaining expressions that evaluate to None produce empty output rather than the literal string 'None'.

RFC: kida-modern-syntax-features — needed for optional chaining.

Parameters
Name Type Description
value Any
Returns
str