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