jinja-types 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. jinja_types/__init__.py +38 -0
  2. jinja_types/cli.py +53 -0
  3. jinja_types/contrib/__init__.py +1 -0
  4. jinja_types/contrib/babel.py +245 -0
  5. jinja_types/core/__init__.py +36 -0
  6. jinja_types/core/catalog.py +175 -0
  7. jinja_types/core/collection.py +237 -0
  8. jinja_types/core/errors.py +42 -0
  9. jinja_types/core/invoker.py +204 -0
  10. jinja_types/core/namespace.py +21 -0
  11. jinja_types/core/options.py +28 -0
  12. jinja_types/core/plugins.py +46 -0
  13. jinja_types/core/registry.py +192 -0
  14. jinja_types/core/spec.py +52 -0
  15. jinja_types/extension.py +84 -0
  16. jinja_types/helpers/__init__.py +8 -0
  17. jinja_types/helpers/convert.py +248 -0
  18. jinja_types/helpers/globals.py +133 -0
  19. jinja_types/py.typed +0 -0
  20. jinja_types/regex/__init__.py +1 -0
  21. jinja_types/regex/engine.py +64 -0
  22. jinja_types/regex/match_.py +121 -0
  23. jinja_types/regex/pattern_.py +165 -0
  24. jinja_types/regex/re_.py +170 -0
  25. jinja_types/types/__init__.py +41 -0
  26. jinja_types/types/ar_.py +354 -0
  27. jinja_types/types/bool_.py +12 -0
  28. jinja_types/types/date_.py +137 -0
  29. jinja_types/types/datetime_.py +267 -0
  30. jinja_types/types/decimal_.py +450 -0
  31. jinja_types/types/dict_.py +116 -0
  32. jinja_types/types/float_.py +53 -0
  33. jinja_types/types/fraction_.py +86 -0
  34. jinja_types/types/int_.py +102 -0
  35. jinja_types/types/list_.py +138 -0
  36. jinja_types/types/path_.py +190 -0
  37. jinja_types/types/str_.py +406 -0
  38. jinja_types/types/time_.py +120 -0
  39. jinja_types/types/timedelta_.py +34 -0
  40. jinja_types/types/uuid_.py +126 -0
  41. jinja_types-0.1.0.dist-info/METADATA +162 -0
  42. jinja_types-0.1.0.dist-info/RECORD +45 -0
  43. jinja_types-0.1.0.dist-info/WHEEL +4 -0
  44. jinja_types-0.1.0.dist-info/entry_points.txt +3 -0
  45. jinja_types-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,38 @@
