From 1a13967bfcc59efffa2c22a7056d6bb3476f1346 Mon Sep 17 00:00:00 2001 From: Victor Stinner Date: Thu, 5 Jul 2018 03:07:14 +0200 Subject: [PATCH] WIP: Use assign expr for match/group Replace: m = regex.match(text) if m: return m.group(1) with: if (m := regex.match(text)): return m.group(1) Notes: * Similar code using "if not m: return" is unchanged * When the condition was more complex than "if m", the code is left unchanged --- Lib/_markupbase.py | 3 +-- Lib/_osx_support.py | 3 +-- Lib/configparser.py | 6 ++---- Lib/dataclasses.py | 3 +-- Lib/imaplib.py | 7 ++++--- Lib/inspect.py | 3 +-- Lib/keyword.py | 3 +-- Lib/nntplib.py | 6 ++---- Lib/smtplib.py | 3 +-- Lib/string.py | 3 +-- Lib/sysconfig.py | 15 +++++---------- Lib/tarfile.py | 3 +-- Lib/token.py | 12 +++++------- 13 files changed, 26 insertions(+), 44 deletions(-) diff --git a/Lib/_markupbase.py b/Lib/_markupbase.py index 2af5f1c23b6066..17d62da9913584 100644 --- a/Lib/_markupbase.py +++ b/Lib/_markupbase.py @@ -378,8 +378,7 @@ def _scan_name(self, i, declstartpos): n = len(rawdata) if i == n: return None, -1 - m = _declname_match(rawdata, i) - if m: + if (m := _declname_match(rawdata, i)): s = m.group() name = s.strip() if (i + len(s)) == n: diff --git a/Lib/_osx_support.py b/Lib/_osx_support.py index e37852e2536c33..655288e95a4138 100644 --- a/Lib/_osx_support.py +++ b/Lib/_osx_support.py @@ -287,8 +287,7 @@ def _check_for_unavailable_sdk(_config_vars): # to /usr and /System/Library by either a standalone CLT # package or the CLT component within Xcode. cflags = _config_vars.get('CFLAGS', '') - m = re.search(r'-isysroot\s+(\S+)', cflags) - if m is not None: + if (m := re.search(r'-isysroot\s+(\S+)', cflags)) is not None: sdk = m.group(1) if not os.path.exists(sdk): for cv in _UNIVERSAL_CONFIG_VARS: diff --git a/Lib/configparser.py b/Lib/configparser.py index 4a16101c7a3ab6..657fcf8e511cea 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -1059,8 +1059,7 @@ def _read(self, fp, fpname): else: indent_level = cur_indent_level # is it a section header? - mo = self.SECTCRE.match(value) - if mo: + if (mo := self.SECTCRE.match(value)): sectname = mo.group('header') if sectname in self._sections: if self._strict and sectname in elements_added: @@ -1082,8 +1081,7 @@ def _read(self, fp, fpname): raise MissingSectionHeaderError(fpname, lineno, line) # an option line? else: - mo = self._optcre.match(value) - if mo: + if (mo := self._optcre.match(value)): optname, vi, optval = mo.group('option', 'vi', 'value') if not optname: e = self._handle_error(e, fpname, lineno, line) diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index ad7bf0f7593a13..2c59fc7e319414 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -599,8 +599,7 @@ def _is_type(annotation, cls, a_module, a_type, is_type_predicate): # a eval() penalty for every single field of every dataclass # that's defined. It was judged not worth it. - match = _MODULE_IDENTIFIER_RE.match(annotation) - if match: + if (match := _MODULE_IDENTIFIER_RE.match(annotation)): ns = None module_name = match.group(1) if not module_name: diff --git a/Lib/imaplib.py b/Lib/imaplib.py index e1cece0b283f2b..3545aad777ff3b 100644 --- a/Lib/imaplib.py +++ b/Lib/imaplib.py @@ -1579,9 +1579,10 @@ def run(cmd, args): run(cmd, args) for ml in run('list', ('/tmp/', 'yy%')): - mo = re.match(r'.*"([^"]+)"$', ml) - if mo: path = mo.group(1) - else: path = ml.split()[-1] + if (mo := re.match(r'.*"([^"]+)"$', ml)): + path = mo.group(1) + else: + path = ml.split()[-1] run('delete', (path,)) for cmd,args in test_seq2: diff --git a/Lib/inspect.py b/Lib/inspect.py index 717518614fc6d7..61248fa4085fae 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -796,8 +796,7 @@ def findsource(object): # that's most probably not inside a function definition. candidates = [] for i in range(len(lines)): - match = pat.match(lines[i]) - if match: + if (match := pat.match(lines[i])): # if it's at toplevel, it's already the best one if lines[i][0] == 'c': return lines, i diff --git a/Lib/keyword.py b/Lib/keyword.py index 431991dcf4ace6..855e961d41536f 100755 --- a/Lib/keyword.py +++ b/Lib/keyword.py @@ -74,8 +74,7 @@ def main(): lines = [] for line in fp: if '{1, "' in line: - match = strprog.search(line) - if match: + if (match := strprog.search(line)): lines.append(" '" + match.group(1) + "'," + nl) lines.sort() diff --git a/Lib/nntplib.py b/Lib/nntplib.py index 5961a28ab7d9bc..d154217f107260 100644 --- a/Lib/nntplib.py +++ b/Lib/nntplib.py @@ -619,8 +619,7 @@ def _getdescriptions(self, group_pattern, return_all): resp, lines = self._longcmdstring('XGTITLE ' + group_pattern) groups = {} for raw_line in lines: - match = line_pat.search(raw_line.strip()) - if match: + if (match := line_pat.search(raw_line.strip())): name, desc = match.group(1, 2) if not return_all: return desc @@ -845,8 +844,7 @@ def xgtitle(self, group, *, file=None): resp, raw_lines = self._longcmdstring('XGTITLE ' + group, file) lines = [] for raw_line in raw_lines: - match = line_pat.search(raw_line.strip()) - if match: + if (match := line_pat.search(raw_line.strip())): lines.append(match.group(1, 2)) return resp, lines diff --git a/Lib/smtplib.py b/Lib/smtplib.py index b679875fd2c539..33eec84b3c7db1 100755 --- a/Lib/smtplib.py +++ b/Lib/smtplib.py @@ -471,8 +471,7 @@ def ehlo(self, name=''): # It's actually stricter, in that only spaces are allowed between # parameters, but were not going to check for that here. Note # that the space isn't present if there are no parameters. - m = re.match(r'(?P[A-Za-z0-9][A-Za-z0-9\-]*) ?', each) - if m: + if (m := re.match(r'(?P[A-Za-z0-9][A-Za-z0-9\-]*) ?', each)): feature = m.group("feature").lower() params = m.string[m.end("feature"):].strip() if feature == "auth": diff --git a/Lib/string.py b/Lib/string.py index b9d6f5eb5675f6..e04574fc4c72e4 100644 --- a/Lib/string.py +++ b/Lib/string.py @@ -120,8 +120,7 @@ def substitute(*args, **kws): # Helper function for .sub() def convert(mo): # Check the most common path first. - named = mo.group('named') or mo.group('braced') - if named is not None: + if (named := mo.group('named') or mo.group('braced')) is not None: return str(mapping[named]) if mo.group('escaped') is not None: return self.delimiter diff --git a/Lib/sysconfig.py b/Lib/sysconfig.py index 9ee4d3185a7127..41818a1f842f36 100644 --- a/Lib/sysconfig.py +++ b/Lib/sysconfig.py @@ -224,8 +224,7 @@ def _parse_makefile(filename, vars=None): for line in lines: if line.startswith('#') or line.strip() == '': continue - m = _variable_rx.match(line) - if m: + if (m := _variable_rx.match(line)): n, v = m.group(1, 2) v = v.strip() # `$$' is a literal `$' in make @@ -449,18 +448,15 @@ def parse_config_h(fp, vars=None): line = fp.readline() if not line: break - m = define_rx.match(line) - if m: + if (m := define_rx.match(line)): n, v = m.group(1, 2) try: v = int(v) except ValueError: pass vars[n] = v - else: - m = undef_rx.match(line) - if m: - vars[m.group(1)] = 0 + elif (m := undef_rx.match(line)): + vars[m.group(1)] = 0 return vars @@ -659,8 +655,7 @@ def get_platform(): osname = "cygwin" import re rel_re = re.compile(r'[\d.]+') - m = rel_re.match(release) - if m: + if (m := rel_re.match(release)): release = m.group() elif osname[:6] == "darwin": import _osx_support diff --git a/Lib/tarfile.py b/Lib/tarfile.py index 59f044cc5a00dc..a00215da00fda9 100755 --- a/Lib/tarfile.py +++ b/Lib/tarfile.py @@ -1200,8 +1200,7 @@ def _proc_pax(self, tarfile): # these fields are UTF-8 encoded but since POSIX.1-2008 tar # implementations are allowed to store them as raw binary strings if # the translation to UTF-8 fails. - match = re.search(br"\d+ hdrcharset=([^\n]+)\n", buf) - if match is not None: + if (match := re.search(br"\d+ hdrcharset=([^\n]+)\n", buf)) is not None: pax_headers["hdrcharset"] = match.group(1).decode("utf-8") # For the time being, we don't care about anything other than "BINARY". diff --git a/Lib/token.py b/Lib/token.py index ba132059abf5ee..2ca6ae4f49f68d 100644 --- a/Lib/token.py +++ b/Lib/token.py @@ -115,17 +115,15 @@ def _main(): tokens = {} prev_val = None for line in lines: - match = prog.match(line) - if match: + + if (match := prog.match(line)): name, val = match.group(1, 2) val = int(val) tokens[val] = {'token': name} # reverse so we can sort them... prev_val = val - else: - comment_match = comment_regex.match(line) - if comment_match and prev_val is not None: - comment = comment_match.group(1) - tokens[prev_val]['comment'] = comment + elif (comment_match := comment_regex.match(line)) and prev_val is not None: + comment = comment_match.group(1) + tokens[prev_val]['comment'] = comment keys = sorted(tokens.keys()) # load the output skeleton from the target: try: