1"""Lazy regex compilation helper used outside of URL routing."""
2
3import re
4
5from plain.utils.functional import SimpleLazyObject
6
7
8def _lazy_re_compile(
9 regex: str | bytes | re.Pattern[str] | re.Pattern[bytes], flags: int = 0
10) -> SimpleLazyObject:
11 """Lazily compile a regex with flags."""
12
13 def _compile() -> re.Pattern[str] | re.Pattern[bytes]:
14 if isinstance(regex, str | bytes):
15 return re.compile(regex, flags)
16 else:
17 assert not flags, "flags must be empty if regex is passed pre-compiled"
18 return regex
19
20 return SimpleLazyObject(_compile)