1
+ """Python type methods and attributes as qualified Jinja2 filters and tests."""
2
+
3
+ from .core import (
4
+ BuiltinClashError,
5
+ Catalog,
6
+ CatalogEntry,
7
+ Collection,
8
+ Conflict,
9
+ DuplicateMemberError,
10
+ JinjaTypesError,
11
+ Kind,
12
+ MemberSpec,
13
+ Namespace,
14
+ Options,
15
+ Param,
16
+ Registry,
17
+ RegistryError,
18
+ )
19
+ from .extension import TypesExtension, install
20
+
21
+ __all__ = [
22
+ "BuiltinClashError",
23
+ "Catalog",
24
+ "CatalogEntry",
25
+ "Collection",
26
+ "Conflict",
27
+ "DuplicateMemberError",
28
+ "JinjaTypesError",
29
+ "Kind",
30
+ "MemberSpec",
31
+ "Namespace",
32
+ "Options",
33
+ "Param",
34
+ "Registry",
35
+ "RegistryError",
36
+ "TypesExtension",
37
+ "install",
38
+ ]
jinja_types/cli.py ADDED
@@ -0,0 +1,53 @@
1
+ """The `jinja-types` command: export the catalog and list conflict resolutions."""
2
+
3
+ import argparse
4
+ import io
5
+ import sys
6
+
7
+ from jinja_types.core import Kind, Registry
8
+
9
+
10
+ def build_parser() -> argparse.ArgumentParser:
11
+ parser = argparse.ArgumentParser(prog="jinja-types", description=__doc__)
12
+ commands = parser.add_subparsers(dest="command", required=True)
13
+
14
+ catalog = commands.add_parser("catalog", help="print the catalog of every member")
15
+ catalog.add_argument("--namespace", help="only this namespace ('helpers' for plain names)")
16
+ catalog.add_argument("--kind", choices=[str(kind.name).lower() for kind in Kind])
17
+ catalog.add_argument("--format", choices=["json", "markdown"], default="json")
18
+
19
+ conflicts = commands.add_parser("conflicts", help="print every conflict resolution")
20
+
21
+ for command in (catalog, conflicts):
22
+ command.add_argument(
23
+ "--plugins", action="store_true", help="also load 'jinja_types.plugins' entry points"
24
+ )
25
+
26
+ return parser
27
+
28
+
29
+ def main(argv: list[str] | None = None) -> int:
30
+ """Run the `jinja-types` command."""
31
+
32
+ args = build_parser().parse_args(argv)
33
+ registry = Registry.default(plugins=args.plugins)
34
+
35
+ if isinstance(sys.stdout, io.TextIOWrapper):
36
+ sys.stdout.reconfigure(encoding="utf-8") # Windows consoles default to a legacy codepage
37
+
38
+ if args.command == "conflicts":
39
+ for conflict in registry.conflicts():
40
+ print(f"{conflict.name}\t{conflict.resolution}\t{conflict.detail}")
41
+
42
+ return 0
43
+
44
+ catalog = registry.catalog().select(namespace=args.namespace, kind=args.kind)
45
+
46
+ if not catalog:
47
+ print("jinja-types: no members match the filters", file=sys.stderr)
48
+
49
+ return 1
50
+
51
+ print(catalog.to_json() if args.format == "json" else catalog.to_markdown())
52
+
53
+ return 0
@@ -0,0 +1 @@
1
+ """Optional collections that need an extra (`[babel]`)."""
@@ -0,0 +1,245 @@
1
+ """The `babel` namespace: locale-aware number, currency and date formatting (`[babel]` extra).
2
+
3
+ The locale is the `locale` argument, else the install's `Options.locale`, else `en_US` (so a
4
+ render never depends on the machine's environment). `numbering_system="default"` uses the
5
+ locale's own separators, e.g. `٬` and `٫` for `ar_SY`; Babel keeps Latin digits either way.
6
+
7
+ `Registry.default()` includes this collection only when Babel is importable.
8
+ """
9
+
10
+ from datetime import date, datetime, time, timedelta, tzinfo
11
+ from decimal import Decimal
12
+ from typing import Literal
13
+
14
+ from jinja_types.core import CURRENT, Collection
15
+
16
+ try:
17
+ from babel import dates, numbers
18
+ except ImportError as exc: # pragma: no cover (the extra is installed in development)
19
+ raise ImportError(
20
+ "jinja_types.contrib.babel needs Babel: install 'jinja-types[babel]'"
21
+ ) from exc
22
+
23
+ collection = Collection("babel", object)
24
+
25
+ DEFAULT_LOCALE = "en_US"
26
+
27
+ type Number = Decimal | float | int
28
+ type Width = Literal["full", "long", "medium", "short"] | str
29
+
30
+ X = {"x": Decimal("1234.5")}
31
+ D = {"d": date(2026, 11, 22)}
32
+ DT = {"dt": datetime(2026, 11, 22, 14, 30)}
33
+
34
+
35
+ def locale_of(locale: str | None) -> str:
36
+ """The call's locale, else the install's, else `en_US`."""
37
+ return locale or CURRENT.get().locale or DEFAULT_LOCALE
38
+
39
+
40
+ def zone(tz: tzinfo | str | None) -> tzinfo | None:
41
+ """Turn an IANA name such as `Asia/Damascus` into a `tzinfo`."""
42
+ return dates.get_timezone(tz) if isinstance(tz, str) else tz
43
+
44
+
45
+ @collection.filter(
46
+ examples=[
47
+ ("{{ x | babel.format_decimal }}", X, "1,234.5"),
48
+ ("{{ x | babel.format_decimal(locale='de_DE') }}", X, "1.234,5"),
49
+ ("{{ x | babel.format_decimal('#,##0.00') }}", X, "1,234.50"),
50
+ (
51
+ "{{ x | babel.format_decimal(locale='ar_SY', numbering_system='default') }}",
52
+ X,
53
+ "1٬234٫5",
54
+ ),
55
+ ]
56
+ )
57
+ def format_decimal(
58
+ value: Number,
59
+ /,
60
+ format: str | None = None,
61
+ locale: str | None = None,
62
+ decimal_quantization: bool = True,
63
+ group_separator: bool = True,
64
+ *,
65
+ numbering_system: str = "latn",
66
+ ) -> str:
67
+ """Format a number for the locale, optionally with a CLDR pattern such as `#,##0.00`."""
68
+ return numbers.format_decimal(
69
+ value,
70
+ format,
71
+ locale_of(locale),
72
+ decimal_quantization,
73
+ group_separator,
74
+ numbering_system=numbering_system,
75
+ )
76
+
77
+
78
+ @collection.filter(
79
+ examples=[
80
+ ("{{ x | babel.format_currency('USD') }}", X, "$1,234.50"),
81
+ ("{{ x | babel.format_currency('USD', locale='ar_SY') }}", X, "‏1,234.50\xa0US$"),
82
+ ("{{ x | babel.format_currency('SYP', locale='ar_SY') }}", X, "‏1,234\xa0ل.س.‏"),
83
+ (
84
+ "{{ x | babel.format_currency('SYP', locale='ar_SY', currency_digits=false) }}",
85
+ X,
86
+ "‏1,234.50\xa0ل.س.‏",
87
+ ),
88
+ ("{{ x | babel.format_currency('EUR', locale='de_DE') }}", X, "1.234,50\xa0€"),
89
+ ]
90
+ )
91
+ def format_currency(
92
+ value: Number,
93
+ currency: str,
94
+ /,
95
+ format: str | None = None,
96
+ locale: str | None = None,
97
+ currency_digits: bool = True,
98
+ format_type: Literal["name", "standard", "accounting"] = "standard",
99
+ decimal_quantization: bool = True,
100
+ group_separator: bool = True,
101
+ *,
102
+ numbering_system: str = "latn",
103
+ ) -> str:
104
+ """Format an amount in `currency` (ISO 4217). `currency_digits` uses the currency's decimals."""
105
+ return numbers.format_currency(
106
+ value,
107
+ currency,
108
+ format,
109
+ locale_of(locale),
110
+ currency_digits,
111
+ format_type,
112
+ decimal_quantization,
113
+ group_separator,
114
+ numbering_system=numbering_system,
115
+ )
116
+
117
+
118
+ @collection.filter(
119
+ examples=[
120
+ ("{{ 0.256 | babel.format_percent }}", {}, "26%"),
121
+ ("{{ 0.256 | babel.format_percent('#,##0.0%') }}", {}, "25.6%"),
122
+ ]
123
+ )
124
+ def format_percent(
125
+ value: Number,
126
+ /,
127
+ format: str | None = None,
128
+ locale: str | None = None,
129
+ decimal_quantization: bool = True,
130
+ group_separator: bool = True,
131
+ *,
132
+ numbering_system: str = "latn",
133
+ ) -> str:
134
+ """Format a ratio as a percentage (`0.25` gives `25%`)."""
135
+ return numbers.format_percent(
136
+ value,
137
+ format,
138
+ locale_of(locale),
139
+ decimal_quantization,
140
+ group_separator,
141
+ numbering_system=numbering_system,
142
+ )
143
+
144
+
145
+ @collection.filter(
146
+ examples=[
147
+ ("{{ 1234567 | babel.format_compact_decimal }}", {}, "1M"),
148
+ ("{{ 1234567 | babel.format_compact_decimal(fraction_digits=1) }}", {}, "1.2M"),
149
+ ("{{ 1234567 | babel.format_compact_decimal(format_type='long') }}", {}, "1 million"),
150
+ ]
151
+ )
152
+ def format_compact_decimal(
153
+ value: Number,
154
+ /,
155
+ *,
156
+ format_type: Literal["short", "long"] = "short",
157
+ locale: str | None = None,
158
+ fraction_digits: int = 0,
159
+ numbering_system: str = "latn",
160
+ ) -> str:
161
+ """Format a number in compact form, e.g. `1.2M` or `1 million`."""
162
+ return numbers.format_compact_decimal(
163
+ value,
164
+ format_type=format_type,
165
+ locale=locale_of(locale),
166
+ fraction_digits=fraction_digits,
167
+ numbering_system=numbering_system,
168
+ )
169
+
170
+
171
+ @collection.filter(
172
+ examples=[
173
+ ("{{ d | babel.format_date }}", D, "Nov 22, 2026"),
174
+ ("{{ d | babel.format_date('dd/MM/yyyy') }}", D, "22/11/2026"),
175
+ ("{{ d | babel.format_date('full', locale='ar_SY') }}", D, "الأحد، 22 تشرين الثاني 2026"),
176
+ ]
177
+ )
178
+ def format_date(value: date, /, format: Width = "medium", locale: str | None = None) -> str:
179
+ """Format a date with a width (`short` … `full`) or a CLDR pattern such as `dd/MM/yyyy`."""
180
+ return dates.format_date(value, format, locale_of(locale))
181
+
182
+
183
+ @collection.filter(
184
+ examples=[
185
+ ("{{ dt | babel.format_datetime('short') }}", DT, "11/22/26, 2:30 PM"),
186
+ ("{{ dt | babel.format_datetime('yyyy-MM-dd HH:mm') }}", DT, "2026-11-22 14:30"),
187
+ (
188
+ "{{ dt | babel.format_datetime('HH:mm zzzz', tzinfo='Asia/Damascus') }}",
189
+ {"dt": datetime.fromisoformat("2026-11-22T12:00Z")},
190
+ "15:00 GMT+03:00",
191
+ ),
192
+ ]
193
+ )
194
+ def format_datetime(
195
+ value: datetime,
196
+ /,
197
+ format: Width = "medium",
198
+ tzinfo: tzinfo | str | None = None,
199
+ locale: str | None = None,
200
+ ) -> str:
201
+ """Format a datetime; `tzinfo` (a `tzinfo` or an IANA name) converts it first."""
202
+ return dates.format_datetime(value, format, zone(tzinfo), locale_of(locale))
203
+
204
+
205
+ @collection.filter(
206
+ examples=[
207
+ ("{{ t | babel.format_time('short') }}", {"t": time(14, 30)}, "2:30 PM"),
208
+ ("{{ t | babel.format_time('HH:mm') }}", {"t": time(14, 30)}, "14:30"),
209
+ ]
210
+ )
211
+ def format_time(
212
+ value: time | datetime,
213
+ /,
214
+ format: Width = "medium",
215
+ tzinfo: tzinfo | str | None = None,
216
+ locale: str | None = None,
217
+ ) -> str:
218
+ """Format a time (or the time of a datetime)."""
219
+ return dates.format_time(value, format, zone(tzinfo), locale_of(locale))
220
+
221
+
222
+ @collection.filter(
223
+ examples=[
224
+ ("{{ x | babel.format_timedelta }}", {"x": timedelta(hours=3)}, "3 hours"),
225
+ ("{{ x | babel.format_timedelta(locale='ar_SY') }}", {"x": timedelta(days=2)}, "يومان"),
226
+ (
227
+ "{{ x | babel.format_timedelta(add_direction=true, format='short') }}",
228
+ {"x": timedelta(minutes=-5)},
229
+ "5 min. ago",
230
+ ),
231
+ ]
232
+ )
233
+ def format_timedelta(
234
+ value: timedelta,
235
+ /,
236
+ granularity: Literal["year", "month", "week", "day", "hour", "minute", "second"] = "second",
237
+ threshold: float = 0.85,
238
+ add_direction: bool = False,
239
+ format: Literal["narrow", "short", "medium", "long"] = "long",
240
+ locale: str | None = None,
241
+ ) -> str:
242
+ """Format a duration in words, rounded to its largest unit (`3 hours`)."""
243
+ return dates.format_timedelta(
244
+ value, granularity, threshold, add_direction, format, locale_of(locale)
245
+ )
@@ -0,0 +1,36 @@
1
+ """The registry core: specs, collections, the registry, the invoker and the catalog."""
2
+
3
+ from .catalog import Catalog, CatalogEntry
4
+ from .collection import Collection, build_spec, type_repr
5
+ from .errors import BuiltinClashError, DuplicateMemberError, JinjaTypesError, RegistryError
6
+ from .invoker import Invoker
7
+ from .namespace import Namespace
8
+ from .options import CURRENT, Options, OptionsKwargs
9
+ from .plugins import PLUGIN_GROUP, load_plugins
10
+ from .registry import Conflict, Registry
11
+ from .spec import Example, Kind, MemberSpec, Param
12
+
13
+ __all__ = [
14
+ "CURRENT",
15
+ "PLUGIN_GROUP",
16
+ "BuiltinClashError",
17
+ "Catalog",
18
+ "CatalogEntry",
19
+ "Collection",
20
+ "Conflict",
21
+ "DuplicateMemberError",
22
+ "Example",
23
+ "Invoker",
24
+ "JinjaTypesError",
25
+ "Kind",
26
+ "MemberSpec",
27
+ "Namespace",
28
+ "Options",
29
+ "OptionsKwargs",
30
+ "Param",
31
+ "Registry",
32
+ "RegistryError",
33
+ "build_spec",
34
+ "load_plugins",
35
+ "type_repr",
36
+ ]
@@ -0,0 +1,175 @@
1
+ """The catalog: a serializable view of every spec, for docs and autocomplete."""
2
+
3
+ import builtins
4
+ import dataclasses
5
+ import json
6
+ from collections.abc import Iterable, Iterator
7
+ from dataclasses import dataclass
8
+ from typing import Self
9
+
10
+ from .spec import Example, Kind, MemberSpec, Param
11
+
12
+
13
+ @dataclass(frozen=True, slots=True)
14
+ class CatalogEntry:
15
+ """One member as tooling sees it (no callables)."""
16
+
17
+ name: str
18
+ kinds: tuple[str, ...]
19
+ namespace: str | None
20
+ input_type: str | None
21
+ params: tuple[Param, ...]
22
+ returns: str
23
+ doc: str
24
+ examples: tuple[Example, ...]
25
+ source: str
26
+ replaced: bool
27
+ constant: bool
28
+ classmethod: bool
29
+
30
+ @builtins.classmethod # the `classmethod` field shadows the name here
31
+ def from_spec(cls, spec: MemberSpec) -> Self:
32
+ return cls(
33
+ name=spec.name,
34
+ kinds=tuple(str(kind.name).lower() for kind in Kind if kind in spec.kinds),
35
+ namespace=spec.namespace.name,
36
+ input_type=spec.input_type,
37
+ params=spec.params,
38
+ returns=spec.returns,
39
+ doc=spec.doc,
40
+ examples=spec.examples,
41
+ source=spec.source,
42
+ replaced=spec.replaced,
43
+ constant=spec.constant,
44
+ classmethod=spec.classmethod,
45
+ )
46
+
47
+
48
+ @dataclass(frozen=True, slots=True)
49
+ class Catalog:
50
+ """All catalog entries, sorted by name."""
51
+
52
+ entries: tuple[CatalogEntry, ...]
53
+
54
+ @classmethod
55
+ def from_specs(cls, specs: Iterable[MemberSpec]) -> Self:
56
+ return cls(tuple(CatalogEntry.from_spec(spec) for spec in specs))
57
+
58
+ def __iter__(self) -> Iterator[CatalogEntry]:
59
+ return iter(self.entries)
60
+
61
+ def __len__(self) -> int:
62
+ return len(self.entries)
63
+
64
+ def to_dict(self) -> dict[str, object]:
65
+ """Plain data. Example context values are kept as they are (not deep-copied)."""
66
+
67
+ entries = [
68
+ {field.name: getattr(entry, field.name) for field in dataclasses.fields(entry)}
69
+ | {
70
+ "params": [dataclasses.asdict(param) for param in entry.params],
71
+ "examples": [
72
+ [template, dict(context), out] for template, context, out in entry.examples
73
+ ],
74
+ }
75
+ for entry in self.entries
76
+ ]
77
+
78
+ return {"entries": entries}
79
+
80
+ def to_json(self, *, indent: int | None = 2) -> str:
81
+ """Export as JSON. Non-JSON example context values are written as `repr()`."""
82
+ return json.dumps(self.to_dict(), indent=indent, default=repr, ensure_ascii=False)
83
+
84
+ def namespaces(self) -> list[str]:
85
+ """Return the namespace labels in use, sorted (`helpers` for plain names)."""
86
+ return sorted({label(entry) for entry in self.entries})
87
+
88
+ def select(self, *, namespace: str | None = None, kind: str | None = None) -> Self:
89
+ """Keep the entries in `namespace` (a label, see `namespaces`) and with `kind`."""
90
+
91
+ return type(self)(
92
+ tuple(
93
+ entry
94
+ for entry in self.entries
95
+ if namespace in (None, label(entry)) and kind in (None, *entry.kinds)
96
+ )
97
+ )
98
+
99
+ def to_markdown(self) -> str:
100
+ """Export as Markdown: one `#` section per namespace, one `##` section per member."""
101
+
102
+ lines: list[str] = []
103
+
104
+ for namespace in self.namespaces():
105
+ lines += [f"# `{namespace}`", ""]
106
+
107
+ for entry in self.select(namespace=namespace):
108
+ lines += entry_markdown(entry)
109
+
110
+ return "\n".join(lines)
111
+
112
+
113
+ def label(entry: CatalogEntry) -> str:
114
+ """The namespace label: the namespace name, or `helpers` for plain names."""
115
+ return entry.namespace or "helpers"
116
+
117
+
118
+ def signature(entry: CatalogEntry) -> str:
119
+ """Return a Python-style signature, e.g. `str.zfill(value: str, /, width: int) -> str`."""
120
+
121
+ parts = [] if entry.input_type is None else [f"value: {entry.input_type}"]
122
+ positional_only = entry.input_type is not None
123
+ starred = False
124
+
125
+ for param in entry.params:
126
+ if positional_only and param.kind != "positional_only":
127
+ parts.append("/")
128
+ positional_only = False
129
+
130
+ if param.kind == "keyword_only" and not starred:
131
+ parts.append("*")
132
+
133
+ prefix = {"var_positional": "*", "var_keyword": "**"}.get(param.kind, "")
134
+ default = "" if param.default is None else f" = {param.default}"
135
+ starred = starred or param.kind in ("var_positional", "keyword_only")
136
+
137
+ parts.append(f"{prefix}{param.name}: {param.annotation}{default}")
138
+
139
+ if positional_only:
140
+ parts.append("/")
141
+
142
+ return f"{entry.name}({', '.join(parts)}) -> {entry.returns}"
143
+
144
+
145
+ def short_repr(value: object, limit: int = 80) -> str:
146
+ """`repr(value)`, or `TypeName(...)` when that is longer than `limit`."""
147
+
148
+ text = repr(value)
149
+
150
+ return text if len(text) <= limit else f"{type(value).__name__}(...)"
151
+
152
+
153
+ def entry_markdown(entry: CatalogEntry) -> list[str]:
154
+ """Return the Markdown lines for one member."""
155
+
156
+ tags = [*entry.kinds]
157
+
158
+ if entry.classmethod:
159
+ tags.append("classmethod")
160
+
161
+ if entry.source != "jinja_types":
162
+ tags.append(f"from {entry.source}" + (" (replaced)" if entry.replaced else ""))
163
+
164
+ lines = [f"## `{entry.name}`", "", f"`{signature(entry)}`", "", f"*{', '.join(tags)}*", ""]
165
+
166
+ if entry.doc:
167
+ lines += [entry.doc, ""]
168
+
169
+ for template, context, output in entry.examples:
170
+ given = ", ".join(f"`{key} = {short_repr(value)}`" for key, value in context.items())
171
+ suffix = f" with {given}" if given else ""
172
+
173
+ lines.append(f"- ``{template}``{suffix} → ``{output}``")
174
+
175
+ return [*lines, ""]