#37082: Improved readability and minor performance of sanitize_strftime_format
regex substitution
-------------------------------------+-------------------------------------
Reporter: xMintTea | Type:
| Cleanup/optimization
Status: new | Component: Core
| (Other)
Version: 6.0 | Severity: Normal
Keywords: | Triage Stage:
sanitize_strftime_format, regex, | Unreviewed
readability, performance |
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
The current implementation of `sanitize_strftime_format` uses an inline
lambda with indexed groups (`r"%s%%0%s%s" % (m[1], mapping[m[2]], m[2])`)
and a compact regular expression. While correct, it is not immediately
obvious what the replacement does and why the groups are referenced by
index.
This patch replaces the lambda with a small helper function
`_replace_specifier`, uses a named group `(?P<letter>...)` in the regex,
enables `re.VERBOSE` for readability, and switches to an f-string for
clarity.
**No behavioral changes** – the early exit condition and the mapping
dictionary remain identical. Equivalence was verified on Windows by
mocking the early exit and comparing outputs for a comprehensive set of
format strings, including edge cases with escaped percent signs (`%%`).
The regex match results were also confirmed to be the same.
Additionally, the use of an f-string and named group yields a ~12-13%
performance improvement over the old `%`-formatting with `m[1]`/`m[2]`
access (measured with timeit on 240,000 calls).
--
Ticket URL: <https://code.djangoproject.com/ticket/37082>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion visit
https://groups.google.com/d/msgid/django-updates/0107019de872bed4-5bf74117-3e59-43da-9a17-c144bc5f8e79-000000%40eu-central-1.amazonses.com.