Skip to main content

temparse

temparse = template + parse, parse strings using t-string templates.

Inspired by parse, but built on Python 3.14's t-strings, with better type hints.

Installation

uv

uv add temparse

pip

# Requires Python >= 3.14.
pip install temparse

Quick Start

from temparse import parse

city, year = parse[str, int](
    t"I live in {str}, since {int}", "I live in Tokyo, since 2010"
)
assert city == "Tokyo"
assert year == 2010

The return type is tuple[str, int].

Supported Types

Interpolation Example Output
{str} "hello" "hello"
{int} "42" 42
{int} "0xff" 255
{int:16} "ff" 255
{float} "3.14" 3.14
{complex} "-1.23+4.5j" -1.23+4.5j
{list} '[1,2,3]' [1, 2, 3]
{dict} '{"a":1}' {"a": 1}
{json} '{"a":1}' {"a": 1}
{datetime.datetime:%d/%m/%y %H:%M:%S} "31/01/22 23:59:59" datetime
{datetime.date:%Y-%m-%d} "2024-03-15" date
{datetime.time:%H:%M:%S} "13:23:27" time

Custom Conversions

Decorate a function with @Conversion to use it directly in a template:

from temparse import Conversion, parse


@Conversion
def percent(s: str) -> float:
    return float(s.rstrip("%")) / 100


(result,) = parse[float](t"x = {percent}", "x = 30%")
assert result == 0.3

When your converter needs the format spec as well, use FormatConversion:

from temparse import FormatConversion, parse


@FormatConversion
def between(s: str, spec: str) -> str:
    lo, hi = spec.split(",")
    return s[int(lo) : int(hi)]


(result,) = parse[str](t"{between:2,5}", "abcdefg")
assert result == "cde"

Parser (Compiled Templates)

Build a parser once and reuse it:

from temparse import Parser

parser = Parser[str, int, float](t"{str} + {int} = {float}")

assert parser.parse("foo + 3 = 3.14") == ("foo", 3, 3.14)
assert parser.parse("bar + 7 = 2.72") == ("bar", 7, 2.72)

Matcher (Pattern Matching & Structured Parsing)

Subclass Matcher with a Parser to match strings in match/case statements or parse strings directly into structured instances:

from temparse import Matcher, MatchStr, Parser


class OkResp(Matcher, parser=Parser(t'code={int};message="{str}";')):
    code: int
    message: str


class ErrResp(Matcher, parser=Parser(t'code={int};error="{str}";')):
    code: int
    error: str


def handle_response(raw: str) -> str:
    # Wrap the string with MatchStr to enable pattern matching
    match MatchStr(raw):
        case OkResp(code, message):
            return f"OK ({code}): {message}"
        case ErrResp(code, error):
            return f"Error ({code}): {error}"
        case _:
            return "Unknown response"


assert handle_response('code=200;message="success";') == "OK (200): success"
assert handle_response('code=400;error="bad request";') == "Error (400): bad request"

Matcher subclasses are also dataclasses that support keyword matching and .parse():

from temparse import Matcher, MatchStr, Parser


class Point(Matcher, parser=Parser(t"x={int}, y={int}")):
    x: int
    y: int


p = Point.parse("x=1, y=2")
assert p == Point(x=1, y=2)

# Wrap the string with MatchStr to enable pattern matching
match MatchStr("x=0, y=5"):
    case Point(x=0, y=y):
        assert y == 5

License

MIT

Metadata

Release files for temparse 1.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for temparse 1.1.0
File Size Uploaded Provenance Actions
temparse-1.1.0.tar.gz 4.6 kB Without provenance Details for temparse-1.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for temparse 1.1.0
File Interpreter ABI Platform Actions
temparse-1.1.0-py3-none-any.whl Python 3 none any Details for temparse-1.1.0-py3-none-any.whl

Total release size: 9.9 kB

Release files / temparse-1.1.0.tar.gz

Download URL temparse-1.1.0.tar.gz
Size 4.6 kB
Tags Source
SHA-256 checksum
How to use checksums
e5100d8fd07c5f6733ec9cfec4dce658c62535a61f8c6f0dd9bfab05b80bd543
BLAKE2b-256 checksum
How to use checksums
d8f95014b55ff0c0396030b468217adbc5e3187ebb716eca74d69bf92b566d0e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / temparse-1.1.0-py3-none-any.whl

Download URL temparse-1.1.0-py3-none-any.whl
Size 5.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
c264b884715b324b6d523f7d8a47f99030ca10d00cf87cd2e6b260a3a53b015f
BLAKE2b-256 checksum
How to use checksums
65affa4102857ab6fc245f97608f100c5410c61ae50545255c2eb134b5094e29
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.6 {"installer":{"name":"uv","version":"0.13.6","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"24.04","id":"noble","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for temparse 1.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page