File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 22
33from __future__ import annotations
44
5+ import functools
56import re
67from collections .abc import Callable
78from typing import TYPE_CHECKING
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.
You can’t perform that action at this time.
0 commit comments