Skip to content

Commit c2418c1

Browse files
committed
Move comment handling into a _CommentSpec class.
Rely on re.sub to perform the substitutions in a unified way across full and inline prefixes.
1 parent b005e50 commit c2418c1

File tree

1 file changed

+22
-19
lines changed

1 file changed

+22
-19
lines changed

Lib/configparser.py

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -574,19 +574,30 @@ def value(self):
574574
def value(self, string):
575575
self._value = string
576576
string = string.strip()
577-
self.clean = self._strip_full(string) and self._strip_inline(string)
577+
self.clean = self.comments.strip(string)
578578
self.has_comments = string != self.clean
579579

580-
def _strip_full(self, string):
581-
return '' if any(map(string.startswith, self.comments.full)) else True
582580

583-
def _strip_inline(self, string):
584-
match = None
585-
if self.comments.inline:
586-
match = self.comments.inline.search(string)
587-
if match:
588-
return string[:match.start()].rstrip()
589-
return string
581+
class _CommentSpec:
582+
def __init__(self, full_prefixes, inline_prefixes):
583+
if not full_prefixes and not inline_prefixes:
584+
# performance optimization when no prefixes (gh-128641)
585+
self.strip = lambda text: text
586+
return
587+
full_patterns = (
588+
# prefix at the beginning of a line
589+
fr'^({re.escape(prefix)}).*'
590+
for prefix in full_prefixes
591+
)
592+
inline_patterns = (
593+
# prefix at the beginning of the line or following a space
594+
fr'(^|\s)({re.escape(prefix)}.*)'
595+
for prefix in inline_prefixes
596+
)
597+
self.pattern = re.compile('|'.join(itertools.chain(full_patterns, inline_patterns)))
598+
599+
def strip(self, text):
600+
return self.pattern.sub('', text).rstrip()
590601

591602

592603
class RawConfigParser(MutableMapping):
@@ -655,15 +666,7 @@ def __init__(self, defaults=None, dict_type=_default_dict,
655666
else:
656667
self._optcre = re.compile(self._OPT_TMPL.format(delim=d),
657668
re.VERBOSE)
658-
# prefix at the beginning of the line or following a space
659-
inline_tmpl = lambda prefix: fr'(^|\s)({re.escape(prefix)})'
660-
inline_comm = '|'.join(map(inline_tmpl, inline_comment_prefixes or ()))
661-
# optional cre used with _LineParser for best performance (gh-128641)
662-
inline_comment_cre = re.compile(inline_comm) if inline_comm else None
663-
self._comments = types.SimpleNamespace(
664-
inline=inline_comment_cre,
665-
full=tuple(comment_prefixes or ())
666-
)
669+
self._comments = _CommentSpec(comment_prefixes or (), inline_comment_prefixes or ())
667670
self._strict = strict
668671
self._allow_no_value = allow_no_value
669672
self._empty_lines_in_values = empty_lines_in_values

0 commit comments

Comments
 (0)