Skip to content

Commit ad58ad5

Browse files
committed
perf: Pre-compile patterns for docstring style detection
1 parent 1671e59 commit ad58ad5

1 file changed

Lines changed: 14 additions & 7 deletions

File tree

  • packages/griffelib/src/griffe/_internal/docstrings

‎packages/griffelib/src/griffe/_internal/docstrings/auto.py‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
"""The supported methods to infer docstring styles."""
4545

4646

47-
_patterns = {
47+
_pattern_templates = {
4848
Parser.google: (
4949
r"\n[ \t]*{0}:([ \t]+.+)?\n[ \t]+.+",
5050
[
@@ -122,6 +122,14 @@
122122
),
123123
}
124124

125+
_patterns = {
126+
style: re.compile(
127+
pattern.format(f"(?:{'|'.join(map(re.escape, replacements))})"),
128+
re.IGNORECASE | re.MULTILINE,
129+
)
130+
for style, (pattern, replacements) in _pattern_templates.items()
131+
}
132+
125133

126134
class PerStyleOptions(TypedDict, total=False):
127135
"""Per-style options for docstring parsing."""
@@ -168,15 +176,14 @@ def infer_docstring_style(
168176

169177
per_style_options = per_style_options or {}
170178

171-
style_order = [Parser(style) if isinstance(style, str) else style for style in style_order or _default_style_order]
179+
if not style_order:
180+
style_order = _default_style_order
181+
else:
182+
style_order = [Parser(style) if isinstance(style, str) else style for style in style_order]
172183

173184
if method == "heuristics":
174185
for style in style_order:
175-
pattern, replacements = _patterns[style]
176-
patterns = [
177-
re.compile(pattern.format(replacement), re.IGNORECASE | re.MULTILINE) for replacement in replacements
178-
]
179-
if any(pattern.search(docstring.value) for pattern in patterns):
186+
if _patterns[style].search(docstring.value):
180187
return style, None
181188
return default if default is None or isinstance(default, Parser) else Parser(default), None
182189

0 commit comments

Comments
 (0)