Skip to main content

Template string utilities and backports

Project description

PyPI Version Python Version License Tests

Various template string utilities, with backports for older versions of Python.

tstr is a Python library that provides convenient utility functions for working with PEP 750 template strings. tstr makes template strings easier to use by providing common processing patterns and utilities.

For Python versions older than 3.14, tstr includes a backport allowing you to use template strings functionality in earlier Python versions.

Installation

You can install the tstr package using pip:

pip install tstr

Features

  • Create and manipulate template strings programmatically
  • Full compatibility with Python 3.14's template strings (PEP 750)
  • Backport for Python 3.10-3.13
  • Utility functions for binding, rendering, and comparing templates

Installation

pip install tstr

Included Functions

  • generate_template (alias: t) - Construct a Template object from a string and context
  • render (alias: f)- Render a template to a string, just like f-strings
  • bind - Process a template's interpolations with a binder function
  • binder - Create a reusable template processor function
  • normalize - Convert an interpolation to its value, preserving type when possible
  • normalize_str - Convert an interpolation to a string
  • convert - Apply f-string-like conversion to a value
  • converter - Get a callable that performs f-string conversion
  • template_eq - Compare two templates for equivalence

The package includes the following experimental applications:

  • html_render - Escape HTML with templates
  • execute - Execute SQL with templates, preventing injection attacks

Compatibility

The package automatically detects if native template strings (PEP 750) are supported in your Python version:

  • Python 3.14+: Uses native template string
  • Python 3.10-3.13: Uses compatible backport implementation

The package provides a boolean constant TEMPLATE_STRING_SUPPORTED to check if your Python version supports template strings.

Usage

Creating Templates

from tstr import t, f, generate_template

# Create a template string literal
name = "world"
template = t"Hello, {name}!"
# and render it
print(f(template))  # "Hello, world!"

# Create templates programmatically (useful for Python < 3.14)
template = generate_template("Hello, {name}!")
print(f(template))  # "Hello, world!"
# or using t()
template = t("Hello, {name}!")
print(f(template))  # "Hello, world!"

Template Operations

from tstr import t, f, normalize, normalize_str, template_eq

# Normalize interpolations
age = 42
template = t"Hello, {age}!"
interp = template.interpolations[0]
print(normalize(interp))  # 42
print(normalize_str(interp))  # "42"

# Compare templates
name = "Python"
t1 = t("Hello, {name}!")
t2 = t("Hello, {name}!")
assert template_eq(t1, t2)

Custom Template Processors

from tstr import t, binder, Interpolation

# binder decorates a function that accepts Interpolation values
# and transforms it into a Template converter
@binder
def uppercase_names(i: Interpolation) -> str:
    return normalize_str(i.value).upper()

name = "world"
template = t("Hello, {name}!")
print(uppercase_names(template))  # "Hello, WORLD!"

Experimental Applications

tstr includes several experimental applications that demonstrate how template strings can be applied in real-world scenarios:

Safe HTML Rendering

Automatically escape HTML special characters in template interpolations to prevent XSS attacks:

from tstr._html import html_render

user_input = "<script>alert('XSS')</script>"
template = t"<div>{user_input}</div>"
assert html_render(template) == "<div>&lt;script&gt;alert(&#x27;XSS&#x27;)&lt;/script&gt;</div>"

SQL Injection Prevention

Execute SQL queries with template strings while protecting against SQL injection:

from tstr._sqlite import execute
import sqlite3

conn = sqlite3.connect(":memory:")
cursor = conn.cursor()
cursor.execute("CREATE TABLE users (id PRIMARY KEY, name STRING)")
cursor.execute("INSERT INTO users (name) VALUES ('hello')")

user_input = "'; DROP TABLE users; --"
assert execute(cursor, t"SELECT * FROM users WHERE name = {user_input}").fetchone() is None

cursor.close()
conn.close()

License

Apache License 2.0

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

tstr-0.1.1.post1.tar.gz (33.7 kB view details)

Uploaded Source

Built Distribution

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

tstr-0.1.1.post1-py3-none-any.whl (16.0 kB view details)

Uploaded Python 3

File details

Details for the file tstr-0.1.1.post1.tar.gz.

File metadata

  • Download URL: tstr-0.1.1.post1.tar.gz
  • Upload date:
  • Size: 33.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.0

File hashes

Hashes for tstr-0.1.1.post1.tar.gz
Algorithm Hash digest
SHA256 5887eddd01f6fe7864411962b0593faf8d996950b1403f0dde7110cbb065d331
MD5 1ad2191dd621e71da8555c1d3edbb0fd
BLAKE2b-256 4fae5bacf3c33f17f6e58776787dd52581853b1257bf66bcb7db681431fb2339

See more details on using hashes here.

File details

Details for the file tstr-0.1.1.post1-py3-none-any.whl.

File metadata

  • Download URL: tstr-0.1.1.post1-py3-none-any.whl
  • Upload date:
  • Size: 16.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.6.0

File hashes

Hashes for tstr-0.1.1.post1-py3-none-any.whl
Algorithm Hash digest
SHA256 1900c23d68677b42224ce88b2584c954921d4bb41c84d555a52e9b5df92048c0
MD5 0637327bebfe2cda578be97f5fb272f9
BLAKE2b-256 5f4ddcdb85e444072a50c2554f5cd23814d6c980d56a30a4d0fd1e8a0294d719

See more details on using hashes here.

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