Skip to content

Commit d0d8d46

Browse files
Make default terminator regex a lazily-computed cached function
Agent-Logs-Url: https://github.com/executablebooks/markdown-it-py/sessions/04e84ce1-b921-4475-9f26-c0b296e29e33 Co-authored-by: chrisjsewell <2997570+chrisjsewell@users.noreply.github.com>
1 parent 6100aeb commit d0d8d46

1 file changed

Lines changed: 10 additions & 6 deletions

File tree

markdown_it/parser_inline.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from __future__ import annotations
44

5+
import functools
56
import re
67
from collections.abc import Callable
78
from typing import TYPE_CHECKING
@@ -48,11 +49,14 @@
4849
}
4950
)
5051

51-
# Pre-compiled regex for the default terminator set. Shared across all ParserInline
52-
# instances that have not had extra chars added, so __init__ pays no allocation cost.
53-
_default_terminator_re: re.Pattern[str] = re.compile(
54-
"[" + re.escape("".join(_DEFAULT_TERMINATORS)) + "]"
55-
)
52+
# Lazily compiled regex for the default terminator set. The @cache ensures it is
53+
# compiled at most once (on first ParserInline instantiation) and shared across all
54+
# instances that have not added extra chars, keeping __init__ cost near zero.
55+
@functools.cache
56+
def _default_terminator_re() -> re.Pattern[str]:
57+
return re.compile(
58+
"[" + re.escape("".join(_DEFAULT_TERMINATORS)) + "]"
59+
)
5660

5761

5862
# Parser rules
@@ -106,7 +110,7 @@ def __init__(self) -> None:
106110
# with a char outside the defaults, keeping __init__ allocation-free.
107111
self._extra_terminator_chars: set[str] = set()
108112
# Pre-compiled regex shared with all default instances (no copy in the common path).
109-
self.terminator_re: re.Pattern[str] = _default_terminator_re
113+
self.terminator_re: re.Pattern[str] = _default_terminator_re()
110114

111115
def add_terminator_char(self, ch: str) -> None:
112116
"""Register a character that stops the ``text`` rule, allowing inline rules to fire.

0 commit comments

Comments
 (0)