libtexpr is a Python library that parses and evaluates placeholders such as [ДОЛГ.СУММА * 2 | деньги: кратко] or [DEBT.AMOUNT * 2 | money: short]. It is for applications that fill data into document templates and let template authors write fields and functions in their own language: Cyrillic or Latin.
The library reads and checks a placeholder, then evaluates it for the given data. The functions themselves (declension, amount in words, date format) are written by the application: the library only calls them in order.
Quick start
uv add libtexpr
The function деньги formats a number; the placeholder computes a sum and applies the function.
from decimal import Decimal
from libtexpr import Engine, FieldType, Function, Param, Placeholder
def money(value: Decimal, args: tuple[str, ...]) -> str:
text = f"{value:,.2f}".replace(",", " ").replace(".", ",")
return text + (" руб." if args == ("кратко",) else " рублей")
engine = Engine()
engine.register(
Function(
"деньги",
money,
FieldType.NUMBER,
FieldType.TEXT,
(Param(frozenset({"кратко", "полно"}), default="кратко"),),
)
)
placeholder = Placeholder.parse("ДОЛГ.СУММА * 2 | деньги")
schema = {"ДОЛГ.СУММА": FieldType.NUMBER}
data = {"ДОЛГ.СУММА": "1 000,5"}
print(engine.validate(placeholder, schema))
print(engine.evaluate(placeholder, data))
print(engine.render_text("Сумма: [ДОЛГ.СУММА | деньги: полно]", data))
Output:
[]
2 001,00 руб.
Сумма: 1 000,50 рублей
The empty list on the first line means there are no problems.
Syntax
A placeholder is a value followed by a chain of functions separated by |:
[ value | function | function: argument, argument ]
| Placeholder | What it does |
|---|---|
[ПОЛЕ] |
takes the value of a field |
[ДОЛГ.СУММА], [А.Б.В] |
a field name may contain dots, e.g. as a hierarchy |
[родился] |
a word as plain text |
[100], [-ПОЛЕ] |
a number |
[(ДОЛГ.СУММА + ПЕНИ.СУММА) * 0.01] |
arithmetic: + - * / and parentheses |
[ФИО.ПОЛНОЕ | падеж: род] |
a function with an argument |
[ФИО.ПОЛНОЕ | падеж: род | инициалы] |
a chain: the result of one function feeds the next |
[ЧИСЛО.ДЕЛ | число: текст, женский] |
several arguments separated by commas |
[родился | согласуй: ФИО.ПОЛНОЕ] |
a function argument can be a field |
[DEBT.AMOUNT * 2 | money: short] |
the same syntax in Latin |
Rules:
- A name in UPPERCASE letters is a field (
ПОЛЕ,DEBT,ДОЛГ.СУММА,DEBT.AMOUNT). Functions and words are lowercase. Only Cyrillic and Latin letters are allowed; a name starts with a letter. - An argument is a word, a number or a field. There is no arithmetic inside an argument.
- Arithmetic (
+ - * /) is allowed only in the value, before the first function: the result of a function cannot go back into arithmetic. Compute first, then apply functions:[А.Б * 2 | округлить: 1]. - In the template text the decimal part is written with a dot (
0.5), because a comma separates arguments. In data a comma is accepted:"1 000,5". - There are no quoted strings, conditions, loops or nested calls
f(g(x)): use the chainx | g | finstead.
Optional blocks
Text in braces is kept only when every placeholder inside has a value: {Passport: [DEBTOR.PASSPORT]}.
- If any placeholder inside is empty, the whole block is removed, label included; otherwise it stays without the braces.
- Three functions:
Engine.render_blocks(text, data)settles only the blocks,Engine.render_placeholders(text, data)replaces only the[...], andEngine.render_text(text, data)does both. - A missing value where a number or a date is needed counts as empty. A placeholder that does not parse never counts as empty.
- A block holds at least one placeholder, does not nest and does not span lines.
Block.check(text)lists what breaks these rules, each as aBlockIssue(kind, text): the kind isUNCLOSED,UNOPENED,EMPTYorNESTED(BlockIssueKind), the text is the piece it is about as written.render_blocksleaves such text as written.
A syntax error is a ParseError carrying the character position: UnexpectedCharacterError (for example $ or a Greek letter), UnexpectedTokenError (for example an unclosed parenthesis), InvalidNumberError, LimitExceededError.
Functions and types
A function is described by Function(name, run, input_type, output_type, params):
run(value, args)is the code of the function.argsholds exactly one string perParam: an omitted argument is replaced by its default, a field by its value fromdata.Param(choices, default)is one argument: the allowed words (empty means any) and the default value (Nonemakes the argument required).- A mistake in the description (a name that is not lowercase Latin or Cyrillic letters, a required parameter after an optional one) raises
InvalidSignatureErroras soon as theFunctionis created.
The value keeps its type between functions:
FieldType |
Python object |
|---|---|
TEXT |
str |
NUMBER |
decimal.Decimal |
DATE |
datetime.date |
A NUMBER → NUMBER function receives and returns a Decimal. Before each call evaluate converts the value to the input type: text to a number (NotNumericError) and to an ISO 8601 date (NotDateError). The result of evaluate is always text. An exception inside run, or a result of the wrong type, becomes a FunctionError.
validate is stricter than evaluate: the type of the value must match the input type of the function. It returns all the problems it finds (UNKNOWN_FIELD, UNKNOWN_FUNCTION, TYPE_MISMATCH, BAD_ARGUMENT), so the template author learns about every mistake at once.
Limits
- A placeholder is at most 500 characters (
Placeholder.MAX_LENGTH), and parentheses and unary minus nest at most 20 levels (Placeholder.MAX_NESTING); beyond that,LimitExceededError. - Arithmetic runs in
Decimal:0.1 + 0.2gives exactly0.3; division is exact to 28 significant digits.
Requirements
Python 3.12 or newer. No dependencies.
Development
make test # tests
make lint # style check
make format # auto-format
See CONTRIBUTING.md and CHANGELOG.md.
License
Metadata
Release files for libtexpr 0.2.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| libtexpr-0.2.0.tar.gz | 17.9 kB | Without provenance | Details for libtexpr-0.2.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| libtexpr-0.2.0-py3-none-any.whl | Python 3 | none | any | Details for libtexpr-0.2.0-py3-none-any.whl |
Total release size: 37.2 kB
Release files / libtexpr-0.2.0.tar.gz
| Download URL | libtexpr-0.2.0.tar.gz |
|---|---|
| Size | 17.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
97d9a813ac8f062b063bc38d4de6a8dc900e15f4e68e1b71b3c536db4c41097d
|
|
BLAKE2b-256 checksum How to use checksums |
428572080861dbe33bdd7913c51fb459fd08f86939e817690c49f462b5553c02
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / libtexpr-0.2.0-py3-none-any.whl
| Download URL | libtexpr-0.2.0-py3-none-any.whl |
|---|---|
| Size | 19.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
26fa3ba90f93c0d50a5a03371a593f296baf2e35ece8d98149072191af6324fd
|
|
BLAKE2b-256 checksum How to use checksums |
a4d73439a04631e255a56e61f3386be01066ac5e42497c83edb915f5c3442ad2
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for libtexpr 0.2.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.