From f0c18f62bbc8c943f22337c79462d58b468d7ced Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Tue, 29 Aug 2023 19:26:06 -0400 Subject: [PATCH] style: use walrus for regexing --- ci/parse_relnotes.py | 7 ++----- coverage/files.py | 9 +++------ lab/parser.py | 3 +-- 3 files changed, 6 insertions(+), 13 deletions(-) diff --git a/ci/parse_relnotes.py b/ci/parse_relnotes.py index df83818a6..6ba32e6f0 100644 --- a/ci/parse_relnotes.py +++ b/ci/parse_relnotes.py @@ -44,9 +44,7 @@ def parse_md(lines): buffer = TextChunkBuffer() for line in lines: - header_match = re.search(r"^(#+) (.+)$", line) - is_header = bool(header_match) - if is_header: + if header_match := re.search(r"^(#+) (.+)$", line): yield from buffer.flush() hashes, text = header_match.groups() yield (f"h{len(hashes)}", text) @@ -80,8 +78,7 @@ def sections(parsed_data): def refind(regex, text): """Find a regex in some text, and return the matched text, or None.""" - m = re.search(regex, text) - if m: + if m := re.search(regex, text): return m.group() else: return None diff --git a/coverage/files.py b/coverage/files.py index aade31afd..79c6e7bc1 100644 --- a/coverage/files.py +++ b/coverage/files.py @@ -300,8 +300,7 @@ def match(self, fpath: str) -> bool: def sep(s: str) -> str: """Find the path separator used in this string, or os.sep if none.""" - sep_match = re.search(r"[\\/]", s) - if sep_match: + if sep_match := re.search(r"[\\/]", s): the_sep = sep_match[0] else: the_sep = os.sep @@ -337,8 +336,7 @@ def _glob_to_regex(pattern: str) -> str: pos = 0 while pos < len(pattern): for rx, sub in G2RX_TOKENS: # pragma: always breaks - m = rx.match(pattern, pos=pos) - if m: + if m := rx.match(pattern, pos=pos): if sub is None: raise ConfigError(f"File pattern can't include {m[0]!r}") path_rx.append(m.expand(sub)) @@ -469,8 +467,7 @@ def map(self, path: str, exists:Callable[[str], bool] = source_exists) -> str: self.pprinted = True for original_pattern, regex, result in self.aliases: - m = regex.match(path) - if m: + if m := regex.match(path): new = path.replace(m[0], result) new = new.replace(sep(path), sep(result)) if not self.relative: diff --git a/lab/parser.py b/lab/parser.py index c7687bda6..73c414245 100644 --- a/lab/parser.py +++ b/lab/parser.py @@ -61,8 +61,7 @@ def one_file(self, options, filename): # `filename` can have a line number suffix. In that case, extract those # lines, dedent them, and use that. This is for trying test cases # embedded in the test files. - match = re.search(r"^(.*):(\d+)-(\d+)$", filename) - if match: + if match := re.search(r"^(.*):(\d+)-(\d+)$", filename): filename, start, end = match.groups() start, end = int(start), int(end) else: