From 7a92475a346d1add5b01e5b405da12b247c61fe9 Mon Sep 17 00:00:00 2001 From: Mason Lyons Date: Sun, 18 Oct 2026 11:21:46 +0000 Subject: [PATCH] Faster |localtime / |timezone output and native humanize |ordinal - The tz filters (`localtime`, `utc`, `timezone`) return `django.templatetags.tz.datetimeobject`, a bare datetime subclass whose only addition is the `convert_to_local_time` instance attribute. The native datetime paths (`template_localtime`, `dateformat.format`, `render_value_in_context`) only accepted an exact datetime, so every filtered value fell back to Python's dateformat. They now accept the stock `datetimeobject` too, found via `sys.modules` and used only while its class body is still empty. `convert_to_local_time` is honoured like stock. - `ordinal` translated all ten suffix templates on every call (9 gettext calls per value). The native port translates only the template it needs, through `Translator::pgettext`, and formats natively when the translation is a plain `{}` template. Non-int inputs and patched `pgettext`/`mark_safe` globals take the Python function. gaps microbench (20-row loop): |localtime 1.05x -> 5.2x, |timezone 1.07x -> 9.8x, |ordinal 1.07x -> 24x faster than stock. Co-Authored-By: Claude Opus 5.5 --- src/filters/dates.rs | 11 +++-- src/filters/humanize.rs | 95 ++++++++++++++++++++++++++++++++++++ src/filters/mod.rs | 69 ++++++++++++++++++++++++--- src/render/value.rs | 8 ++-- tests/test_realpage.py | 103 ++++++++++++++++++++++++++++++++++++++++ 5 files changed, 272 insertions(+), 14 deletions(-) diff --git a/src/filters/dates.rs b/src/filters/dates.rs index 6ad32b7..5ab0986 100644 --- a/src/filters/dates.rs +++ b/src/filters/dates.rs @@ -514,8 +514,9 @@ fn try_native( fmt: &str, date_only_ok: bool, ) -> PyResult> { - // Exact datetime.datetime only (cast would also accept subclasses). - if value.get_type().as_ptr() != py.get_type::().as_ptr() { + // Exact datetime.datetime or stock `tz.datetimeobject` only (cast + // would also accept arbitrary subclasses). + if !crate::filters::is_stock_datetime(value) { return Ok(None); } let dt = value.cast::()?; @@ -543,8 +544,8 @@ fn try_native( run_program(py, fmt, &fields) } -/// `dateformat.format(value, fmt)` for an EXACT `datetime.datetime` or -/// `datetime.date` (`localize`'s `date_format` step); `Ok(None)` → stock +/// `dateformat.format(value, fmt)` for an EXACT `datetime.datetime` (or +/// stock `tz.datetimeobject`) or `datetime.date` (`localize`'s `date_format` step); `Ok(None)` → stock /// Python path (timezone/isoformat specifiers, time specifiers on a plain /// date, other types). pub(crate) fn format_exact( @@ -552,7 +553,7 @@ pub(crate) fn format_exact( value: &Bound<'_, PyAny>, fmt: &str, ) -> PyResult> { - if value.get_type().as_ptr() == py.get_type::().as_ptr() { + if crate::filters::is_stock_datetime(value) { return try_native(py, value, fmt, true); } if value.get_type().as_ptr() != py.get_type::().as_ptr() { diff --git a/src/filters/humanize.rs b/src/filters/humanize.rs index bb34ca0..9acfede 100644 --- a/src/filters/humanize.rs +++ b/src/filters/humanize.rs @@ -472,3 +472,98 @@ fn timesince<'py>( let sep = tr.gettext(", ")?; sep.call_method1(pyo3::intern!(py, "join"), (parts,)) } + +/// The stock Python `ordinal` (fallback for everything but plain ints). +fn py_ordinal(py: Python<'_>) -> PyResult<&Bound<'_, PyAny>> { + static F: PyOnceLock> = PyOnceLock::new(); + Ok(F.get_or_try_init(py, || -> PyResult> { + Ok(py + .import("django.contrib.humanize.templatetags.humanize")? + .getattr("ordinal")? + .unbind()) + })? + .bind(py)) +} + +/// `True` while the humanize module's `pgettext` / `mark_safe` globals are +/// the stock functions (`ordinal` resolves both at call time). +fn ordinal_globals_stock(py: Python<'_>) -> PyResult { + static G: PyOnceLock<(Py, Py, Py)> = PyOnceLock::new(); + let (globals, pgettext, mark_safe) = G.get_or_try_init(py, || -> PyResult<_> { + Ok(( + py.import("django.contrib.humanize.templatetags.humanize")? + .dict() + .unbind(), + py.import("django.utils.translation")?.getattr("pgettext")?.unbind(), + py.import("django.utils.safestring")?.getattr("mark_safe")?.unbind(), + )) + })?; + let globals = globals.bind(py); + let same = |name: &str, f: &Py| -> PyResult { + Ok(globals.get_item(name)?.is_some_and(|g| g.is(f.bind(py)))) + }; + Ok(same("pgettext", pgettext)? && same("mark_safe", mark_safe)?) +} + +/// `(context, msgid)` of the one ordinal template stock picks for `n >= 0` +/// (it translates all ten `n % 10` templates, then indexes one: the other +/// nine lookups have no visible effect). +fn ordinal_msg(n: i64) -> (&'static str, &'static str) { + const BY_LAST: [(&str, &str); 10] = [ + ("ordinal 0", "{}th"), + ("ordinal 1", "{}st"), + ("ordinal 2", "{}nd"), + ("ordinal 3", "{}rd"), + ("ordinal 4", "{}th"), + ("ordinal 5", "{}th"), + ("ordinal 6", "{}th"), + ("ordinal 7", "{}th"), + ("ordinal 8", "{}th"), + ("ordinal 9", "{}th"), + ]; + if n == 1 { + ("ordinal is 1", "{}st") + } else if matches!(n % 100, 11..=13) { + ("ordinal 11, 12, 13", "{}th") + } else { + #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)] // 0..=9 + BY_LAST[(n % 10) as usize] + } +} + +/// `ordinal(value)` for an exact `int` that fits `i64` (`int(value)` is +/// the identity): negatives → plain `str(value)`, else the selected +/// template translated through `Translator::pgettext`, `.format(value)` +/// (natively when the translation holds exactly one `{}` and no other +/// brace), then `mark_safe`. Other inputs or patched module globals take +/// the Python function. +pub(crate) fn ordinal<'py>( + _rc: &mut Rctx<'py>, + input: &Bound<'py, PyAny>, + args: &[Bound<'py, PyAny>], + _ae: Option, +) -> PyResult> { + let py = input.py(); + if args.is_empty() && input.is_exact_instance_of::() { + if let Ok(n) = input.extract::() { + if n < 0 { + return Ok(PyString::new(py, &n.to_string()).into_any()); + } + if ordinal_globals_stock(py)? { + let (context, msgid) = ordinal_msg(n); + let tmpl = super::Translator::new(py).pgettext(context, msgid)?; + let formatted = match tmpl.cast_exact::().ok().and_then(|s| { + let s = s.to_str().ok()?; + let (pre, post) = s.split_once("{}")?; + let plain = |p: &str| !p.contains(['{', '}']); + (plain(pre) && plain(post)).then(|| format!("{pre}{n}{post}")) + }) { + Some(s) => PyString::new(py, &s).into_any(), + None => tmpl.call_method1(pyo3::intern!(py, "format"), (input,))?, + }; + return crate::render::value::mark_safe_bound(&formatted); + } + } + } + py_ordinal(py)?.call1((input,).into_pyobject(py)?.add_args(args)?) +} diff --git a/src/filters/mod.rs b/src/filters/mod.rs index 82feb9d..93f6798 100644 --- a/src/filters/mod.rs +++ b/src/filters/mod.rs @@ -156,6 +156,7 @@ fn humanize_native(func: &Bound<'_, PyAny>) -> Option { match qualname.as_str() { "intcomma" => Some(humanize::intcomma), "naturaltime" => Some(humanize::naturaltime), + "ordinal" => Some(humanize::ordinal), _ => None, } } @@ -684,13 +685,63 @@ pub(crate) fn local_value<'py>( .ok() } +/// `django.templatetags.tz.datetimeobject`: the bare `datetime` subclass +/// the `localtime`/`utc`/`timezone` filters return (its only addition is +/// the `convert_to_local_time` instance attribute). Looked up in +/// `sys.modules` rather than imported (no instance can exist before the +/// module loads) and cached once found, only if the class body is empty +/// at that point (a class patched by then keeps the Python path). +fn tz_datetimeobject(py: Python<'_>) -> Option<&Bound<'_, pyo3::types::PyType>> { + static TY: PyOnceLock> = PyOnceLock::new(); + if let Some(t) = TY.get(py) { + return Some(t.bind(py)); + } + let modules = py.import("sys").ok()?.getattr("modules").ok()?; + let tz = modules.get_item("django.templatetags.tz").ok()?; + let ty = tz.getattr("datetimeobject").ok()?.cast_into::().ok()?; + let plain = ty.getattr("__dict__").ok()?.try_iter().ok()?.all(|k| { + k.ok().and_then(|k| k.extract::().ok()).is_some_and(|k| { + matches!( + k.as_str(), + "__module__" + | "__qualname__" + | "__doc__" + | "__dict__" + | "__weakref__" + | "__firstlineno__" + | "__static_attributes__" + ) + }) + }); + if !plain || ty.getattr("__bases__").ok()?.len().ok()? != 1 { + return None; + } + let _ = TY.set(py, ty.unbind()); + TY.get(py).map(|t| t.bind(py)) +} + +/// `True` for an exact `datetime.datetime` or a stock `tz.datetimeobject` +/// — the types the native datetime paths treat alike (same C layout, no +/// overridden methods). +pub(crate) fn is_stock_datetime(value: &Bound<'_, PyAny>) -> bool { + use pyo3::types::PyDateTime; + let py = value.py(); + let ty = value.get_type(); + if ty.as_ptr() == py.get_type::().as_ptr() { + return true; + } + value.is_instance_of::() && tz_datetimeobject(py).is_some_and(|t| ty.is(t)) +} + /// Native `django.utils.timezone.template_localtime(value, use_tz)` for an -/// EXACT `datetime.datetime`; `Ok(None)` means "call the Python function" -/// (other types, or state that can't be read natively). +/// exact `datetime.datetime` or a stock `tz.datetimeobject`; `Ok(None)` +/// means "call the Python function" (other types, or state that can't be +/// read natively). /// -/// Stock: convert iff `use_tz` (or `settings.USE_TZ` when None) and -/// `value.utcoffset() is not None` (an exact datetime has no -/// `convert_to_local_time` attribute), via `value.astimezone(tz)` with +/// Stock: convert iff `use_tz` (or `settings.USE_TZ` when None), +/// `value.utcoffset() is not None` and +/// `getattr(value, "convert_to_local_time", True)` (absent on an exact +/// datetime), via `value.astimezone(tz)` with /// `tz = getattr(_active, "value", get_default_timezone())`. The active /// zone is read from `timezone._active`'s contextvar (~0.2 µs) instead of /// the asgiref `Local.__getattr__` chain (~5 µs). @@ -700,7 +751,7 @@ pub(crate) fn template_localtime_exact<'py>( ) -> PyResult>> { use pyo3::types::{PyDateTime, PyTzInfoAccess}; let py = value.py(); - if value.get_type().as_ptr() != py.get_type::().as_ptr() { + if !is_stock_datetime(value) { return Ok(None); } let dt = value.cast::()?; @@ -718,6 +769,12 @@ pub(crate) fn template_localtime_exact<'py>( if !use_tz || value.call_method0(pyo3::intern!(py, "utcoffset"))?.is_none() { return Ok(Some(value.clone())); } + if value.get_type().as_ptr() != py.get_type::().as_ptr() { + match value.getattr_opt(pyo3::intern!(py, "convert_to_local_time"))? { + Some(c) if !c.is_truthy()? => return Ok(Some(value.clone())), + _ => {} + } + } let Some(tz) = current_timezone(py)? else { return Ok(None); }; diff --git a/src/render/value.rs b/src/render/value.rs index 8b7ae21..c5c190f 100644 --- a/src/render/value.rs +++ b/src/render/value.rs @@ -1358,7 +1358,7 @@ fn finish(rctx: &Rctx<'_>, s: String) -> PyResult { /// and without `decimal_pos`: `str(value)` with the locale /// `DECIMAL_SEPARATOR` substituted (`str(value)` when `use_l10n` is /// False). Exponent notation, non-finite or huge `Decimal`s keep Python; -/// - exact `datetime` / `date`: `template_localtime` is the identity for +/// - exact `datetime` (or stock `tz.datetimeobject`) / `date`: `template_localtime` is the identity for /// naive values (aware ones take the real call), then `date_format` with /// `DATETIME_FORMAT` / `DATE_FORMAT` through the native dateformat port; /// - any other object whose class is none of `str`/`int`/`float`/ @@ -1431,13 +1431,15 @@ fn native_render<'py>( } return finish(rctx, out).map(Native::Done); } - let is_dt = ty.is(vt.datetime.bind(py)); + // Stock `tz.datetimeobject` (the `localtime`/`timezone` filters' + // result) renders exactly like a datetime. + let is_dt = ty.is(vt.datetime.bind(py)) || crate::filters::is_stock_datetime(value); if is_dt || ty.is(vt.date.bind(py)) { let mut v = value.clone(); if is_dt && !value.cast::()?.get_tzinfo().is_none() { // Possibly aware: `template_localtime` decides. v = template_localtime(rctx, value.clone())?; - if !v.get_type().is(vt.datetime.bind(py)) { + if !crate::filters::is_stock_datetime(&v) { return Ok(Native::Localtimed(v)); } } diff --git a/tests/test_realpage.py b/tests/test_realpage.py index d04040d..1e5d180 100644 --- a/tests/test_realpage.py +++ b/tests/test_realpage.py @@ -27,6 +27,8 @@ "i18n": "django.templatetags.i18n", "humanize": "django.contrib.humanize.templatetags.humanize", "static": "django.templatetags.static", + "tz": "django.templatetags.tz", + "l10n": "django.templatetags.l10n", } ENGINES = {"stock": StockEngine(libraries=LIBS), "rust": RustEngine(libraries=LIBS)} LANGS = [None, "de", "fr", "es", "ja"] @@ -478,3 +480,104 @@ def test_static(src, static_url, installed): # `STATIC_URL` is read when the storage is set up. staticfiles_storage._wrapped = empty assert_parity("{% load static %}" + src, ctx) + + +def tz_filter_values(): + from django.templatetags.tz import datetimeobject + + aware = datetime.datetime(2024, 3, 10, 7, 30, 15, 123456, tzinfo=datetime.timezone.utc) + forced = datetimeobject(2024, 7, 1, 23, 5, tzinfo=datetime.timezone.utc) + forced.convert_to_local_time = True + flagged = datetimeobject(2024, 7, 1, 23, 5, tzinfo=datetime.timezone.utc) + flagged.convert_to_local_time = 0 + return [ + aware, + aware.astimezone(zoneinfo.ZoneInfo("Asia/Kolkata")), + datetime.datetime(2024, 11, 3, 1, 30), # naive, DST fold in Chicago + datetime.date(2024, 1, 2), + # Constructed directly: no instance flag (converts), set True, falsy. + datetimeobject(2024, 7, 1, 23, 5, tzinfo=datetime.timezone.utc), + datetimeobject(2024, 7, 1, 23, 5), + forced, + flagged, + "2024-01-01", + None, + ] + + +TZ_FILTER_CASES = { + "localtime": "{{ v|localtime }}", + "utc": "{{ v|utc }}", + "timezone-name": "{{ v|timezone:'Europe/Paris' }}", + "timezone-obj": "{{ v|timezone:tz }}", + "timezone-bad": "[{{ v|timezone:'Nowhere/Nope' }}]", + "localtime-off": "{% localtime off %}{{ v }}|{{ v|localtime }}{% endlocaltime %}", + "date": "{{ v|timezone:'Asia/Tokyo'|date:'Y-m-d H:i:s.u e O T U c r' }}", + "date-default": "{{ v|localtime|date }}|{{ v|utc|time }}|{{ v|utc|time:'H:i e' }}", + "plain": "{{ v }}", + "l10n-off": "{% localize off %}{{ v|utc }}{% endlocalize %}", + "autoescape-off": "{% autoescape off %}{{ v|localtime }}{% endautoescape %}", +} + + +@pytest.mark.parametrize("use_tz", [True, False]) +@pytest.mark.parametrize("lang", [None, "de", "ja"]) +@pytest.mark.parametrize("src", TZ_FILTER_CASES.values(), ids=TZ_FILTER_CASES.keys()) +def test_tz_filters(src, lang, use_tz): + """`localtime`/`utc`/`timezone` return a `tz.datetimeobject`, which the + native datetime paths treat like an exact datetime.""" + engines_libs = "{% load tz l10n %}" + ctx_tz = zoneinfo.ZoneInfo("Australia/Adelaide") + with override_settings(USE_TZ=use_tz): + for v in tz_filter_values(): + for active in (None, "Pacific/Auckland"): + assert_parity(engines_libs + src, {"v": v, "tz": ctx_tz}, lang=lang, tz=active) + + +def test_tz_datetimeobject_subclass_stays_python(): + """A further subclass of `datetimeobject` isn't the stock type.""" + from django.templatetags.tz import datetimeobject + + class Odd(datetimeobject): + def __str__(self): + return "odd" + + v = Odd(2024, 7, 1, 23, 5, tzinfo=datetime.timezone.utc) + assert_parity("{% load tz %}{{ v }}|{{ v|date:'c' }}|{{ v|localtime }}", {"v": v}, lang="de") + + +ORDINAL_VALUES = [ + *range(0, 30), 100, 101, 102, 103, 104, 111, 112, 113, 114, 121, 1011, 2**62, 2**63, 10**30, + -1, -11, -(2**63), True, False, "3", "x", 3.7, Decimal("12"), None, [], +] + + +@pytest.mark.parametrize("lang", [None, "de", "fr", "es", "ja", "nl", "ar"]) +def test_ordinal(lang): + src = ( + "{% load humanize %}{% for v in vals %}[{{ v|ordinal }}|{{ v|ordinal|length }}" + "|{% autoescape off %}{{ v|ordinal }}{% endautoescape %}]{% endfor %}" + ) + assert_parity(src, {"vals": ORDINAL_VALUES}, lang=lang) + + +def test_ordinal_i18n_off(): + with override_settings(USE_I18N=False): + src = "{% load humanize %}{% for v in vals %}[{{ v|ordinal }}]{% endfor %}" + assert_parity(src, {"vals": ORDINAL_VALUES}, lang="de") + + +@pytest.mark.parametrize("tmpl", ["<{}>", "{}{{x}}", "{0}.", "no placeholder", "{}-{}"]) +def test_ordinal_patched_globals(tmpl): + """Patched `pgettext` (any template shape) / `mark_safe` keep stock output.""" + from django.contrib.humanize.templatetags import humanize + + src = "{% load humanize %}{% for v in vals %}[{{ v|ordinal }}]{% endfor %}" + orig_pg, orig_ms = humanize.pgettext, humanize.mark_safe + humanize.pgettext = lambda ctx, msg: tmpl + try: + assert_parity(src, {"vals": [1, 2, 11, 23]}, lang="de") + humanize.mark_safe = str + assert_parity(src, {"vals": [1, 2, 11, 23]}, lang="de") + finally: + humanize.pgettext, humanize.mark_safe = orig_pg, orig_ms