From a4998b264544496870dcc3adb9dc34b6122d9184 Mon Sep 17 00:00:00 2001 From: Sourcery AI Date: Wed, 19 May 2021 20:56:42 +0000 Subject: [PATCH] 'Refactored by Sourcery' --- Doc/includes/minidom-example.py | 5 +- Doc/includes/mp_pool.py | 3 +- Doc/includes/mp_workers.py | 8 +- Doc/includes/sqlite3/row_factory.py | 5 +- Doc/includes/tzinfo_examples.py | 7 +- Doc/tools/extensions/c_annotations.py | 4 +- Doc/tools/extensions/suspicious.py | 14 +--- Lib/_collections_abc.py | 22 ++--- Lib/_compat_pickle.py | 4 +- Lib/_dummy_thread.py | 19 ++--- Lib/_markupbase.py | 11 ++- Lib/_osx_support.py | 24 +++--- Lib/_pydecimal.py | 92 ++++++--------------- Lib/_pyio.py | 39 ++++----- Lib/_strptime.py | 10 +-- Lib/aifc.py | 44 +++++----- Lib/argparse.py | 72 ++++++++-------- Lib/asynchat.py | 4 +- Lib/asyncore.py | 43 ++++------ Lib/base64.py | 12 +-- Lib/bdb.py | 50 +++-------- Lib/binhex.py | 13 ++- Lib/calendar.py | 23 ++---- Lib/cgi.py | 79 ++++++++---------- Lib/chunk.py | 8 +- Lib/cmd.py | 43 ++++------ Lib/code.py | 7 +- Lib/codecs.py | 33 +++----- Lib/colorsys.py | 25 ++---- Lib/compileall.py | 45 ++++------ Lib/configparser.py | 26 +++--- Lib/contextlib.py | 8 +- Lib/copy.py | 24 ++---- Lib/csv.py | 42 +++++----- Lib/dataclasses.py | 60 ++++++++------ Lib/datetime.py | 58 +++++-------- Lib/difflib.py | 32 ++----- Lib/dis.py | 38 ++++----- Lib/doctest.py | 95 ++++++++------------- Lib/enum.py | 69 +++++++--------- Lib/filecmp.py | 2 +- Lib/fileinput.py | 11 ++- Lib/fnmatch.py | 16 ++-- Lib/formatter.py | 25 ++---- Lib/fractions.py | 46 +++++------ Lib/ftplib.py | 17 ++-- Lib/functools.py | 5 +- Lib/getopt.py | 11 +-- Lib/getpass.py | 4 +- Lib/gettext.py | 34 ++------ Lib/gzip.py | 5 +- Lib/imaplib.py | 99 +++++++++------------- Lib/imp.py | 35 ++++---- Lib/inspect.py | 74 +++++++---------- Lib/ipaddress.py | 29 ++----- Lib/keyword.py | 4 +- Lib/linecache.py | 13 +-- Lib/locale.py | 8 +- Lib/macpath.py | 16 ++-- Lib/mailbox.py | 107 ++++++++++-------------- Lib/mailcap.py | 9 +- Lib/mimetypes.py | 5 +- Lib/modulefinder.py | 23 ++---- Lib/netrc.py | 11 ++- Lib/nntplib.py | 27 ++---- Lib/ntpath.py | 16 ++-- Lib/nturl2path.py | 4 +- Lib/operator.py | 16 ++-- Lib/optparse.py | 77 ++++++++--------- Lib/pathlib.py | 115 +++++++++++--------------- Lib/pdb.py | 99 ++++++++++------------ setup.py | 17 ++-- 72 files changed, 857 insertions(+), 1343 deletions(-) diff --git a/Doc/includes/minidom-example.py b/Doc/includes/minidom-example.py index 5ee7682c1927124..e7f0ad05a8090b1 100644 --- a/Doc/includes/minidom-example.py +++ b/Doc/includes/minidom-example.py @@ -19,10 +19,7 @@ dom = xml.dom.minidom.parseString(document) def getText(nodelist): - rc = [] - for node in nodelist: - if node.nodeType == node.TEXT_NODE: - rc.append(node.data) + rc = [node.data for node in nodelist if node.nodeType == node.TEXT_NODE] return ''.join(rc) def handleSlideshow(slideshow): diff --git a/Doc/includes/mp_pool.py b/Doc/includes/mp_pool.py index 11101e1a90954e8..5ce42e7054a220c 100644 --- a/Doc/includes/mp_pool.py +++ b/Doc/includes/mp_pool.py @@ -106,8 +106,7 @@ def test(): try: x = next(it) except ZeroDivisionError: - if i == 5: - pass + pass except StopIteration: break else: diff --git a/Doc/includes/mp_workers.py b/Doc/includes/mp_workers.py index 3b92269f897e932..043f5fd6c8bcccd 100644 --- a/Doc/includes/mp_workers.py +++ b/Doc/includes/mp_workers.py @@ -51,12 +51,12 @@ def test(): task_queue.put(task) # Start worker processes - for i in range(NUMBER_OF_PROCESSES): + for _ in range(NUMBER_OF_PROCESSES): Process(target=worker, args=(task_queue, done_queue)).start() # Get and print results print('Unordered results:') - for i in range(len(TASKS1)): + for item in TASKS1: print('\t', done_queue.get()) # Add more tasks using `put()` @@ -64,11 +64,11 @@ def test(): task_queue.put(task) # Get and print some more results - for i in range(len(TASKS2)): + for _ in TASKS2: print('\t', done_queue.get()) # Tell child processes to stop - for i in range(NUMBER_OF_PROCESSES): + for _ in range(NUMBER_OF_PROCESSES): task_queue.put('STOP') diff --git a/Doc/includes/sqlite3/row_factory.py b/Doc/includes/sqlite3/row_factory.py index e436ffc6c80225f..850579ae8161388 100644 --- a/Doc/includes/sqlite3/row_factory.py +++ b/Doc/includes/sqlite3/row_factory.py @@ -1,10 +1,7 @@ import sqlite3 def dict_factory(cursor, row): - d = {} - for idx, col in enumerate(cursor.description): - d[col[0]] = row[idx] - return d + return {col[0]: row[idx] for idx, col in enumerate(cursor.description)} con = sqlite3.connect(":memory:") con.row_factory = dict_factory diff --git a/Doc/includes/tzinfo_examples.py b/Doc/includes/tzinfo_examples.py index 9b9e32a553e7d8e..848d094a1f23ad9 100644 --- a/Doc/includes/tzinfo_examples.py +++ b/Doc/includes/tzinfo_examples.py @@ -11,10 +11,7 @@ import time as _time STDOFFSET = timedelta(seconds = -_time.timezone) -if _time.daylight: - DSTOFFSET = timedelta(seconds = -_time.altzone) -else: - DSTOFFSET = STDOFFSET +DSTOFFSET = timedelta(seconds=-_time.altzone) if _time.daylight else STDOFFSET DSTDIFF = DSTOFFSET - STDOFFSET @@ -93,7 +90,7 @@ def first_sunday_on_or_after(dt): def us_dst_range(year): # Find start and end times for US DST. For years before 1967, return # start = end for no DST. - if 2006 < year: + if year > 2006: dststart, dstend = DSTSTART_2007, DSTEND_2007 elif 1986 < year < 2007: dststart, dstend = DSTSTART_1987_2006, DSTEND_1987_2006 diff --git a/Doc/tools/extensions/c_annotations.py b/Doc/tools/extensions/c_annotations.py index baa39f3b44646ad..8ecd47533dd17b0 100644 --- a/Doc/tools/extensions/c_annotations.py +++ b/Doc/tools/extensions/c_annotations.py @@ -85,9 +85,7 @@ def add_annotations(self, app, doctree): if name.startswith("c."): name = name[2:] entry = self.get(name) - if not entry: - continue - elif entry.result_type not in ("PyObject*", "PyVarObject*"): + if not entry or entry.result_type not in ("PyObject*", "PyVarObject*"): continue if entry.result_refs is None: rc = 'Return value: Always NULL.' diff --git a/Doc/tools/extensions/suspicious.py b/Doc/tools/extensions/suspicious.py index 0a70e57d2b044f0..7b2e498335cc6e3 100644 --- a/Doc/tools/extensions/suspicious.py +++ b/Doc/tools/extensions/suspicious.py @@ -165,7 +165,6 @@ def write_log_entry(self, lineno, issue, text): f = open(self.log_file_name, 'a') writer = csv.writer(f, dialect) writer.writerow([self.docname, lineno, issue, text.strip()]) - f.close() else: f = open(self.log_file_name, 'ab') writer = csv.writer(f, dialect) @@ -173,7 +172,8 @@ def write_log_entry(self, lineno, issue, text): lineno, issue.encode('utf-8'), text.strip().encode('utf-8')]) - f.close() + + f.close() def load_rules(self, filename): """Load database of previously ignored issues. @@ -184,10 +184,7 @@ def load_rules(self, filename): self.info("loading ignore rules... ", nonl=1) self.rules = rules = [] try: - if py3: - f = open(filename, 'r') - else: - f = open(filename, 'rb') + f = open(filename, 'r') if py3 else open(filename, 'rb') except IOError: return for i, row in enumerate(csv.reader(f)): @@ -195,10 +192,7 @@ def load_rules(self, filename): raise ValueError( "wrong format in %s, line %d: %s" % (filename, i+1, row)) docname, lineno, issue, text = row - if lineno: - lineno = int(lineno) - else: - lineno = None + lineno = int(lineno) if lineno else None if not py3: docname = docname.decode('utf-8') issue = issue.decode('utf-8') diff --git a/Lib/_collections_abc.py b/Lib/_collections_abc.py index dbe30dff1fe190a..361abc4f67c435d 100644 --- a/Lib/_collections_abc.py +++ b/Lib/_collections_abc.py @@ -432,10 +432,7 @@ def __le__(self, other): return NotImplemented if len(self) > len(other): return False - for elem in self: - if elem not in other: - return False - return True + return all(elem in other for elem in self) def __lt__(self, other): if not isinstance(other, Set): @@ -452,10 +449,7 @@ def __ge__(self, other): return NotImplemented if len(self) < len(other): return False - for elem in other: - if elem not in self: - return False - return True + return all(elem in self for elem in other) def __eq__(self, other): if not isinstance(other, Set): @@ -480,10 +474,7 @@ def __and__(self, other): def isdisjoint(self, other): 'Return True if two sets have a null intersection.' - for value in other: - if value in self: - return False - return True + return all(value not in self for value in other) def __or__(self, other): if not isinstance(other, Iterable): @@ -887,10 +878,7 @@ def __iter__(self): return def __contains__(self, value): - for v in self: - if v is value or v == value: - return True - return False + return any(v is value or v == value for v in self) def __reversed__(self): for i in reversed(range(len(self))): @@ -921,7 +909,7 @@ def index(self, value, start=0, stop=None): def count(self, value): 'S.count(value) -> integer -- return number of occurrences of value' - return sum(1 for v in self if v is value or v == value) + return sum(v is value or v == value for v in self) Sequence.register(tuple) Sequence.register(str) diff --git a/Lib/_compat_pickle.py b/Lib/_compat_pickle.py index f68496ae639f5f8..74550c6da69960b 100644 --- a/Lib/_compat_pickle.py +++ b/Lib/_compat_pickle.py @@ -162,9 +162,9 @@ NAME_MAPPING[("multiprocessing", excname)] = ("multiprocessing.context", excname) # Same, but for 3.x to 2.x -REVERSE_IMPORT_MAPPING = dict((v, k) for (k, v) in IMPORT_MAPPING.items()) +REVERSE_IMPORT_MAPPING = {v: k for (k, v) in IMPORT_MAPPING.items()} assert len(REVERSE_IMPORT_MAPPING) == len(IMPORT_MAPPING) -REVERSE_NAME_MAPPING = dict((v, k) for (k, v) in NAME_MAPPING.items()) +REVERSE_NAME_MAPPING = {v: k for (k, v) in NAME_MAPPING.items()} assert len(REVERSE_NAME_MAPPING) == len(NAME_MAPPING) # Non-mutual mappings. diff --git a/Lib/_dummy_thread.py b/Lib/_dummy_thread.py index a2cae54b0580db3..57fcae3b98cb2e7 100644 --- a/Lib/_dummy_thread.py +++ b/Lib/_dummy_thread.py @@ -110,18 +110,14 @@ def acquire(self, waitflag=None, timeout=-1): aren't triggered and throw a little fit. """ - if waitflag is None or waitflag: + if not self.locked_status or waitflag is None or waitflag: self.locked_status = True return True else: - if not self.locked_status: - self.locked_status = True - return True - else: - if timeout > 0: - import time - time.sleep(timeout) - return False + if timeout > 0: + import time + time.sleep(timeout) + return False __enter__ = acquire @@ -158,6 +154,5 @@ def interrupt_main(): KeyboardInterrupt upon exiting.""" if _main: raise KeyboardInterrupt - else: - global _interrupt - _interrupt = True + global _interrupt + _interrupt = True diff --git a/Lib/_markupbase.py b/Lib/_markupbase.py index 2af5f1c23b60662..4b1d575b3803dfd 100644 --- a/Lib/_markupbase.py +++ b/Lib/_markupbase.py @@ -230,13 +230,12 @@ def _parse_doctype_subset(self, i, declstartpos): j = j + 1 while j < n and rawdata[j].isspace(): j = j + 1 - if j < n: - if rawdata[j] == ">": - return j - self.updatepos(declstartpos, j) - self.error("unexpected char after internal subset") - else: + if j >= n: return -1 + if rawdata[j] == ">": + return j + self.updatepos(declstartpos, j) + self.error("unexpected char after internal subset") elif c.isspace(): j = j + 1 else: diff --git a/Lib/_osx_support.py b/Lib/_osx_support.py index e37852e2536c339..b4a0cf77e75d591 100644 --- a/Lib/_osx_support.py +++ b/Lib/_osx_support.py @@ -41,16 +41,16 @@ def _find_executable(executable, path=None): if (sys.platform == 'win32') and (ext != '.exe'): executable = executable + '.exe' - if not os.path.isfile(executable): - for p in paths: - f = os.path.join(p, executable) - if os.path.isfile(f): - # the file exists, we have a shot at spawn working - return f - return None - else: + if os.path.isfile(executable): return executable + for p in paths: + f = os.path.join(p, executable) + if os.path.isfile(f): + # the file exists, we have a shot at spawn working + return f + return None + def _read_output(commandstring): """Output from successful command execution or None""" @@ -334,7 +334,7 @@ def compiler_fixup(compiler_so, cc_args): if 'ARCHFLAGS' in os.environ and not stripArch: # User specified different -arch flags in the environ, # see also distutils.sysconfig - compiler_so = compiler_so + os.environ['ARCHFLAGS'].split() + compiler_so += os.environ['ARCHFLAGS'].split() if stripSysroot: while True: @@ -494,9 +494,5 @@ def get_platform_osx(_config_vars, osname, release, machine): elif machine in ('PowerPC', 'Power_Macintosh'): # Pick a sane name for the PPC architecture. # See 'i386' case - if sys.maxsize >= 2**32: - machine = 'ppc64' - else: - machine = 'ppc' - + machine = 'ppc64' if sys.maxsize >= 2**32 else 'ppc' return (osname, release, machine) diff --git a/Lib/_pydecimal.py b/Lib/_pydecimal.py index 359690003fe1605..d082da9b829da36 100644 --- a/Lib/_pydecimal.py +++ b/Lib/_pydecimal.py @@ -550,10 +550,7 @@ def __new__(cls, value="0", context=None): return context._raise_error(ConversionSyntax, "Invalid literal for Decimal: %r" % value) - if m.group('sign') == "-": - self._sign = 1 - else: - self._sign = 0 + self._sign = 1 if m.group('sign') == "-" else 0 intpart = m.group('int') if intpart is not None: # finite number @@ -567,10 +564,7 @@ def __new__(cls, value="0", context=None): if diag is not None: # NaN self._int = str(int(diag or '0')).lstrip('0') - if m.group('signal'): - self._exp = 'N' - else: - self._exp = 'n' + self._exp = 'N' if m.group('signal') else 'n' else: # infinity self._int = '0' @@ -580,10 +574,7 @@ def __new__(cls, value="0", context=None): # From an integer if isinstance(value, int): - if value >= 0: - self._sign = 0 - else: - self._sign = 1 + self._sign = 0 if value >= 0 else 1 self._exp = 0 self._int = str(abs(value)) self._is_special = False @@ -694,10 +685,7 @@ def from_float(cls, f): elif isinstance(f, float): if _math.isinf(f) or _math.isnan(f): return cls(repr(f)) - if _math.copysign(1.0, f) == 1.0: - sign = 0 - else: - sign = 1 + sign = 0 if _math.copysign(1.0, f) == 1.0 else 1 n, d = abs(f).as_integer_ratio() k = d.bit_length() - 1 coeff = str(n*5**k) @@ -749,11 +737,7 @@ def _check_nans(self, other=None, context=None): """ self_is_nan = self._isnan() - if other is None: - other_is_nan = False - else: - other_is_nan = other._isnan() - + other_is_nan = False if other is None else other._isnan() if self_is_nan or other_is_nan: if context is None: context = getcontext() @@ -1226,11 +1210,7 @@ def __add__(self, other, context=None): result.sign = 0 # Now, op1 > abs(op2) > 0 - if op2.sign == 0: - result.int = op1.int + op2.int - else: - result.int = op1.int - op2.int - + result.int = op1.int + op2.int if op2.sign == 0 else op1.int - op2.int result.exp = op1.exp ans = Decimal(result) ans = ans._fix(context) @@ -1383,11 +1363,7 @@ def _divide(self, other, context): infinite and that other is nonzero. """ sign = self._sign ^ other._sign - if other._isinfinity(): - ideal_exp = self._exp - else: - ideal_exp = min(self._exp, other._exp) - + ideal_exp = self._exp if other._isinfinity() else min(self._exp, other._exp) expdiff = self.adjusted() - other.adjusted() if not self or other._isinfinity() or expdiff <= -2: return (_dec_from_triple(sign, '0', 0), @@ -1433,21 +1409,19 @@ def __divmod__(self, other, context=None): sign = self._sign ^ other._sign if self._isinfinity(): - if other._isinfinity(): - ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') - return ans, ans - else: + if not other._isinfinity(): return (_SignedInfinity[sign], context._raise_error(InvalidOperation, 'INF % x')) + ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)') + return ans, ans if not other: - if not self: - ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') - return ans, ans - else: + if self: return (context._raise_error(DivisionByZero, 'x // 0', sign), context._raise_error(InvalidOperation, 'x % 0')) + ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)') + return ans, ans quotient, remainder = self._divide(other, context) remainder = remainder._fix(context) return quotient, remainder @@ -1679,12 +1653,11 @@ def _fix(self, context): if not self: exp_max = [context.Emax, Etop][context.clamp] new_exp = min(max(self._exp, Etiny), exp_max) - if new_exp != self._exp: - context._raise_error(Clamped) - return _dec_from_triple(self._sign, '0', new_exp) - else: + if new_exp == self._exp: return Decimal(self) + context._raise_error(Clamped) + return _dec_from_triple(self._sign, '0', new_exp) # exp_min is the smallest allowable exponent of the result, # equal to max(self.adjusted()-context.prec+1, Etiny) exp_min = len(self._int) + self._exp - context.prec @@ -2025,11 +1998,7 @@ def _power_modulo(self, other, modulo, context=None): '0**0 is not defined') # compute sign of result - if other._iseven(): - sign = 0 - else: - sign = self._sign - + sign = 0 if other._iseven() else self._sign # convert modulo to a Python integer, and self and other to # Decimal integers (i.e. force their exponents to be >= 0) modulo = abs(int(modulo)) @@ -2038,7 +2007,7 @@ def _power_modulo(self, other, modulo, context=None): # compute result using integer pow() base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo - for i in range(exponent.exp): + for _ in range(exponent.exp): base = pow(base, 10, modulo) base = pow(base, exponent.int, modulo) @@ -2254,7 +2223,7 @@ def _power_exact(self, other, p): break else: a = (a*(n-1) + q)//n - if not (a == q and r == 0): + if a != q or r != 0: return None xc = a @@ -2844,11 +2813,7 @@ def max(self, other, context=None): # the result. This is exactly the ordering used in compare_total. c = self.compare_total(other) - if c == -1: - ans = other - else: - ans = self - + ans = other if c == -1 else self return ans._fix(context) def min(self, other, context=None): @@ -2878,11 +2843,7 @@ def min(self, other, context=None): if c == 0: c = self.compare_total(other) - if c == -1: - ans = self - else: - ans = other - + ans = self if c == -1 else other return ans._fix(context) def _isinteger(self): @@ -3355,10 +3316,7 @@ def _islogical(self): """ if self._sign != 0 or self._exp != 0: return False - for dig in self._int: - if dig not in '01': - return False - return True + return all(dig in '01' for dig in self._int) def _fill_logical(self, context, opa, opb): dif = context.prec - len(opa) @@ -3387,7 +3345,7 @@ def logical_and(self, other, context=None): (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes - result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)]) + result = "".join(str(int(a)&int(b)) for a,b in zip(opa,opb)) return _dec_from_triple(0, result.lstrip('0') or '0', 0) def logical_invert(self, context=None): @@ -3411,7 +3369,7 @@ def logical_or(self, other, context=None): (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes - result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)]) + result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb)) return _dec_from_triple(0, result.lstrip('0') or '0', 0) def logical_xor(self, other, context=None): @@ -3428,7 +3386,7 @@ def logical_xor(self, other, context=None): (opa, opb) = self._fill_logical(context, self._int, other._int) # make the operation, and clean starting zeroes - result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)]) + result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb)) return _dec_from_triple(0, result.lstrip('0') or '0', 0) def max_mag(self, other, context=None): diff --git a/Lib/_pyio.py b/Lib/_pyio.py index f0d4f4ed27a2434..55bf1377277c255 100644 --- a/Lib/_pyio.py +++ b/Lib/_pyio.py @@ -230,10 +230,8 @@ def open(file, mode="r", buffering=-1, encoding=None, errors=None, buffer = BufferedRandom(raw, buffering) elif creating or writing or appending: buffer = BufferedWriter(raw, buffering) - elif reading: - buffer = BufferedReader(raw, buffering) else: - raise ValueError("unknown mode: %r" % mode) + buffer = BufferedReader(raw, buffering) result = buffer if binary: return result @@ -693,10 +691,7 @@ def _readinto(self, b, read1): b = memoryview(b) b = b.cast('B') - if read1: - data = self.read1(len(b)) - else: - data = self.read(len(b)) + data = self.read1(len(b)) if read1 else self.read(len(b)) n = len(data) b[:n] = data @@ -1509,8 +1504,7 @@ def __init__(self, file, mode='r', closefd=True, opener=None): raise OSError('Negative file descriptor') owned_fd = fd if not noinherit_flag: - os.set_inheritable(fd, False) - + os.set_inheritable(owned_fd, False) self._closefd = closefd fdfstat = os.fstat(fd) try: @@ -1944,14 +1938,14 @@ def __init__(self, buffer, encoding=None, errors=None, newline=None, encoding = os.device_encoding(buffer.fileno()) except (AttributeError, UnsupportedOperation): pass - if encoding is None: - try: - import locale - except ImportError: - # Importing locale may fail if Python is being built - encoding = "ascii" - else: - encoding = locale.getpreferredencoding(False) + if encoding is None: + try: + import locale + except ImportError: + # Importing locale may fail if Python is being built + encoding = "ascii" + else: + encoding = locale.getpreferredencoding(False) if not isinstance(encoding, str): raise ValueError("invalid encoding: %r" % encoding) @@ -2070,10 +2064,7 @@ def reconfigure(self, *, "after the first read") if errors is None: - if encoding is None: - errors = self._errors - else: - errors = 'strict' + errors = self._errors if encoding is None else 'strict' elif not isinstance(errors, str): raise TypeError("invalid errors: %r" % errors) @@ -2306,7 +2297,7 @@ def tell(self): else: # We're too far ahead, skip back a bit skip_bytes -= skip_back - skip_back = skip_back * 2 + skip_back *= 2 else: skip_bytes = 0 decoder.setstate((b'', dec_flags)) @@ -2457,7 +2448,6 @@ def read(self, size=None): decoder.decode(self.buffer.read(), final=True)) self._set_decoded_chars('') self._snapshot = None - return result else: # Keep reading chunks until we have size characters to return. eof = False @@ -2465,7 +2455,8 @@ def read(self, size=None): while len(result) < size and not eof: eof = not self._read_chunk() result += self._get_decoded_chars(size - len(result)) - return result + + return result def __next__(self): self._telling = False diff --git a/Lib/_strptime.py b/Lib/_strptime.py index f4f3c0b80c1d05b..6cc8e84365ace57 100644 --- a/Lib/_strptime.py +++ b/Lib/_strptime.py @@ -176,10 +176,7 @@ def __init__(self, locale_time=None): Order of execution is important for dependency reasons. """ - if locale_time: - self.locale_time = locale_time - else: - self.locale_time = LocaleTime() + self.locale_time = locale_time or LocaleTime() base = super() base.__init__({ # The " \d" part of the regex is to make %c from ANSI C work @@ -285,9 +282,8 @@ def _calc_julian_from_U_or_W(year, week_of_year, day_of_week, week_starts_Mon): week_0_length = (7 - first_weekday) % 7 if week_of_year == 0: return 1 + day_of_week - first_weekday - else: - days_to_week = week_0_length + (7 * (week_of_year - 1)) - return 1 + days_to_week + day_of_week + days_to_week = week_0_length + (7 * (week_of_year - 1)) + return 1 + days_to_week + day_of_week def _calc_julian_from_V(iso_year, iso_week, iso_weekday): diff --git a/Lib/aifc.py b/Lib/aifc.py index 1916e7ef8e7eab8..050febbd4dc45cb 100644 --- a/Lib/aifc.py +++ b/Lib/aifc.py @@ -171,10 +171,7 @@ def _read_ushort(file): def _read_string(file): length = ord(file.read(1)) - if length == 0: - data = b'' - else: - data = file.read(length) + data = b'' if length == 0 else file.read(length) if length & 1 == 0: dummy = file.read(1) return data @@ -485,7 +482,7 @@ def _read_comm_chunk(self, chunk): if kludge: length = ord(chunk.file.read(1)) if length & 1 == 0: - length = length + 1 + length += 1 chunk.chunksize = chunk.chunksize + length chunk.file.seek(-1, 1) #DEBUG end @@ -509,7 +506,7 @@ def _readmark(self, chunk): # Some files appear to contain invalid counts. # Cope with this by testing for EOF. try: - for i in range(nmarkers): + for _ in range(nmarkers): id = _read_short(chunk) pos = _read_long(chunk) name = _read_string(chunk) @@ -779,20 +776,22 @@ def _lin2adpcm(self, data): return data def _ensure_header_written(self, datasize): - if not self._nframeswritten: - if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): - if not self._sampwidth: - self._sampwidth = 2 - if self._sampwidth != 2: - raise Error('sample width must be 2 when compressing ' - 'with ulaw/ULAW, alaw/ALAW or G7.22 (ADPCM)') - if not self._nchannels: - raise Error('# channels not specified') + if self._nframeswritten: + return + + if self._comptype in (b'ULAW', b'ulaw', b'ALAW', b'alaw', b'G722'): if not self._sampwidth: - raise Error('sample width not specified') - if not self._framerate: - raise Error('sampling rate not specified') - self._write_header(datasize) + self._sampwidth = 2 + if self._sampwidth != 2: + raise Error('sample width must be 2 when compressing ' + 'with ulaw/ULAW, alaw/ALAW or G7.22 (ADPCM)') + if not self._nchannels: + raise Error('# channels not specified') + if not self._sampwidth: + raise Error('sample width not specified') + if not self._framerate: + raise Error('sampling rate not specified') + self._write_header(datasize) def _init_compression(self): if self._comptype == b'G722': @@ -897,7 +896,7 @@ def _writemarkers(self): id, pos, name = marker length = length + len(name) + 1 + 6 if len(name) & 1 == 0: - length = length + 1 + length += 1 _write_ulong(self._file, length) self._marklength = length + 8 _write_short(self._file, len(self._markers)) @@ -909,10 +908,7 @@ def _writemarkers(self): def open(f, mode=None): if mode is None: - if hasattr(f, 'mode'): - mode = f.mode - else: - mode = 'rb' + mode = f.mode if hasattr(f, 'mode') else 'rb' if mode in ('r', 'rb'): return Aifc_read(f) elif mode in ('w', 'wb'): diff --git a/Lib/argparse.py b/Lib/argparse.py index a0307492476259c..8a3ccae87ca42cc 100644 --- a/Lib/argparse.py +++ b/Lib/argparse.py @@ -113,10 +113,8 @@ class _AttributeHolder(object): def __repr__(self): type_name = type(self).__name__ - arg_strings = [] star_args = {} - for arg in self._get_args(): - arg_strings.append(repr(arg)) + arg_strings = [repr(arg) for arg in self._get_args()] for name, value in self._get_kwargs(): if name.isidentifier(): arg_strings.append('%s=%r' % (name, value)) @@ -265,7 +263,7 @@ def add_argument(self, action): invocations.append(get_invocation(subaction)) # update the maximum item length - invocation_length = max([len(s) for s in invocations]) + invocation_length = max(len(s) for s in invocations) action_length = invocation_length + self._current_indent self._action_max_length = max(self._action_max_length, action_length) @@ -288,9 +286,8 @@ def format_help(self): return help def _join_parts(self, part_strings): - return ''.join([part - for part in part_strings - if part and part is not SUPPRESS]) + return ''.join(part for part in part_strings + if part and part is not SUPPRESS) def _format_usage(self, usage, actions, groups, prefix): if prefix is None: @@ -343,10 +340,7 @@ def _format_usage(self, usage, actions, groups, prefix): def get_lines(parts, indent, prefix=None): lines = [] line = [] - if prefix is not None: - line_len = len(prefix) - 1 - else: - line_len = len(indent) - 1 + line_len = len(prefix) - 1 if prefix is not None else len(indent) - 1 for part in parts: if line_len + 1 + len(part) > text_width and line: lines.append(indent + ' '.join(line)) @@ -582,23 +576,22 @@ def format(tuple_size): def _format_args(self, action, default_metavar): get_metavar = self._metavar_formatter(action, default_metavar) if action.nargs is None: - result = '%s' % get_metavar(1) + return '%s' % get_metavar(1) elif action.nargs == OPTIONAL: - result = '[%s]' % get_metavar(1) + return '[%s]' % get_metavar(1) elif action.nargs == ZERO_OR_MORE: - result = '[%s [%s ...]]' % get_metavar(2) + return '[%s [%s ...]]' % get_metavar(2) elif action.nargs == ONE_OR_MORE: - result = '%s [%s ...]' % get_metavar(2) + return '%s [%s ...]' % get_metavar(2) elif action.nargs == REMAINDER: - result = '...' + return '...' elif action.nargs == PARSER: - result = '%s ...' % get_metavar(1) + return '%s ...' % get_metavar(1) elif action.nargs == SUPPRESS: - result = '' + return '' else: formats = ['%s' for _ in range(action.nargs)] - result = ' '.join(formats) % get_metavar(action.nargs) - return result + return ' '.join(formats) % get_metavar(action.nargs) def _expand_help(self, action): params = dict(vars(action), prog=self._prog) @@ -609,7 +602,7 @@ def _expand_help(self, action): if hasattr(params[name], '__name__'): params[name] = params[name].__name__ if params.get('choices') is not None: - choices_str = ', '.join([str(c) for c in params['choices']]) + choices_str = ', '.join(str(c) for c in params['choices']) params['choices'] = choices_str return self._get_help_string(action) % params @@ -678,11 +671,10 @@ class ArgumentDefaultsHelpFormatter(HelpFormatter): def _get_help_string(self, action): help = action.help - if '%(default)' not in action.help: - if action.default is not SUPPRESS: - defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] - if action.option_strings or action.nargs in defaulting_nargs: - help += ' (default: %(default)s)' + if '%(default)' not in action.help and action.default is not SUPPRESS: + defaulting_nargs = [OPTIONAL, ZERO_OR_MORE] + if action.option_strings or action.nargs in defaulting_nargs: + help += ' (default: %(default)s)' return help @@ -1390,9 +1382,11 @@ def _add_action(self, action): # set the flag if any option strings look like negative numbers for option_string in action.option_strings: - if self._negative_number_matcher.match(option_string): - if not self._has_negative_number_optionals: - self._has_negative_number_optionals.append(True) + if ( + self._negative_number_matcher.match(option_string) + and not self._has_negative_number_optionals + ): + self._has_negative_number_optionals.append(True) # return the created action return action @@ -1462,7 +1456,7 @@ def _get_optional_kwargs(self, *args, **kwargs): long_option_strings = [] for option_string in args: # error on strings that don't start with an appropriate prefix - if not option_string[0] in self.prefix_chars: + if option_string[0] not in self.prefix_chars: args = {'option': option_string, 'prefix_chars': self.prefix_chars} msg = _('invalid option string %(option)r: ' @@ -1471,10 +1465,12 @@ def _get_optional_kwargs(self, *args, **kwargs): # strings starting with two prefix characters are long options option_strings.append(option_string) - if option_string[0] in self.prefix_chars: - if len(option_string) > 1: - if option_string[1] in self.prefix_chars: - long_option_strings.append(option_string) + if ( + option_string[0] in self.prefix_chars + and len(option_string) > 1 + and option_string[1] in self.prefix_chars + ): + long_option_strings.append(option_string) # infer destination, '--foo-bar' -> 'foo_bar' and '-x' -> 'x' dest = kwargs.pop('dest', None) @@ -1523,9 +1519,8 @@ def _handle_conflict_error(self, action, conflicting_actions): message = ngettext('conflicting option string: %s', 'conflicting option strings: %s', len(conflicting_actions)) - conflict_string = ', '.join([option_string - for option_string, action - in conflicting_actions]) + conflict_string = ', '.join(option_string for option_string, action + in conflicting_actions) raise ArgumentError(action, message % conflict_string) def _handle_conflict_resolve(self, action, conflicting_actions): @@ -2089,8 +2084,7 @@ def _match_arguments_partial(self, actions, arg_strings_pattern): result = [] for i in range(len(actions), 0, -1): actions_slice = actions[:i] - pattern = ''.join([self._get_nargs_pattern(action) - for action in actions_slice]) + pattern = ''.join(self._get_nargs_pattern(action) for action in actions_slice) match = _re.match(pattern, arg_strings_pattern) if match is not None: result.extend([len(string) for string in match.groups()]) diff --git a/Lib/asynchat.py b/Lib/asynchat.py index fc1146adbb10dc5..6cc4d7dd791fa93 100644 --- a/Lib/asynchat.py +++ b/Lib/asynchat.py @@ -278,11 +278,11 @@ def more(self): if len(self.data) > self.buffer_size: result = self.data[:self.buffer_size] self.data = self.data[self.buffer_size:] - return result else: result = self.data self.data = b'' - return result + + return result # Given 'haystack', see if any prefix of 'needle' is at its end. This diff --git a/Lib/asyncore.py b/Lib/asyncore.py index 828f4d4fe7897b7..6c33f19f5747bc9 100644 --- a/Lib/asyncore.py +++ b/Lib/asyncore.py @@ -218,11 +218,7 @@ class dispatcher: ignore_log_types = frozenset({'warning'}) def __init__(self, sock=None, map=None): - if map is None: - self._map = socket_map - else: - self._map = map - + self._map = socket_map if map is None else map self._fileno = None if sock: @@ -335,12 +331,12 @@ def connect(self, address): or err == EINVAL and os.name == 'nt': self.addr = address return - if err in (0, EISCONN): - self.addr = address - self.handle_connect_event() - else: + if err not in (0, EISCONN): raise OSError(err, errorcode[err]) + self.addr = address + self.handle_connect_event() + def accept(self): # XXX can return either an address pair or None try: @@ -357,8 +353,7 @@ def accept(self): def send(self, data): try: - result = self.socket.send(data) - return result + return self.socket.send(data) except OSError as why: if why.args[0] == EWOULDBLOCK: return 0 @@ -371,21 +366,20 @@ def send(self, data): def recv(self, buffer_size): try: data = self.socket.recv(buffer_size) - if not data: - # a closed connection is indicated by signaling - # a read condition, and having recv() return 0. - self.handle_close() - return b'' - else: + if data: return data + # a closed connection is indicated by signaling + # a read condition, and having recv() return 0. + self.handle_close() + return b'' except OSError as why: # winsock sometimes raises ENOTCONN - if why.args[0] in _DISCONNECTED: - self.handle_close() - return b'' - else: + if why.args[0] not in _DISCONNECTED: raise + self.handle_close() + return b'' + def close(self): self.connected = False self.accepting = False @@ -435,9 +429,8 @@ def handle_write_event(self): # We will pretend it didn't happen. return - if not self.connected: - if self.connecting: - self.handle_connect_event() + if not self.connected and self.connecting: + self.handle_connect_event() self.handle_write() def handle_expt_event(self): @@ -549,7 +542,7 @@ def compact_traceback(): del tb file, function, line = tbinfo[-1] - info = ' '.join(['[%s|%s|%s]' % x for x in tbinfo]) + info = ' '.join('[%s|%s|%s]' % x for x in tbinfo) return (file, function, line), t, v, info def close_all(map=None, ignore_all=False): diff --git a/Lib/base64.py b/Lib/base64.py index eb8f258a2d19774..a4507aaf3f82206 100755 --- a/Lib/base64.py +++ b/Lib/base64.py @@ -339,9 +339,8 @@ def a85encode(b, *, foldspaces=False, wrapcol=0, pad=False, adobe=False): wrapcol = max(2 if adobe else 1, wrapcol) chunks = [result[i: i + wrapcol] for i in range(0, len(result), wrapcol)] - if adobe: - if len(chunks[-1]) + 2 > wrapcol: - chunks.append(b'') + if adobe and len(chunks[-1]) + 2 > wrapcol: + chunks.append(b'') result = b'\n'.join(chunks) if adobe: result += _A85END @@ -577,9 +576,10 @@ def main(): sys.exit(2) func = encode for o, a in opts: - if o == '-e': func = encode - if o == '-d': func = decode - if o == '-u': func = decode + if o in ['-d', '-u']: + func = decode + elif o == '-e': + func = encode if o == '-t': test(); return if args and args[0] != '-': with open(args[0], 'rb') as f: diff --git a/Lib/bdb.py b/Lib/bdb.py index 880ff5daf9953de..ecad13d3b9077eb 100644 --- a/Lib/bdb.py +++ b/Lib/bdb.py @@ -190,10 +190,7 @@ def dispatch_exception(self, frame, arg): def is_skipped_module(self, module_name): "Return True if module_name matches any skip pattern." - for pattern in self.skip: - if fnmatch.fnmatch(module_name, pattern): - return True - return False + return any(fnmatch.fnmatch(module_name, pattern) for pattern in self.skip) def stop_here(self, frame): "Return True if frame is below the starting frame in the stack." @@ -206,9 +203,7 @@ def stop_here(self, frame): if self.stoplineno == -1: return False return frame.f_lineno >= self.stoplineno - if not self.stopframe: - return True - return False + return not self.stopframe def break_here(self, frame): """Return True if there is an effective breakpoint for this line. @@ -224,8 +219,8 @@ def break_here(self, frame): # The line itself has no breakpoint, but maybe the line is the # first line of a function with breakpoint set by function name. lineno = frame.f_code.co_firstlineno - if lineno not in self.breaks[filename]: - return False + if lineno not in self.breaks[filename]: + return False # flag says ok to delete temp. bp (bp, flag) = effective(filename, lineno, frame) @@ -542,18 +537,9 @@ def format_stack_entry(self, frame_lineno, lprefix=': '): frame, lineno = frame_lineno filename = self.canonic(frame.f_code.co_filename) s = '%s(%r)' % (filename, lineno) - if frame.f_code.co_name: - s += frame.f_code.co_name - else: - s += "" - if '__args__' in frame.f_locals: - args = frame.f_locals['__args__'] - else: - args = None - if args: - s += reprlib.repr(args) - else: - s += '()' + s += frame.f_code.co_name or "" + args = frame.f_locals['__args__'] if '__args__' in frame.f_locals else None + s += reprlib.repr(args) if args else '()' if '__return__' in frame.f_locals: rv = frame.f_locals['__return__'] s += '->' @@ -726,14 +712,8 @@ def bpformat(self): ignore, and number of times hit. """ - if self.temporary: - disp = 'del ' - else: - disp = 'keep ' - if self.enabled: - disp = disp + 'yes ' - else: - disp = disp + 'no ' + disp = 'del ' if self.temporary else 'keep ' + disp += 'yes ' if self.enabled else 'no ' ret = '%-4dbreakpoint %s at %s:%d' % (self.number, disp, self.file, self.line) if self.cond: @@ -741,10 +721,7 @@ def bpformat(self): if self.ignore: ret += '\n\tignore next %d hits' % (self.ignore,) if self.hits: - if self.hits > 1: - ss = 's' - else: - ss = '' + ss = 's' if self.hits > 1 else '' ret += '\n\tbreakpoint already hit %d time%s' % (self.hits, ss) return ret @@ -807,12 +784,11 @@ def effective(file, line, frame): b.hits += 1 if not b.cond: # If unconditional, and ignoring go on to next, else break - if b.ignore > 0: - b.ignore -= 1 - continue - else: + if b.ignore <= 0: # breakpoint and marker that it's ok to delete if temporary return (b, True) + b.ignore -= 1 + continue else: # Conditional bp. # Ignore count applies only to those bpt hits where the diff --git a/Lib/binhex.py b/Lib/binhex.py index 56b5f852c0038ac..4443feecc02948f 100644 --- a/Lib/binhex.py +++ b/Lib/binhex.py @@ -186,10 +186,7 @@ def _write(self, data): def _writecrc(self): # XXXX Should this be here?? # self.crc = binascii.crc_hqx('\0\0', self.crc) - if self.crc < 0: - fmt = '>h' - else: - fmt = '>H' + fmt = '>h' if self.crc < 0 else '>H' self.ofp.write(struct.pack(fmt, self.crc)) self.crc = 0 @@ -284,7 +281,7 @@ def read(self, totalwtd): if not newdata: raise Error('Premature EOF on binhex file') data = data + newdata - decdata = decdata + decdatacur + decdata += decdatacur wtd = totalwtd - len(decdata) if not decdata and not self.eof: raise Error('Premature EOF on binhex file') @@ -360,11 +357,11 @@ def __init__(self, ifp): raise Error("No binhex data found") # Cater for \r\n terminated lines (which show up as \n\r, hence # all lines start with \r) - if ch == b'\r': - continue if ch == b':': break + elif ch == b'\r': + continue hqxifp = _Hqxdecoderengine(ifp) self.ifp = _Rledecoderengine(hqxifp) self.crc = 0 @@ -415,7 +412,7 @@ def read(self, *n): n = self.dlen rv = b'' while len(rv) < n: - rv = rv + self._read(n-len(rv)) + rv += self._read(n-len(rv)) self.dlen = self.dlen - n return rv diff --git a/Lib/calendar.py b/Lib/calendar.py index 3828c43ed279f8f..2c45786e9d4571c 100644 --- a/Lib/calendar.py +++ b/Lib/calendar.py @@ -322,10 +322,7 @@ def formatweekday(self, day, width): """ Returns a formatted week day name. """ - if width >= 9: - names = day_name - else: - names = day_abbr + names = day_name if width >= 9 else day_abbr return names[day][:width].center(width) def formatweekheader(self, width): @@ -571,10 +568,7 @@ def __init__(self, firstweekday=0, locale=None): def formatweekday(self, day, width): with different_locale(self.locale): - if width >= 9: - names = day_name - else: - names = day_abbr + names = day_name if width >= 9 else day_abbr name = names[day] return name[:width].center(width) @@ -658,8 +652,7 @@ def timegm(tuple): days = datetime.date(year, month, 1).toordinal() - _EPOCH_ORD + day - 1 hours = days*24 + hour minutes = hours*60 + minute - seconds = minutes*60 + second - return seconds + return minutes*60 + second def main(args): @@ -728,10 +721,7 @@ def main(args): locale = options.locale, options.encoding if options.type == "html": - if options.locale: - cal = LocaleHTMLCalendar(locale=locale) - else: - cal = HTMLCalendar() + cal = LocaleHTMLCalendar(locale=locale) if options.locale else HTMLCalendar() encoding = options.encoding if encoding is None: encoding = sys.getdefaultencoding() @@ -745,10 +735,7 @@ def main(args): parser.error("incorrect number of arguments") sys.exit(1) else: - if options.locale: - cal = LocaleTextCalendar(locale=locale) - else: - cal = TextCalendar() + cal = LocaleTextCalendar(locale=locale) if options.locale else TextCalendar() optdict = dict(w=options.width, l=options.lines) if options.month is None: optdict["c"] = options.spacing diff --git a/Lib/cgi.py b/Lib/cgi.py index b655a057d4be485..49ea70856a42a80 100755 --- a/Lib/cgi.py +++ b/Lib/cgi.py @@ -82,10 +82,7 @@ def initlog(*allargs): logfp = open(logfile, "a") except OSError: pass - if not logfp: - log = nolog - else: - log = dolog + log = nolog if not logfp else dolog log(*allargs) def dolog(fmt, *args): @@ -140,16 +137,12 @@ def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0): # field keys and values (except for files) are returned as strings # an encoding is required to decode the bytes read from self.fp - if hasattr(fp,'encoding'): - encoding = fp.encoding - else: - encoding = 'latin-1' - + encoding = fp.encoding if hasattr(fp,'encoding') else 'latin-1' # fp.read() must return bytes if isinstance(fp, TextIOWrapper): fp = fp.buffer - if not 'REQUEST_METHOD' in environ: + if 'REQUEST_METHOD' not in environ: environ['REQUEST_METHOD'] = 'GET' # For testing stand-alone if environ['REQUEST_METHOD'] == 'POST': ctype, pdict = parse_header(environ['CONTENT_TYPE']) @@ -172,10 +165,7 @@ def parse(fp=None, environ=os.environ, keep_blank_values=0, strict_parsing=0): elif 'QUERY_STRING' in environ: qs = environ['QUERY_STRING'] else: - if sys.argv[1:]: - qs = sys.argv[1] - else: - qs = "" + qs = sys.argv[1] if sys.argv[1:] else "" environ['QUERY_STRING'] = qs # XXX Shouldn't, really return urllib.parse.parse_qs(qs, keep_blank_values, strict_parsing, encoding=encoding) @@ -358,7 +348,7 @@ def __init__(self, fp=None, headers=None, outerboundary=b'', if 'REQUEST_METHOD' in environ: method = environ['REQUEST_METHOD'].upper() self.qs_on_post = None - if method == 'GET' or method == 'HEAD': + if method in ['GET', 'HEAD']: if 'QUERY_STRING' in environ: qs = environ['QUERY_STRING'] elif sys.argv[1:]: @@ -505,9 +495,7 @@ def __getitem__(self, key): """Dictionary style indexing.""" if self.list is None: raise TypeError("not indexable") - found = [] - for item in self.list: - if item.name == key: found.append(item) + found = [item for item in self.list if item.name == key] if not found: raise KeyError(key) if len(found) == 1: @@ -517,42 +505,42 @@ def __getitem__(self, key): def getvalue(self, key, default=None): """Dictionary style get() method, including 'value' lookup.""" - if key in self: - value = self[key] - if isinstance(value, list): - return [x.value for x in value] - else: - return value.value - else: + if key not in self: return default + value = self[key] + if isinstance(value, list): + return [x.value for x in value] + else: + return value.value + def getfirst(self, key, default=None): """ Return the first value received.""" - if key in self: - value = self[key] - if isinstance(value, list): - return value[0].value - else: - return value.value - else: + if key not in self: return default + value = self[key] + if isinstance(value, list): + return value[0].value + else: + return value.value + def getlist(self, key): """ Return list of received values.""" - if key in self: - value = self[key] - if isinstance(value, list): - return [x.value for x in value] - else: - return [value.value] - else: + if key not in self: return [] + value = self[key] + if isinstance(value, list): + return [x.value for x in value] + else: + return [value.value] + def keys(self): """Dictionary style keys() method.""" if self.list is None: raise TypeError("not indexable") - return list(set(item.name for item in self.list)) + return list({item.name for item in self.list}) def __contains__(self, key): """Dictionary style __contains__ method.""" @@ -683,12 +671,11 @@ def read_lines(self): def __write(self, line): """line is always bytes, not string""" - if self.__file is not None: - if self.__file.tell() + len(line) > 1000: - self.file = self.make_file() - data = self.__file.getvalue() - self.file.write(data) - self.__file = None + if self.__file is not None and self.__file.tell() + len(line) > 1000: + self.file = self.make_file() + data = self.__file.getvalue() + self.file.write(data) + self.__file = None if self._binary_file: # keep bytes self.file.write(line) diff --git a/Lib/chunk.py b/Lib/chunk.py index 870c39fe7f50371..0871dedb2f3abca 100644 --- a/Lib/chunk.py +++ b/Lib/chunk.py @@ -53,10 +53,7 @@ def __init__(self, file, align=True, bigendian=True, inclheader=False): import struct self.closed = False self.align = align # whether to align to word (2-byte) boundaries - if bigendian: - strflag = '>' - else: - strflag = '<' + strflag = '>' if bigendian else '<' self.file = file self.chunkname = file.read(4) if len(self.chunkname) < 4: @@ -131,8 +128,7 @@ def read(self, size=-1): return b'' if size < 0: size = self.chunksize - self.size_read - if size > self.chunksize - self.size_read: - size = self.chunksize - self.size_read + size = min(size, self.chunksize - self.size_read) data = self.file.read(size) self.size_read = self.size_read + len(data) if self.size_read == self.chunksize and \ diff --git a/Lib/cmd.py b/Lib/cmd.py index 859e91096d8f57d..0c30798ffc865aa 100644 --- a/Lib/cmd.py +++ b/Lib/cmd.py @@ -84,14 +84,8 @@ def __init__(self, completekey='tab', stdin=None, stdout=None): sys.stdin and sys.stdout are used. """ - if stdin is not None: - self.stdin = stdin - else: - self.stdin = sys.stdin - if stdout is not None: - self.stdout = stdout - else: - self.stdout = sys.stdout + self.stdin = stdin if stdin is not None else sys.stdin + self.stdout = stdout if stdout is not None else sys.stdout self.cmdqueue = [] self.completekey = completekey @@ -130,10 +124,7 @@ def cmdloop(self, intro=None): self.stdout.write(self.prompt) self.stdout.flush() line = self.stdin.readline() - if not len(line): - line = 'EOF' - else: - line = line.rstrip('\r\n') + line = 'EOF' if not len(line) else line.rstrip('\r\n') line = self.precmd(line) stop = self.onecmd(line) stop = self.postcmd(stop, line) @@ -185,7 +176,8 @@ def parseline(self, line): else: return None, None, line i, n = 0, len(line) - while i < n and line[i] in self.identchars: i = i+1 + while i < n and line[i] in self.identchars: + i += 1 cmd, arg = line[:i], line[i:].strip() return cmd, arg, line @@ -209,12 +201,11 @@ def onecmd(self, line): self.lastcmd = '' if cmd == '': return self.default(line) - else: - try: - func = getattr(self, 'do_' + cmd) - except AttributeError: - return self.default(line) - return func(arg) + try: + func = getattr(self, 'do_' + cmd) + except AttributeError: + return self.default(line) + return func(arg) def emptyline(self): """Called when an empty line is entered in response to the prompt. @@ -285,8 +276,8 @@ def get_names(self): def complete_help(self, *args): commands = set(self.completenames(*args)) - topics = set(a[5:] for a in self.get_names() - if a.startswith('help_' + args[0])) + topics = {a[5:] for a in self.get_names() + if a.startswith('help_' + args[0])} return list(commands | topics) def do_help(self, arg): @@ -310,10 +301,7 @@ def do_help(self, arg): names = self.get_names() cmds_doc = [] cmds_undoc = [] - help = {} - for name in names: - if name[:5] == 'help_': - help[name[5:]]=1 + help = {name[5:]: 1 for name in names if name[:5] == 'help_'} names.sort() # There can be duplicates if routines overridden prevname = '' @@ -389,10 +377,7 @@ def columnize(self, list, displaywidth=80): texts = [] for col in range(ncols): i = row + nrows*col - if i >= size: - x = "" - else: - x = list[i] + x = "" if i >= size else list[i] texts.append(x) while texts and not texts[-1]: del texts[-1] diff --git a/Lib/code.py b/Lib/code.py index d8106ae612c4b40..80ba775e2a9d00b 100644 --- a/Lib/code.py +++ b/Lib/code.py @@ -209,8 +209,8 @@ def interact(self, banner=None, exitmsg=None): sys.ps2 except AttributeError: sys.ps2 = "... " - cprt = 'Type "help", "copyright", "credits" or "license" for more information.' if banner is None: + cprt = 'Type "help", "copyright", "credits" or "license" for more information.' self.write("Python %s on %s\n%s\n(%s)\n" % (sys.version, sys.platform, cprt, self.__class__.__name__)) @@ -219,10 +219,7 @@ def interact(self, banner=None, exitmsg=None): more = 0 while 1: try: - if more: - prompt = sys.ps2 - else: - prompt = sys.ps1 + prompt = sys.ps2 if more else sys.ps1 try: line = self.raw_input(prompt) except EOFError: diff --git a/Lib/codecs.py b/Lib/codecs.py index a70ed20f2bc794a..5029f19406a4fc1 100644 --- a/Lib/codecs.py +++ b/Lib/codecs.py @@ -488,14 +488,10 @@ def read(self, size=-1, chars=-1, firstline=False): # read until we get the required number of characters (if available) while True: # can the request be satisfied from the character buffer? - if chars >= 0: - if len(self.charbuffer) >= chars: - break + if chars >= 0 and len(self.charbuffer) >= chars: + break # we need more data - if size < 0: - newdata = self.stream.read() - else: - newdata = self.stream.read(size) + newdata = self.stream.read() if size < 0 else self.stream.read(size) # decode bytes (those remaining from the last call included) data = self.bytebuffer + newdata if not data: @@ -503,13 +499,12 @@ def read(self, size=-1, chars=-1, firstline=False): try: newchars, decodedbytes = self.decode(data, self.errors) except UnicodeDecodeError as exc: - if firstline: - newchars, decodedbytes = \ - self.decode(data[:exc.start], self.errors) - lines = newchars.splitlines(keepends=True) - if len(lines)<=1: - raise - else: + if not firstline: + raise + newchars, decodedbytes = \ + self.decode(data[:exc.start], self.errors) + lines = newchars.splitlines(keepends=True) + if len(lines)<=1: raise # keep undecoded bytes until the next call self.bytebuffer = data[decodedbytes:] @@ -808,10 +803,7 @@ def read(self, size=-1): def readline(self, size=None): - if size is None: - data = self.reader.readline() - else: - data = self.reader.readline(size) + data = self.reader.readline() if size is None else self.reader.readline(size) data, bytesencoded = self.encode(data, self.errors) return data @@ -1073,10 +1065,7 @@ def make_encoding_map(decoding_map): """ m = {} for k,v in decoding_map.items(): - if not v in m: - m[v] = k - else: - m[v] = None + m[v] = k if v not in m else None return m ### error handlers diff --git a/Lib/colorsys.py b/Lib/colorsys.py index b93e3844067e4e5..9a5db15c1481a64 100644 --- a/Lib/colorsys.py +++ b/Lib/colorsys.py @@ -52,18 +52,12 @@ def yiq_to_rgb(y, i, q): g = y - 0.27478764629897834*i - 0.6356910791873801*q b = y - 1.1085450346420322*i + 1.7090069284064666*q - if r < 0.0: - r = 0.0 - if g < 0.0: - g = 0.0 - if b < 0.0: - b = 0.0 - if r > 1.0: - r = 1.0 - if g > 1.0: - g = 1.0 - if b > 1.0: - b = 1.0 + r = max(r, 0.0) + g = max(g, 0.0) + b = max(b, 0.0) + r = min(r, 1.0) + g = min(g, 1.0) + b = min(b, 1.0) return (r, g, b) @@ -98,10 +92,7 @@ def rgb_to_hls(r, g, b): def hls_to_rgb(h, l, s): if s == 0.0: return l, l, l - if l <= 0.5: - m2 = l * (1.0+s) - else: - m2 = l+s-(l*s) + m2 = l * (1.0+s) if l <= 0.5 else l+s-(l*s) m1 = 2.0*l - m2 return (_v(m1, m2, h+ONE_THIRD), _v(m1, m2, h), _v(m1, m2, h-ONE_THIRD)) @@ -148,7 +139,7 @@ def hsv_to_rgb(h, s, v): p = v*(1.0 - s) q = v*(1.0 - s*f) t = v*(1.0 - s*(1.0-f)) - i = i%6 + i %= 6 if i == 0: return v, t, p if i == 1: diff --git a/Lib/compileall.py b/Lib/compileall.py index 72592126d74c3af..4f34976d459c234 100644 --- a/Lib/compileall.py +++ b/Lib/compileall.py @@ -40,10 +40,7 @@ def _walk_dir(dir, ddir=None, maxlevels=10, quiet=0): if name == '__pycache__': continue fullname = os.path.join(dir, name) - if ddir is not None: - dfile = os.path.join(ddir, name) - else: - dfile = None + dfile = os.path.join(ddir, name) if ddir is not None else None if not os.path.isdir(fullname): yield fullname elif (maxlevels > 0 and name != os.curdir and name != os.pardir and @@ -115,10 +112,7 @@ def compile_file(fullname, ddir=None, force=False, rx=None, quiet=0, if quiet < 2 and isinstance(fullname, os.PathLike): fullname = os.fspath(fullname) name = os.path.basename(fullname) - if ddir is not None: - dfile = os.path.join(ddir, name) - else: - dfile = None + dfile = os.path.join(ddir, name) if ddir is not None else None if rx is not None: mo = rx.search(fullname) if mo: @@ -267,11 +261,7 @@ def main(): args.rx = re.compile(args.rx) - if args.recursion is not None: - maxlevels = args.recursion - else: - maxlevels = args.maxlevels - + maxlevels = args.recursion if args.recursion is not None else args.maxlevels # if flist is provided then load it if args.flist: try: @@ -291,24 +281,23 @@ def main(): success = True try: - if compile_dests: - for dest in compile_dests: - if os.path.isfile(dest): - if not compile_file(dest, args.ddir, args.force, args.rx, - args.quiet, args.legacy, - invalidation_mode=invalidation_mode): - success = False - else: - if not compile_dir(dest, maxlevels, args.ddir, - args.force, args.rx, args.quiet, - args.legacy, workers=args.workers, - invalidation_mode=invalidation_mode): - success = False - return success - else: + if not compile_dests: return compile_path(legacy=args.legacy, force=args.force, quiet=args.quiet, invalidation_mode=invalidation_mode) + for dest in compile_dests: + if os.path.isfile(dest): + if not compile_file(dest, args.ddir, args.force, args.rx, + args.quiet, args.legacy, + invalidation_mode=invalidation_mode): + success = False + else: + if not compile_dir(dest, maxlevels, args.ddir, + args.force, args.rx, args.quiet, + args.legacy, workers=args.workers, + invalidation_mode=invalidation_mode): + success = False + return success except KeyboardInterrupt: if args.quiet < 2: print("\n[interrupted]") diff --git a/Lib/configparser.py b/Lib/configparser.py index 4a16101c7a3ab68..e70d4bc6d479658 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -528,19 +528,18 @@ class LegacyInterpolation(Interpolation): def before_get(self, parser, section, option, value, vars): rawval = value depth = MAX_INTERPOLATION_DEPTH - while depth: # Loop through this until it's done + while depth: # Loop through this until it's done depth -= 1 - if value and "%(" in value: - replace = functools.partial(self._interpolation_replace, - parser=parser) - value = self._KEYCRE.sub(replace, value) - try: - value = value % vars - except KeyError as e: - raise InterpolationMissingOptionError( - option, section, rawval, e.args[0]) from None - else: + if not value or "%(" not in value: break + replace = functools.partial(self._interpolation_replace, + parser=parser) + value = self._KEYCRE.sub(replace, value) + try: + value = value % vars + except KeyError as e: + raise InterpolationMissingOptionError( + option, section, rawval, e.args[0]) from None if value and "%(" in value: raise InterpolationDepthError(option, section, rawval) return value @@ -1180,9 +1179,8 @@ def _validate_value_types(self, *, section="", option="", value=""): raise TypeError("section names must be strings") if not isinstance(option, str): raise TypeError("option keys must be strings") - if not self._allow_no_value or value: - if not isinstance(value, str): - raise TypeError("option values must be strings") + if (not self._allow_no_value or value) and not isinstance(value, str): + raise TypeError("option values must be strings") @property def converters(self): diff --git a/Lib/contextlib.py b/Lib/contextlib.py index c06ec73f489d06d..4e45d5817c5a418 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -199,9 +199,11 @@ async def __aexit__(self, typ, value, traceback): # have this behavior). But do this only if the exception wrapped # by the RuntimeError is actully Stop(Async)Iteration (see # issue29692). - if isinstance(value, (StopIteration, StopAsyncIteration)): - if exc.__cause__ is value: - return False + if ( + isinstance(value, (StopIteration, StopAsyncIteration)) + and exc.__cause__ is value + ): + return False raise except BaseException as exc: if exc is not value: diff --git a/Lib/copy.py b/Lib/copy.py index f86040a33c55478..55b9c60b81cdfa3 100644 --- a/Lib/copy.py +++ b/Lib/copy.py @@ -174,11 +174,7 @@ def deepcopy(x, memo=None, _nil=[]): else: raise Error( "un(deep)copyable object of type %s" % cls) - if isinstance(rv, str): - y = x - else: - y = _reconstruct(x, memo, *rv) - + y = x if isinstance(rv, str) else _reconstruct(x, memo, *rv) # If is its own copy, don't memoize. if y is not x: memo[d] = y @@ -292,22 +288,16 @@ def _reconstruct(x, memo, func, args, setattr(y, key, value) if listiter is not None: - if deep: - for item in listiter: + for item in listiter: + if deep: item = deepcopy(item, memo) - y.append(item) - else: - for item in listiter: - y.append(item) + y.append(item) if dictiter is not None: - if deep: - for key, value in dictiter: + for key, value in dictiter: + if deep: key = deepcopy(key, memo) value = deepcopy(value, memo) - y[key] = value - else: - for key, value in dictiter: - y[key] = value + y[key] = value return y del types, weakref, PyStringMap diff --git a/Lib/csv.py b/Lib/csv.py index 58624af9053493b..2a370d2af4c8165 100644 --- a/Lib/csv.py +++ b/Lib/csv.py @@ -147,8 +147,13 @@ def _dict_to_list(self, rowdict): if self.extrasaction == "raise": wrong_fields = rowdict.keys() - self.fieldnames if wrong_fields: - raise ValueError("dict contains fields not in fieldnames: " - + ", ".join([repr(x) for x in wrong_fields])) + raise ValueError( + ( + "dict contains fields not in fieldnames: " + + ", ".join(repr(x) for x in wrong_fields) + ) + ) + return (rowdict.get(key, self.restval) for key in self.fieldnames) def writerow(self, rowdict): @@ -270,11 +275,7 @@ def _guess_quote_and_delimiter(self, data, delimiters): - if dq_regexp.search(data): - doublequote = True - else: - doublequote = False - + doublequote = bool(dq_regexp.search(data)) return (quotechar, doublequote, delim, skipinitialspace) @@ -308,6 +309,8 @@ def _guess_delimiter(self, data, delimiters): modes = {} delims = {} start, end = 0, chunkLength + # minimum consistency threshold + threshold = 0.9 while start < len(data): iteration += 1 for line in data[start:end]: @@ -319,7 +322,7 @@ def _guess_delimiter(self, data, delimiters): metaFrequency[freq] = metaFrequency.get(freq, 0) + 1 charFrequency[char] = metaFrequency - for char in charFrequency.keys(): + for char in charFrequency: items = list(charFrequency[char].items()) if len(items) == 1 and items[0][0] == 0: continue @@ -339,14 +342,17 @@ def _guess_delimiter(self, data, delimiters): total = float(min(chunkLength * iteration, len(data))) # (rows of consistent data) / (number of rows) = 100% consistency = 1.0 - # minimum consistency threshold - threshold = 0.9 - while len(delims) == 0 and consistency >= threshold: + while not delims and consistency >= threshold: for k, v in modeList: - if v[0] > 0 and v[1] > 0: - if ((v[1]/total) >= consistency and - (delimiters is None or k in delimiters)): - delims[k] = v + if ( + v[0] > 0 + and v[1] > 0 + and ( + (v[1] / total) >= consistency + and (delimiters is None or k in delimiters) + ) + ): + delims[k] = v consistency -= 0.01 if len(delims) == 1: @@ -365,7 +371,7 @@ def _guess_delimiter(self, data, delimiters): # if there's more than one, fall back to a 'preferred' list if len(delims) > 1: for d in self.preferred: - if d in delims.keys(): + if d in delims: skipinitialspace = (data[0].count(d) == data[0].count("%c " % d)) return (d, skipinitialspace) @@ -396,9 +402,7 @@ def has_header(self, sample): header = next(rdr) # assume first row is header columns = len(header) - columnTypes = {} - for i in range(columns): columnTypes[i] = None - + columnTypes = {i: None for i in range(columns)} checked = 0 for row in rdr: # arbitrary number of rows to check, to keep it sane diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index e00a125bbd87111..914e4504608a587 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -374,7 +374,18 @@ def _field_init(f, frozen, globals, self_name): # initialize this field. default_name = f'_dflt_{f.name}' - if f.default_factory is not MISSING: + if f.default_factory is MISSING: + # No default factory. + if not f.init: + # This field does not need initialization. Signify that + # to the caller by returning None. + return None + + if f.default is not MISSING: + globals[default_name] = f.default + # There's no default, just do an assignment. + value = f.name + else: if f.init: # This field has a default factory. If a parameter is # given, use it. If not, call the factory. @@ -399,20 +410,6 @@ def _field_init(f, frozen, globals, self_name): globals[default_name] = f.default_factory value = f'{default_name}()' - else: - # No default factory. - if f.init: - if f.default is MISSING: - # There's no default, just do an assignment. - value = f.name - elif f.default is not MISSING: - globals[default_name] = f.default - value = f.name - else: - # This field does not need initialization. Signify that - # to the caller by returning None. - return None - # Only test this now, so that we can create variables for the # default. However, return None to signify that we're not going # to actually do the assignment statement for InitVars. @@ -436,7 +433,7 @@ def _init_param(f): # There's a default, this will be the name that's used to look # it up. default = f'=_dflt_{f.name}' - elif f.default_factory is not MISSING: + else: # There's a factory function. Set a marker. default = '=_HAS_DEFAULT_FACTORY' return f'{f.name}:_type_{f.name}{default}' @@ -454,7 +451,7 @@ def _init_fn(fields, frozen, has_post_init, self_name): for f in fields: # Only consider fields in the __init__ call. if f.init: - if not (f.default is MISSING and f.default_factory is MISSING): + if f.default is not MISSING or f.default_factory is not MISSING: seen_default = True elif seen_default: raise TypeError(f'non-default argument {f.name!r} ' @@ -491,12 +488,21 @@ def _init_fn(fields, frozen, has_post_init, self_name): def _repr_fn(fields): - return _create_fn('__repr__', - ('self',), - ['return self.__class__.__qualname__ + f"(' + - ', '.join([f"{f.name}={{self.{f.name}!r}}" - for f in fields]) + - ')"']) + return _create_fn( + '__repr__', + ('self',), + [ + ( + ( + 'return self.__class__.__qualname__ + f"(' + + ', '.join( + f"{f.name}={{self.{f.name}!r}}" for f in fields + ) + ) + + ')"' + ) + ], + ) def _frozen_get_del_attr(cls, fields): @@ -822,7 +828,7 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen): # Do we have any Field members that don't also have annotations? for name, value in cls.__dict__.items(): - if isinstance(value, Field) and not name in cls_annotations: + if isinstance(value, Field) and name not in cls_annotations: raise TypeError(f'{name!r} is a field but has no type annotation') # Check rules that apply if we are derived from any dataclasses. @@ -847,8 +853,10 @@ def _process_class(cls, init, repr, eq, order, unsafe_hash, frozen): # that such a __hash__ == None was not auto-generated, but it # close enough. class_hash = cls.__dict__.get('__hash__', MISSING) - has_explicit_hash = not (class_hash is MISSING or - (class_hash is None and '__eq__' in cls.__dict__)) + has_explicit_hash = class_hash is not MISSING and ( + class_hash is not None or '__eq__' not in cls.__dict__ + ) + # If we're generating ordering methods, we must be generating the # eq methods. diff --git a/Lib/datetime.py b/Lib/datetime.py index 5e922c80b017ffb..1219572320fb68d 100644 --- a/Lib/datetime.py +++ b/Lib/datetime.py @@ -187,8 +187,8 @@ def _format_offset(off): if ss or ss.microseconds: s += ":%02d" % ss.seconds - if ss.microseconds: - s += '.%06d' % ss.microseconds + if ss.microseconds: + s += '.%06d' % ss.microseconds return s # Correctly substitute for %z and %Z escapes in strftime formats. @@ -278,7 +278,7 @@ def _parse_hh_mm_ss_ff(tstr): time_comps = [0, 0, 0, 0] pos = 0 - for comp in range(0, 3): + for comp in range(3): if (len_str - pos) < 2: raise ValueError('Incomplete time component') @@ -298,16 +298,15 @@ def _parse_hh_mm_ss_ff(tstr): if pos < len_str: if tstr[pos] != '.': raise ValueError('Invalid microsecond component') - else: - pos += 1 + pos += 1 - len_remainder = len_str - pos - if len_remainder not in (3, 6): - raise ValueError('Invalid microsecond component') + len_remainder = len_str - pos + if len_remainder not in (3, 6): + raise ValueError('Invalid microsecond component') - time_comps[3] = int(tstr[pos:]) - if len_remainder == 3: - time_comps[3] *= 1000 + time_comps[3] = int(tstr[pos:]) + if len_remainder == 3: + time_comps[3] *= 1000 return time_comps @@ -535,16 +534,13 @@ def __new__(cls, days=0, seconds=0, microseconds=0, if isinstance(microseconds, float): microseconds = round(microseconds + usdouble) seconds, microseconds = divmod(microseconds, 1000000) - days, seconds = divmod(seconds, 24*3600) - d += days - s += seconds else: microseconds = int(microseconds) seconds, microseconds = divmod(microseconds, 1000000) - days, seconds = divmod(seconds, 24*3600) - d += days - s += seconds microseconds = round(microseconds + usdouble) + days, seconds = divmod(seconds, 24*3600) + d += days + s += seconds assert isinstance(s, int) assert isinstance(microseconds, int) assert abs(s) <= 3 * 24 * 3600 @@ -1132,15 +1128,9 @@ def fromutc(self, dt): def __reduce__(self): getinitargs = getattr(self, "__getinitargs__", None) - if getinitargs: - args = getinitargs() - else: - args = () + args = getinitargs() if getinitargs else () getstate = getattr(self, "__getstate__", None) - if getstate: - state = getstate() - else: - state = getattr(self, "__dict__", None) or None + state = getstate() if getstate else getattr(self, "__dict__", None) or None if state is None: return (self.__class__, args) else: @@ -1297,10 +1287,7 @@ def _cmp(self, other, allow_mixed=False): def __hash__(self): """Hash.""" if self._hashcode == -1: - if self.fold: - t = self.replace(fold=0) - else: - t = self + t = self.replace(fold=0) if self.fold else self tzoff = t.utcoffset() if not tzoff: # zero or None self._hashcode = hash(t._getstate()[0]) @@ -1699,12 +1686,12 @@ def local(u): def timestamp(self): "Return POSIX timestamp as float" - if self._tzinfo is None: - s = self._mktime() - return s + self.microsecond / 1e6 - else: + if self._tzinfo is not None: return (self - _EPOCH).total_seconds() + s = self._mktime() + return s + self.microsecond / 1e6 + def utctimetuple(self): "Return UTC time tuple compatible with time.gmtime()." offset = self.utcoffset() @@ -2019,10 +2006,7 @@ def __sub__(self, other): def __hash__(self): if self._hashcode == -1: - if self.fold: - t = self.replace(fold=0) - else: - t = self + t = self.replace(fold=0) if self.fold else self tzoff = t.utcoffset() if tzoff is None: self._hashcode = hash(t._getstate()[0]) diff --git a/Lib/difflib.py b/Lib/difflib.py index 887c3c26cae4588..a5171685cf76fc3 100644 --- a/Lib/difflib.py +++ b/Lib/difflib.py @@ -616,7 +616,7 @@ def get_grouped_opcodes(self, n=3): group = [] i1, j1 = max(i1, i2-n), max(j1, j2-n) group.append((tag, i1, i2, j1 ,j2)) - if group and not (len(group)==1 and group[0][0] == 'equal'): + if group and (len(group) != 1 or group[0][0] != 'equal'): yield group def ratio(self): @@ -664,13 +664,10 @@ def quick_ratio(self): avail = {} availhas, matches = avail.__contains__, 0 for elt in self.a: - if availhas(elt): - numb = avail[elt] - else: - numb = fullbcount.get(elt, 0) + numb = avail[elt] if availhas(elt) else fullbcount.get(elt, 0) avail[elt] = numb - 1 if numb > 0: - matches = matches + 1 + matches += 1 return _calculate_ratio(matches, len(self.a) + len(self.b)) def real_quick_ratio(self): @@ -1498,7 +1495,7 @@ def _line_iterator(): # so we can do some very readable comparisons. while len(lines) < 4: lines.append(next(diff_lines_iterator, 'X')) - s = ''.join([line[0] for line in lines]) + s = ''.join(line[0] for line in lines) if s.startswith('X'): # When no more lines, pump out any remaining blank lines so the # corresponding add/delete lines get a matching blank line so @@ -1581,7 +1578,7 @@ def _line_pair_iterator(): fromlines,tolines=[],[] while True: # Collecting lines of text until we have a from/to pair - while (len(fromlines)==0 or len(tolines)==0): + while not fromlines or not tolines: try: from_line, to_line, found_diff = next(line_iterator) except StopIteration: @@ -1823,14 +1820,12 @@ def _split_line(self,data_list,line_num,text): if text[i] == '\0': i += 1 mark = text[i] - i += 1 elif text[i] == '\1': - i += 1 mark = '' else: - i += 1 n += 1 + i += 1 # wrap point is inside text, break it up into separate lines line1 = text[:i] line2 = text[i:] @@ -1866,14 +1861,8 @@ def _line_wrapper(self,diffs): # yield from/to line in pairs inserting blank lines as # necessary when one side has more wrapped lines while fromlist or tolist: - if fromlist: - fromdata = fromlist.pop(0) - else: - fromdata = ('',' ') - if tolist: - todata = tolist.pop(0) - else: - todata = ('',' ') + fromdata = fromlist.pop(0) if fromlist else ('', ' ') + todata = tolist.pop(0) if tolist else ('', ' ') yield fromdata,todata,flag def _collect_lines(self,diffs): @@ -2005,10 +1994,7 @@ def make_table(self,fromlines,tolines,fromdesc='',todesc='',context=False, fromlines,tolines = self._tab_newline_replace(fromlines,tolines) # create diffs iterator which generates side by side from/to data - if context: - context_lines = numlines - else: - context_lines = None + context_lines = numlines if context else None diffs = _mdiff(fromlines,tolines,context_lines,linejunk=self._linejunk, charjunk=self._charjunk) diff --git a/Lib/dis.py b/Lib/dis.py index b2b0003203a44f3..ba3916e32268705 100644 --- a/Lib/dis.py +++ b/Lib/dis.py @@ -153,14 +153,16 @@ def code_info(x): return _format_code_info(_get_code_object(x)) def _format_code_info(co): - lines = [] - lines.append("Name: %s" % co.co_name) - lines.append("Filename: %s" % co.co_filename) - lines.append("Argument count: %s" % co.co_argcount) - lines.append("Kw-only arguments: %s" % co.co_kwonlyargcount) - lines.append("Number of locals: %s" % co.co_nlocals) - lines.append("Stack size: %s" % co.co_stacksize) - lines.append("Flags: %s" % pretty_flags(co.co_flags)) + lines = [ + "Name: %s" % co.co_name, + "Filename: %s" % co.co_filename, + "Argument count: %s" % co.co_argcount, + "Kw-only arguments: %s" % co.co_kwonlyargcount, + "Number of locals: %s" % co.co_nlocals, + "Stack size: %s" % co.co_stacksize, + "Flags: %s" % pretty_flags(co.co_flags), + ] + if co.co_consts: lines.append("Constants:") for i_c in enumerate(co.co_consts): @@ -271,10 +273,7 @@ def get_instructions(x, *, first_line=None): co = _get_code_object(x) cell_names = co.co_cellvars + co.co_freevars linestarts = dict(findlinestarts(co)) - if first_line is not None: - line_offset = first_line - co.co_firstlineno - else: - line_offset = 0 + line_offset = first_line - co.co_firstlineno if first_line is not None else 0 return _get_instructions_bytes(co.co_code, co.co_varnames, co.co_names, co.co_consts, cell_names, linestarts, line_offset) @@ -386,17 +385,11 @@ def _disassemble_bytes(code, lasti=-1, varnames=None, names=None, show_lineno = linestarts is not None if show_lineno: maxlineno = max(linestarts.values()) + line_offset - if maxlineno >= 1000: - lineno_width = len(str(maxlineno)) - else: - lineno_width = 3 + lineno_width = len(str(maxlineno)) if maxlineno >= 1000 else 3 else: lineno_width = 0 maxoffset = len(code) - 2 - if maxoffset >= 10000: - offset_width = len(str(maxoffset)) - else: - offset_width = 4 + offset_width = len(str(maxoffset)) if maxoffset >= 10000 else 4 for instr in _get_instructions_bytes(code, varnames, names, constants, cells, linestarts, line_offset=line_offset): @@ -516,10 +509,7 @@ def info(self): def dis(self): """Return a formatted view of the bytecode operations.""" co = self.codeobj - if self.current_offset is not None: - offset = self.current_offset - else: - offset = -1 + offset = self.current_offset if self.current_offset is not None else -1 with io.StringIO() as output: _disassemble_bytes(co.co_code, varnames=co.co_varnames, names=co.co_names, constants=co.co_consts, diff --git a/Lib/doctest.py b/Lib/doctest.py index c1d8a1db111ddd4..339bf9fda40831b 100644 --- a/Lib/doctest.py +++ b/Lib/doctest.py @@ -215,13 +215,14 @@ def _load_testfile(filename, package, module_relative, encoding): if module_relative: package = _normalize_module(package, 3) filename = _module_relative_path(package, filename) - if getattr(package, '__loader__', None) is not None: - if hasattr(package.__loader__, 'get_data'): - file_contents = package.__loader__.get_data(filename) - file_contents = file_contents.decode(encoding) - # get_data() opens files as 'rb', so one must do the equivalent - # conversion as universal newlines would do. - return file_contents.replace(os.linesep, '\n'), filename + if getattr(package, '__loader__', None) is not None and hasattr( + package.__loader__, 'get_data' + ): + file_contents = package.__loader__.get_data(filename) + file_contents = file_contents.decode(encoding) + # get_data() opens files as 'rb', so one must do the equivalent + # conversion as universal newlines would do. + return file_contents.replace(os.linesep, '\n'), filename with open(filename, encoding=encoding) as f: return f.read(), filename @@ -277,19 +278,17 @@ def _ellipsis_match(want, got): startpos, endpos = 0, len(got) w = ws[0] if w: # starts with exact match - if got.startswith(w): - startpos = len(w) - del ws[0] - else: + if not got.startswith(w): return False + startpos = len(w) + del ws[0] w = ws[-1] if w: # ends with exact match - if got.endswith(w): - endpos -= len(w) - del ws[-1] - else: + if not got.endswith(w): return False + endpos -= len(w) + del ws[-1] if startpos > endpos: # Exact end matches required more characters than we have, as in # _ellipsis_match('aa...aa', 'aaa') @@ -629,7 +628,7 @@ def parse(self, string, name=''): # If all lines begin with the same indentation, then strip it. min_indent = self._min_indent(string) if min_indent > 0: - string = '\n'.join([l[min_indent:] for l in string.split('\n')]) + string = '\n'.join(l[min_indent:] for l in string.split('\n')) output = [] charno, lineno = 0, 0 @@ -701,7 +700,7 @@ def _parse_example(self, m, name, lineno): source_lines = m.group('source').split('\n') self._check_prompt_blank(source_lines, indent, name, lineno) self._check_prefix(source_lines[1:], ' '*indent + '.', name, lineno) - source = '\n'.join([sl[indent+4:] for sl in source_lines]) + source = '\n'.join(sl[indent+4:] for sl in source_lines) # Divide want into lines; check that it's properly indented; and # then strip the indentation. Spaces before the last newline should @@ -712,15 +711,11 @@ def _parse_example(self, m, name, lineno): del want_lines[-1] # forget final newline & spaces after it self._check_prefix(want_lines, ' '*indent, name, lineno + len(source_lines)) - want = '\n'.join([wl[indent:] for wl in want_lines]) + want = '\n'.join(wl[indent:] for wl in want_lines) # If `want` contains a traceback message, then extract it. m = self._EXCEPTION_RE.match(want) - if m: - exc_msg = m.group('msg') - else: - exc_msg = None - + exc_msg = m.group('msg') if m else None # Extract options from the source. options = self._find_options(source, name, lineno) @@ -769,7 +764,7 @@ def _find_options(self, source, name, lineno): def _min_indent(self, s): "Return the minimum indentation of any non-blank line in `s`" indents = [len(indent) for indent in self._INDENT_RE.findall(s)] - if len(indents) > 0: + if indents: return min(indents) else: return 0 @@ -873,10 +868,10 @@ def find(self, obj, name=None, module=None, globs=None, extraglobs=None): # If name was not specified, then extract it from the object. if name is None: name = getattr(obj, '__name__', None) - if name is None: - raise ValueError("DocTestFinder.find: name must be given " - "when obj.__name__ doesn't exist: %r" % - (type(obj),)) + if name is None: + raise ValueError("DocTestFinder.find: name must be given " + "when obj.__name__ doesn't exist: %r" % + (type(obj),)) # Find the module that contains the given object (if obj is # a module, then module=obj.). Note: this may fail, in which @@ -898,7 +893,7 @@ def find(self, obj, name=None, module=None, globs=None, extraglobs=None): # Check to see if it's one of our special internal "files" # (see __patched_linecache_getlines). file = inspect.getfile(obj) - if not file[0]+file[-2:] == '<]>': file = None + if file[0] + file[-2:] != '<]>': file = None if file is None: source_lines = None else: @@ -916,10 +911,7 @@ def find(self, obj, name=None, module=None, globs=None, extraglobs=None): # Initialize globals, and merge in extraglobs. if globs is None: - if module is None: - globs = {} - else: - globs = module.__dict__.copy() + globs = {} if module is None else module.__dict__.copy() else: globs = globs.copy() if extraglobs is not None: @@ -1408,12 +1400,12 @@ def __record_outcome(self, test, f, t): r'\[(?P\d+)\]>$') def __patched_linecache_getlines(self, filename, module_globals=None): m = self.__LINECACHE_FILENAME_RE.match(filename) - if m and m.group('name') == self.test.name: - example = self.test.examples[int(m.group('examplenum'))] - return example.source.splitlines(keepends=True) - else: + if not m or m.group('name') != self.test.name: return self.save_linecache_getlines(filename, module_globals) + example = self.test.examples[int(m.group('examplenum'))] + return example.source.splitlines(keepends=True) + def run(self, test, compileflags=None, out=None, clear_globs=True): """ Run the examples in `test`, and display the results using the @@ -2054,10 +2046,7 @@ class doctest.Tester, then merges the results into (or creates) name = os.path.basename(filename) # Assemble the globals. - if globs is None: - globs = {} - else: - globs = globs.copy() + globs = {} if globs is None else globs.copy() if extraglobs is not None: globs.update(extraglobs) if '__name__' not in globs: @@ -2160,9 +2149,9 @@ def __init__(self, test, optionflags=0, setUp=None, tearDown=None, self._dt_tearDown = tearDown def setUp(self): - test = self._dt_test - if self._dt_setUp is not None: + test = self._dt_test + self._dt_setUp(test) def tearDown(self): @@ -2199,10 +2188,7 @@ def runTest(self): def format_failure(self, err): test = self._dt_test - if test.lineno is None: - lineno = 'unknown line number' - else: - lineno = '%s' % test.lineno + lineno = 'unknown line number' if test.lineno is None else '%s' % test.lineno lname = '.'.join(test.name.split('.')[-1:]) return ('Failed doctest test for %s\n' ' File "%s", line %s, in %s\n\n%s' @@ -2411,11 +2397,7 @@ def format_failure(self, err): def DocFileTest(path, module_relative=True, package=None, globs=None, parser=DocTestParser(), encoding=None, **options): - if globs is None: - globs = {} - else: - globs = globs.copy() - + globs = {} if globs is None else globs.copy() if package and not module_relative: raise ValueError("Package may only be specified for module-" "relative paths.") @@ -2602,8 +2584,7 @@ def testsource(module, name): if not test: raise ValueError(name, "not found in tests") test = test[0] - testsrc = script_from_examples(test.docstring) - return testsrc + return script_from_examples(test.docstring) def debug_src(src, pm=False, globs=None): """Debug a single doctest docstring, in argument `src`'""" @@ -2614,11 +2595,7 @@ def debug_script(src, pm=False, globs=None): "Debug a test script. `src` is the script, as a string." import pdb - if globs: - globs = globs.copy() - else: - globs = {} - + globs = globs.copy() if globs else {} if pm: try: exec(src, globs, globs) diff --git a/Lib/enum.py b/Lib/enum.py index 04d8ec1fa872f88..41452824b0644bf 100644 --- a/Lib/enum.py +++ b/Lib/enum.py @@ -182,12 +182,11 @@ def __new__(metacls, cls, bases, classdict): # sabotage -- it's on them to make sure it works correctly. We use # __reduce_ex__ instead of any of the others as it is preferred by # pickle over __reduce__, and it handles all pickle protocols. - if '__reduce_ex__' not in classdict: - if member_type is not object: - methods = ('__getnewargs_ex__', '__getnewargs__', - '__reduce_ex__', '__reduce__') - if not any(m in member_type.__dict__ for m in methods): - _make_class_unpicklable(enum_class) + if '__reduce_ex__' not in classdict and member_type is not object: + methods = ('__getnewargs_ex__', '__getnewargs__', + '__reduce_ex__', '__reduce__') + if all(m not in member_type.__dict__ for m in methods): + _make_class_unpicklable(enum_class) # instantiate them, checking for duplicates as we go # we instantiate first instead of checking for duplicates first in case @@ -195,10 +194,7 @@ def __new__(metacls, cls, bases, classdict): # auto-numbering ;) for member_name in classdict._member_names: value = enum_members[member_name] - if not isinstance(value, tuple): - args = (value, ) - else: - args = value + args = (value, ) if not isinstance(value, tuple) else value if member_type is tuple: # special case for tuple enums args = (args, ) # wrap it one more time if not use_args: @@ -208,10 +204,7 @@ def __new__(metacls, cls, bases, classdict): else: enum_member = __new__(enum_class, *args) if not hasattr(enum_member, '_value_'): - if member_type is object: - enum_member._value_ = value - else: - enum_member._value_ = member_type(*args) + enum_member._value_ = value if member_type is object else member_type(*args) value = enum_member._value_ enum_member._name_ = member_name enum_member.__objclass__ = enum_class @@ -508,11 +501,7 @@ def _find_new_(classdict, member_type, first_enum): # if a non-object.__new__ is used then whatever value/tuple was # assigned to the enum member name will be passed to __new__ and to the # new enum member's __init__ - if __new__ is object.__new__: - use_args = False - else: - use_args = True - + use_args = __new__ is not object.__new__ return __new__, save_new, use_args @@ -620,10 +609,7 @@ def _convert(cls, name, module, filter, source=None): # also, replace the __reduce_ex__ method so unpickling works in # previous Python versions module_globals = vars(sys.modules[module]) - if source: - source = vars(source) - else: - source = module_globals + source = vars(source) if source else module_globals # _value2member_map_ is populated in the same order every time # for a consistent reverse mapping of number to name when there # are multiple names for the same number. @@ -714,10 +700,10 @@ def __repr__(self): return '<%s.%s: %r>' % (cls.__name__, self._name_, self._value_) members, uncovered = _decompose(cls, self._value_) return '<%s.%s: %r>' % ( - cls.__name__, - '|'.join([str(m._name_ or m._value_) for m in members]), - self._value_, - ) + cls.__name__, + '|'.join(str(m._name_ or m._value_) for m in members), + self._value_, + ) def __str__(self): cls = self.__class__ @@ -728,9 +714,9 @@ def __str__(self): return '%s.%r' % (cls.__name__, members[0]._value_) else: return '%s.%s' % ( - cls.__name__, - '|'.join([str(m._name_ or m._value_) for m in members]), - ) + cls.__name__, + '|'.join(str(m._name_ or m._value_) for m in members), + ) def __bool__(self): return bool(self._value_) @@ -766,8 +752,7 @@ class IntFlag(int, Flag): def _missing_(cls, value): if not isinstance(value, int): raise ValueError("%r is not a valid %s" % (value, cls.__name__)) - new_member = cls._create_pseudo_member_(value) - return new_member + return cls._create_pseudo_member_(value) @classmethod def _create_pseudo_member_(cls, value): @@ -802,8 +787,7 @@ def _create_pseudo_member_(cls, value): def __or__(self, other): if not isinstance(other, (self.__class__, int)): return NotImplemented - result = self.__class__(self._value_ | self.__class__(other)._value_) - return result + return self.__class__(self._value_ | self.__class__(other)._value_) def __and__(self, other): if not isinstance(other, (self.__class__, int)): @@ -820,8 +804,7 @@ def __xor__(self, other): __rxor__ = __xor__ def __invert__(self): - result = self.__class__(~self._value_) - return result + return self.__class__(~self._value_) def _high_bit(value): @@ -830,13 +813,17 @@ def _high_bit(value): def unique(enumeration): """Class decorator for enumerations ensuring unique member values.""" - duplicates = [] - for name, member in enumeration.__members__.items(): - if name != member.name: - duplicates.append((name, member.name)) + duplicates = [ + (name, member.name) + for name, member in enumeration.__members__.items() + if name != member.name + ] + if duplicates: alias_details = ', '.join( - ["%s -> %s" % (alias, name) for (alias, name) in duplicates]) + "%s -> %s" % (alias, name) for (alias, name) in duplicates + ) + raise ValueError('duplicate values found in %r: %s' % (enumeration, alias_details)) return enumeration diff --git a/Lib/filecmp.py b/Lib/filecmp.py index e5ad8397e4c5395..8be6c6a15e09336 100644 --- a/Lib/filecmp.py +++ b/Lib/filecmp.py @@ -71,8 +71,8 @@ def _sig(st): st.st_mtime) def _do_cmp(f1, f2): - bufsize = BUFSIZE with open(f1, 'rb') as fp1, open(f2, 'rb') as fp2: + bufsize = BUFSIZE while True: b1 = fp1.read(bufsize) b2 = fp2.read(bufsize) diff --git a/Lib/fileinput.py b/Lib/fileinput.py index c6fc9a1981a1fa0..6cab06a1957d902 100644 --- a/Lib/fileinput.py +++ b/Lib/fileinput.py @@ -194,10 +194,7 @@ def __init__(self, files=None, inplace=False, backup="", bufsize=0, else: if files is None: files = sys.argv[1:] - if not files: - files = ('-',) - else: - files = tuple(files) + files = ('-', ) if not files else tuple(files) self._files = files self._inplace = inplace self._backup = backup @@ -414,8 +411,10 @@ def _test(): backup = False opts, args = getopt.getopt(sys.argv[1:], "ib:") for o, a in opts: - if o == '-i': inplace = True - if o == '-b': backup = a + if o == '-b': + backup = a + elif o == '-i': + inplace = True for line in input(args, inplace=inplace, backup=backup): if line[-1:] == '\n': line = line[:-1] if line[-1:] == '\r': line = line[:-1] diff --git a/Lib/fnmatch.py b/Lib/fnmatch.py index b98e6413295e1ca..3d9cd22d6e484fe 100644 --- a/Lib/fnmatch.py +++ b/Lib/fnmatch.py @@ -81,21 +81,21 @@ def translate(pat): res = '' while i < n: c = pat[i] - i = i+1 + i += 1 if c == '*': - res = res + '.*' + res += '.*' elif c == '?': - res = res + '.' + res += '.' elif c == '[': j = i if j < n and pat[j] == '!': - j = j+1 + j += 1 if j < n and pat[j] == ']': - j = j+1 + j += 1 while j < n and pat[j] != ']': - j = j+1 + j += 1 if j >= n: - res = res + '\\[' + res += '\\[' else: stuff = pat[i:j] if '--' not in stuff: @@ -124,5 +124,5 @@ def translate(pat): stuff = '\\' + stuff res = '%s[%s]' % (res, stuff) else: - res = res + re.escape(c) + res += re.escape(c) return r'(?s:%s)\Z' % res diff --git a/Lib/formatter.py b/Lib/formatter.py index e2394de8c291952..b218cae97d8cc83 100644 --- a/Lib/formatter.py +++ b/Lib/formatter.py @@ -131,15 +131,15 @@ def format_counter(self, format, counter): label = '' for c in format: if c == '1': - label = label + ('%d' % counter) + label += '%d' % counter elif c in 'aA': if counter > 0: - label = label + self.format_letter(c, counter) + label += self.format_letter(c, counter) elif c in 'iI': if counter > 0: - label = label + self.format_roman(c, counter) + label += self.format_roman(c, counter) else: - label = label + c + label += c return label def format_letter(self, case, counter): @@ -172,7 +172,7 @@ def format_roman(self, case, counter): s = '' s = s + ones[index]*x label = s + label - index = index + 1 + index += 1 if case == 'I': return label.upper() return label @@ -186,9 +186,8 @@ def add_flowing_data(self, data): return elif prespace or self.softspace: if not data: - if not self.nospace: - self.softspace = 1 - self.parskip = 0 + self.softspace = 1 + self.parskip = 0 return if not self.nospace: data = ' ' + data @@ -250,10 +249,7 @@ def push_font(self, font): def pop_font(self): if self.font_stack: del self.font_stack[-1] - if self.font_stack: - font = self.font_stack[-1] - else: - font = None + font = self.font_stack[-1] if self.font_stack else None self.writer.new_font(font) def push_margin(self, margin): @@ -267,10 +263,7 @@ def pop_margin(self): if self.margin_stack: del self.margin_stack[-1] fstack = [m for m in self.margin_stack if m] - if fstack: - margin = fstack[-1] - else: - margin = None + margin = fstack[-1] if fstack else None self.writer.new_margin(margin, len(fstack)) def set_spacing(self, spacing): diff --git a/Lib/fractions.py b/Lib/fractions.py index 8330202d7037b30..f40e204d57895fd 100644 --- a/Lib/fractions.py +++ b/Lib/fractions.py @@ -453,28 +453,27 @@ def __pow__(a, b): result will be rational. """ - if isinstance(b, numbers.Rational): - if b.denominator == 1: - power = b.numerator - if power >= 0: - return Fraction(a._numerator ** power, - a._denominator ** power, - _normalize=False) - elif a._numerator >= 0: - return Fraction(a._denominator ** -power, - a._numerator ** -power, - _normalize=False) - else: - return Fraction((-a._denominator) ** -power, - (-a._numerator) ** -power, - _normalize=False) - else: - # A fractional power will generally produce an - # irrational number. - return float(a) ** float(b) - else: + if not isinstance(b, numbers.Rational): return float(a) ** b + if b.denominator != 1: + # A fractional power will generally produce an + # irrational number. + return float(a) ** float(b) + power = b.numerator + if power >= 0: + return Fraction(a._numerator ** power, + a._denominator ** power, + _normalize=False) + elif a._numerator >= 0: + return Fraction(a._denominator ** -power, + a._numerator ** -power, + _normalize=False) + else: + return Fraction((-a._denominator) ** -power, + (-a._numerator) ** -power, + _normalize=False) + def __rpow__(b, a): """a ** b""" if b._denominator == 1 and b._numerator >= 0: @@ -557,10 +556,7 @@ def __hash__(self): # _PyHASH_MODULUS, or 0 if self._denominator is divisible by # _PyHASH_MODULUS. dinv = pow(self._denominator, _PyHASH_MODULUS - 2, _PyHASH_MODULUS) - if not dinv: - hash_ = _PyHASH_INF - else: - hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS + hash_ = abs(self._numerator) * dinv % _PyHASH_MODULUS if dinv else _PyHASH_INF result = hash_ if self >= 0 else -hash_ return -2 if result == -1 else result @@ -577,7 +573,7 @@ def __eq__(a, b): if math.isnan(b) or math.isinf(b): # comparisons with an infinity or nan should behave in # the same way for any finite a, so treat a as zero. - return 0.0 == b + return b == 0.0 else: return a == a.from_float(b) else: diff --git a/Lib/ftplib.py b/Lib/ftplib.py index 05840d492360a0c..3923372e7bff2b7 100644 --- a/Lib/ftplib.py +++ b/Lib/ftplib.py @@ -554,7 +554,7 @@ def nlst(self, *args): '''Return a list of files in a given directory (default the current).''' cmd = 'NLST' for arg in args: - cmd = cmd + (' ' + arg) + cmd += ' ' + arg files = [] self.retrlines(cmd, files.append) return files @@ -571,7 +571,7 @@ def dir(self, *args): args, func = args[:-1], args[-1] for arg in args: if arg: - cmd = cmd + (' ' + arg) + cmd += ' ' + arg self.retrlines(cmd, func) def mlsd(self, path="", facts=[]): @@ -588,10 +588,7 @@ def mlsd(self, path="", facts=[]): ''' if facts: self.sendcmd("OPTS MLST " + ";".join(facts) + ";") - if path: - cmd = "MLSD %s" % path - else: - cmd = "MLSD" + cmd = "MLSD %s" % path if path else "MLSD" lines = [] self.retrlines(cmd, lines.append) for line in lines: @@ -892,12 +889,12 @@ def parse257(resp): n = len(resp) while i < n: c = resp[i] - i = i+1 + i += 1 if c == '"': if i >= n or resp[i] != '"': break - i = i+1 - dirname = dirname + c + i += 1 + dirname += c return dirname @@ -946,7 +943,7 @@ def test(): debugging = 0 rcfile = None while sys.argv[1] == '-d': - debugging = debugging+1 + debugging += 1 del sys.argv[1] if sys.argv[1][:2] == '-r': # get name of alternate ~/.netrc file: diff --git a/Lib/functools.py b/Lib/functools.py index d5f43935e6cf796..3e830dd4027f10a 100644 --- a/Lib/functools.py +++ b/Lib/functools.py @@ -693,10 +693,7 @@ def is_related(typ): # Remove entries which are strict bases of other entries (they will end up # in the MRO anyway. def is_strict_base(typ): - for other in types: - if typ != other and typ in other.__mro__: - return True - return False + return any(typ != other and typ in other.__mro__ for other in types) types = [n for n in types if not is_strict_base(n)] # Subclasses of the ABCs in *types* which are also implemented by # *cls* can be used to stabilize ABC ordering. diff --git a/Lib/getopt.py b/Lib/getopt.py index 9d4cab1bac360dd..85855322f04c736 100644 --- a/Lib/getopt.py +++ b/Lib/getopt.py @@ -81,10 +81,7 @@ def getopt(args, shortopts, longopts = []): """ opts = [] - if type(longopts) == type(""): - longopts = [longopts] - else: - longopts = list(longopts) + longopts = [longopts] if type(longopts) == type("") else list(longopts) while args and args[0].startswith('-') and args[0] != '-': if args[0] == '--': args = args[1:] @@ -113,11 +110,7 @@ def gnu_getopt(args, shortopts, longopts = []): opts = [] prog_args = [] - if isinstance(longopts, str): - longopts = [longopts] - else: - longopts = list(longopts) - + longopts = [longopts] if isinstance(longopts, str) else list(longopts) # Allow options after non-option arguments? if shortopts.startswith('+'): shortopts = shortopts[1:] diff --git a/Lib/getpass.py b/Lib/getpass.py index 36e17e4cb6965db..3dbfaed90a1c0fa 100644 --- a/Lib/getpass.py +++ b/Lib/getpass.py @@ -104,11 +104,11 @@ def win_getpass(prompt='Password: ', stream=None): pw = "" while 1: c = msvcrt.getwch() - if c == '\r' or c == '\n': + if c in ['\r', '\n']: break if c == '\003': raise KeyboardInterrupt - if c == '\b': + elif c == '\b': pw = pw[:-1] else: pw = pw + c diff --git a/Lib/gettext.py b/Lib/gettext.py index 4c3b80b0239b0ab..ff5d56ba0c2f15c 100644 --- a/Lib/gettext.py +++ b/Lib/gettext.py @@ -291,10 +291,7 @@ def ngettext(self, msgid1, msgid2, n): def lngettext(self, msgid1, msgid2, n): if self._fallback: return self._fallback.lngettext(msgid1, msgid2, n) - if n == 1: - tmsg = msgid1 - else: - tmsg = msgid2 + tmsg = msgid1 if n == 1 else msgid2 if self._output_charset: return tmsg.encode(self._output_charset) return tmsg.encode(locale.getpreferredencoding()) @@ -367,16 +364,15 @@ def _parse(self, fp): # Now put all messages from the .mo file buffer into the catalog # dictionary. - for i in range(0, msgcount): + for i in range(msgcount): mlen, moff = unpack(ii, buf[masteridx:masteridx+8]) mend = moff + mlen tlen, toff = unpack(ii, buf[transidx:transidx+8]) tend = toff + tlen - if mend < buflen and tend < buflen: - msg = buf[moff:mend] - tmsg = buf[toff:tend] - else: + if mend >= buflen or tend >= buflen: raise OSError(0, 'File is corrupt', filename) + msg = buf[moff:mend] + tmsg = buf[toff:tend] # See if we're looking at GNU .mo conventions for metadata if mlen == 0: # Catalog description @@ -440,10 +436,7 @@ def lngettext(self, msgid1, msgid2, n): except KeyError: if self._fallback: return self._fallback.lngettext(msgid1, msgid2, n) - if n == 1: - tmsg = msgid1 - else: - tmsg = msgid2 + tmsg = msgid1 if n == 1 else msgid2 if self._output_charset: return tmsg.encode(self._output_charset) return tmsg.encode(locale.getpreferredencoding()) @@ -463,10 +456,7 @@ def ngettext(self, msgid1, msgid2, n): except KeyError: if self._fallback: return self._fallback.ngettext(msgid1, msgid2, n) - if n == 1: - tmsg = msgid1 - else: - tmsg = msgid2 + tmsg = msgid1 if n == 1 else msgid2 return tmsg @@ -491,10 +481,7 @@ def find(domain, localedir=None, languages=None, all=False): if nelang not in nelangs: nelangs.append(nelang) # select a language - if all: - result = [] - else: - result = None + result = [] if all else None for lang in nelangs: if lang == 'C': break @@ -614,10 +601,7 @@ def ldngettext(domain, msgid1, msgid2, n): try: t = translation(domain, _localedirs.get(domain, None), codeset=codeset) except OSError: - if n == 1: - tmsg = msgid1 - else: - tmsg = msgid2 + tmsg = msgid1 if n == 1 else msgid2 return tmsg.encode(codeset or locale.getpreferredencoding()) return t.lngettext(msgid1, msgid2, n) diff --git a/Lib/gzip.py b/Lib/gzip.py index ddc7bda1fecbbd2..b4952c7e47b80ac 100644 --- a/Lib/gzip.py +++ b/Lib/gzip.py @@ -80,12 +80,11 @@ def __init__(self, f, prepend=b''): def read(self, size): if self._read is None: return self.file.read(size) + read = self._read if self._read + size <= self._length: - read = self._read self._read += size return self._buffer[read:self._read] else: - read = self._read self._read = None return self._buffer[read:] + \ self.file.read(size-self._length+read) @@ -360,7 +359,7 @@ def seek(self, offset, whence=io.SEEK_SET): raise OSError('Negative seek in write mode') count = offset - self.offset chunk = b'\0' * 1024 - for i in range(count // 1024): + for _ in range(count // 1024): self.write(chunk) self.write(b'\0' * (count % 1024)) elif self.mode == READ: diff --git a/Lib/imaplib.py b/Lib/imaplib.py index e1cece0b283f2be..7db697e8b66a70c 100644 --- a/Lib/imaplib.py +++ b/Lib/imaplib.py @@ -248,12 +248,11 @@ def _connect(self): raise self.error(self.welcome) self._get_capabilities() - if __debug__: - if self.debug >= 3: - self._mesg('CAPABILITIES: %r' % (self.capabilities,)) + if __debug__ and self.debug >= 3: + self._mesg('CAPABILITIES: %r' % (self.capabilities,)) for version in AllowedVersions: - if not version in self.capabilities: + if version not in self.capabilities: continue self.PROTOCOL_VERSION = version return @@ -387,10 +386,7 @@ def append(self, mailbox, flags, date_time, message): flags = '(%s)' % flags else: flags = None - if date_time: - date_time = Time2Internaldate(date_time) - else: - date_time = None + date_time = Time2Internaldate(date_time) if date_time else None literal = MapCRLF.sub(CRLF, message) if self.utf8_enabled: literal = b'UTF8 (' + literal + b')' @@ -662,9 +658,8 @@ def noop(self): (typ, [data]) = .noop() """ - if __debug__: - if self.debug >= 3: - self._dump_ur(self.untagged_responses) + if __debug__ and self.debug >= 3: + self._dump_ur(self.untagged_responses) return self._simple_command('NOOP') @@ -733,10 +728,7 @@ def select(self, mailbox='INBOX', readonly=False): """ self.untagged_responses = {} # Flush old responses. self.is_readonly = readonly - if readonly: - name = 'EXAMINE' - else: - name = 'SELECT' + name = 'EXAMINE' if readonly else 'SELECT' typ, dat = self._simple_command(name, mailbox) if typ != 'OK': self.state = 'AUTH' # Might have been 'SELECTED' @@ -744,9 +736,8 @@ def select(self, mailbox='INBOX', readonly=False): self.state = 'SELECTED' if 'READ-ONLY' in self.untagged_responses \ and not readonly: - if __debug__: - if self.debug >= 1: - self._dump_ur(self.untagged_responses) + if __debug__ and self.debug >= 1: + self._dump_ur(self.untagged_responses) raise self.readonly('%s is not writable' % mailbox) return typ, self.untagged_responses.get('EXISTS', [None]) @@ -802,14 +793,13 @@ def starttls(self, ssl_context=None): if ssl_context is None: ssl_context = ssl._create_stdlib_context() typ, dat = self._simple_command(name) - if typ == 'OK': - self.sock = ssl_context.wrap_socket(self.sock, - server_hostname=self.host) - self.file = self.sock.makefile('rb') - self._tls_established = True - self._get_capabilities() - else: + if typ != 'OK': raise self.error("Couldn't establish TLS session") + self.sock = ssl_context.wrap_socket(self.sock, + server_hostname=self.host) + self.file = self.sock.makefile('rb') + self._tls_established = True + self._get_capabilities() return self._untagged_response(typ, dat, name) @@ -863,7 +853,7 @@ def uid(self, command, *args): Returns response appropriate to 'command'. """ command = command.upper() - if not command in Commands: + if command not in Commands: raise self.error("Unknown IMAP4 UID command: %s" % command) if self.state not in Commands[command]: raise self.error("command %s illegal in state %s, " @@ -872,10 +862,7 @@ def uid(self, command, *args): ', '.join(Commands[command]))) name = 'UID' typ, dat = self._simple_command(name, command, *args) - if command in ('SEARCH', 'SORT', 'THREAD'): - name = command - else: - name = 'FETCH' + name = command if command in ('SEARCH', 'SORT', 'THREAD') else 'FETCH' return self._untagged_response(typ, dat, name) @@ -900,7 +887,7 @@ def xatom(self, name, *args): name = name.upper() #if not name in self.capabilities: # Let the server decide! # raise self.error('unknown extension command: %s' % name) - if not name in Commands: + if name not in Commands: Commands[name] = (self.state,) return self._simple_command(name, *args) @@ -913,10 +900,9 @@ def _append_untagged(self, typ, dat): if dat is None: dat = b'' ur = self.untagged_responses - if __debug__: - if self.debug >= 5: - self._mesg('untagged_responses[%s] %s += ["%r"]' % - (typ, len(ur.get(typ,'')), dat)) + if __debug__ and self.debug >= 5: + self._mesg('untagged_responses[%s] %s += ["%r"]' % + (typ, len(ur.get(typ,'')), dat)) if typ in ur: ur[typ].append(dat) else: @@ -990,9 +976,8 @@ def _command(self, name, *args): if literator: literal = literator(self.continuation_response) - if __debug__: - if self.debug >= 4: - self._mesg('write literal size %s' % len(literal)) + if __debug__ and self.debug >= 4: + self._mesg('write literal size %s' % len(literal)) try: self.send(literal) @@ -1045,7 +1030,7 @@ def _get_response(self): if self._match(self.tagre, resp): tag = self.mo.group('tag') - if not tag in self.tagged_commands: + if tag not in self.tagged_commands: raise self.abort('unexpected tagged response: %r' % resp) typ = self.mo.group('type') @@ -1057,9 +1042,10 @@ def _get_response(self): # '*' (untagged) responses? - if not self._match(Untagged_response, resp): - if self._match(self.Untagged_status, resp): - dat2 = self.mo.group('data2') + if not self._match(Untagged_response, resp) and self._match( + self.Untagged_status, resp + ): + dat2 = self.mo.group('data2') if self.mo is None: # Only other possibility is '+' (continuation) response... @@ -1083,9 +1069,8 @@ def _get_response(self): # Read literal direct from connection. size = int(self.mo.group('size')) - if __debug__: - if self.debug >= 4: - self._mesg('read literal size %s' % size) + if __debug__ and self.debug >= 4: + self._mesg('read literal size %s' % size) data = self.read(size) # Store response with literal as tuple @@ -1105,9 +1090,8 @@ def _get_response(self): typ = str(typ, self._encoding) self._append_untagged(typ, self.mo.group('data')) - if __debug__: - if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'): - self._mesg('%s response: %r' % (typ, dat)) + if __debug__ and self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'): + self._mesg('%s response: %r' % (typ, dat)) return resp @@ -1133,9 +1117,8 @@ def _get_tagged_response(self, tag): try: self._get_response() except self.abort as val: - if __debug__: - if self.debug >= 1: - self.print_log() + if __debug__ and self.debug >= 1: + self.print_log() raise @@ -1164,9 +1147,8 @@ def _match(self, cre, s): # Save result, return success. self.mo = cre.match(s) - if __debug__: - if self.mo is not None and self.debug >= 5: - self._mesg("\tmatched %r => %r" % (cre.pattern, self.mo.groups())) + if __debug__ and self.mo is not None and self.debug >= 5: + self._mesg("\tmatched %r => %r" % (cre.pattern, self.mo.groups())) return self.mo is not None @@ -1194,12 +1176,11 @@ def _simple_command(self, name, *args): def _untagged_response(self, typ, dat, name): if typ == 'NO': return typ, dat - if not name in self.untagged_responses: + if name not in self.untagged_responses: return typ, [None] data = self.untagged_responses.pop(name) - if __debug__: - if self.debug >= 5: - self._mesg('untagged_responses[%s] => %s' % (name, data)) + if __debug__ and self.debug >= 5: + self._mesg('untagged_responses[%s] => %s' % (name, data)) return typ, data @@ -1391,7 +1372,7 @@ def encode(self, inp): inp = b'' e = binascii.b2a_base64(t) if e: - oup = oup + e[:-1] + oup += e[:-1] return oup def decode(self, inp): diff --git a/Lib/imp.py b/Lib/imp.py index 31f8c766381adc3..ce1cf1fa2a1da05 100644 --- a/Lib/imp.py +++ b/Lib/imp.py @@ -141,20 +141,19 @@ def __init__(self, fullname, path, file=None): def get_data(self, path): """Gross hack to contort loader to deal w/ load_*()'s bad API.""" - if self.file and path == self.path: - # The contract of get_data() requires us to return bytes. Reopen the - # file in binary mode if needed. - if not self.file.closed: - file = self.file - if 'b' not in file.mode: - file.close() - if self.file.closed: - self.file = file = open(self.path, 'rb') - - with file: - return file.read() - else: + if not self.file or path != self.path: return super().get_data(path) + # The contract of get_data() requires us to return bytes. Reopen the + # file in binary mode if needed. + if not self.file.closed: + file = self.file + if 'b' not in file.mode: + file.close() + if self.file.closed: + self.file = file = open(self.path, 'rb') + + with file: + return file.read() class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader): @@ -165,10 +164,7 @@ class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader): def load_source(name, pathname, file=None): loader = _LoadSourceCompatibility(name, pathname, file) spec = util.spec_from_file_location(name, pathname, loader=loader) - if name in sys.modules: - module = _exec(spec, sys.modules[name]) - else: - module = _load(spec) + module = _exec(spec, sys.modules[name]) if name in sys.modules else _load(spec) # To allow reloading to potentially work, use a non-hacked loader which # won't rely on a now-closed file object. module.__loader__ = machinery.SourceFileLoader(name, pathname) @@ -185,10 +181,7 @@ def load_compiled(name, pathname, file=None): """**DEPRECATED**""" loader = _LoadCompiledCompatibility(name, pathname, file) spec = util.spec_from_file_location(name, pathname, loader=loader) - if name in sys.modules: - module = _exec(spec, sys.modules[name]) - else: - module = _load(spec) + module = _exec(spec, sys.modules[name]) if name in sys.modules else _load(spec) # To allow reloading to potentially work, use a non-hacked loader which # won't rely on a now-closed file object. module.__loader__ = SourcelessFileLoader(name, pathname) diff --git a/Lib/inspect.py b/Lib/inspect.py index 717518614fc6d74..0d5b0db449bb1c7 100644 --- a/Lib/inspect.py +++ b/Lib/inspect.py @@ -316,10 +316,7 @@ def isabstract(object): def getmembers(object, predicate=None): """Return all members of an object as (name, value) pairs sorted by name. Optionally, only return members that satisfy a given predicate.""" - if isclass(object): - mro = (object,) + getmro(object) - else: - mro = () + mro = (object,) + getmro(object) if isclass(object) else () results = [] processed = set() names = dir(object) @@ -803,14 +800,13 @@ def findsource(object): return lines, i # else add whitespace to candidate list candidates.append((match.group(1), i)) - if candidates: - # this will sort by whitespace, and by line number, - # less whitespace first - candidates.sort() - return lines, candidates[0][1] - else: + if not candidates: raise OSError('could not find class definition') + # this will sort by whitespace, and by line number, + # less whitespace first + candidates.sort() + return lines, candidates[0][1] if ismethod(object): object = object.__func__ if isfunction(object): @@ -1326,9 +1322,6 @@ def getcallargs(*func_and_positional, **named): spec = getfullargspec(func) args, varargs, varkw, defaults, kwonlyargs, kwonlydefaults, ann = spec f_name = func.__name__ - arg2value = {} - - if ismethod(func) and func.__self__ is not None: # implicit 'self' (or 'cls' for classmethods) argument positional = (func.__self__,) + positional @@ -1337,8 +1330,9 @@ def getcallargs(*func_and_positional, **named): num_defaults = len(defaults) if defaults else 0 n = min(num_pos, num_args) - for i in range(n): - arg2value[args[i]] = positional[i] + arg2value = {args[i]: positional[i] for i in range(n)} + + if varargs: arg2value[varargs] = tuple(positional[n:]) possible_kwargs = set(args + kwonlyargs) @@ -1579,10 +1573,15 @@ def getattr_static(obj, attr, default=_sentinel): klass_result = _check_class(klass, attr) - if instance_result is not _sentinel and klass_result is not _sentinel: - if (_check_class(type(klass_result), '__get__') is not _sentinel and - _check_class(type(klass_result), '__set__') is not _sentinel): - return klass_result + if ( + instance_result is not _sentinel + and klass_result is not _sentinel + and ( + _check_class(type(klass_result), '__get__') is not _sentinel + and _check_class(type(klass_result), '__set__') is not _sentinel + ) + ): + return klass_result if instance_result is not _sentinel: return instance_result @@ -1924,7 +1923,7 @@ def _signature_strip_non_python_syntax(signature): current_parameter += 1 continue - if string == '/': + elif string == '/': assert not skip_next_comma assert last_positional_only is None skip_next_comma = True @@ -1938,7 +1937,7 @@ def _signature_strip_non_python_syntax(signature): if delayed_comma: delayed_comma = False - if not ((type == OP) and (string == ')')): + if type != OP or string != ')': add(', ') add(string) if (string == ','): @@ -2132,11 +2131,7 @@ def _signature_from_function(cls, func): defaults = func.__defaults__ kwdefaults = func.__kwdefaults__ - if defaults: - pos_default_count = len(defaults) - else: - pos_default_count = 0 - + pos_default_count = len(defaults) if defaults else 0 parameters = [] # Non-keyword-only parameters w/o defaults. @@ -2264,12 +2259,11 @@ def _signature_from_callable(obj, *, # First argument of the wrapped callable is `*args`, as in # `partialmethod(lambda *args)`. return sig - else: - sig_params = tuple(sig.parameters.values()) - assert (not sig_params or - first_wrapped_param is not sig_params[0]) - new_params = (first_wrapped_param,) + sig_params - return sig.replace(parameters=new_params) + sig_params = tuple(sig.parameters.values()) + assert (not sig_params or + first_wrapped_param is not sig_params[0]) + new_params = (first_wrapped_param,) + sig_params + return sig.replace(parameters=new_params) if isfunction(obj) or _signature_is_functionlike(obj): # If it's a pure Python function, or an object that is duck type @@ -2463,11 +2457,10 @@ def __init__(self, name, kind, *, default=_empty, annotation=_empty): self._kind = _ParameterKind(kind) except ValueError: raise ValueError(f'value {kind!r} is not a valid Parameter.kind') - if default is not _empty: - if self._kind in (_VAR_POSITIONAL, _VAR_KEYWORD): - msg = '{} parameters cannot have default values' - msg = msg.format(self._kind.description) - raise ValueError(msg) + if default is not _empty and self._kind in (_VAR_POSITIONAL, _VAR_KEYWORD): + msg = '{} parameters cannot have default values' + msg = msg.format(self._kind.description) + raise ValueError(msg) self._default = default self._annotation = annotation @@ -2705,9 +2698,7 @@ def __getstate__(self): return {'_signature': self._signature, 'arguments': self.arguments} def __repr__(self): - args = [] - for arg, value in self.arguments.items(): - args.append('{}={!r}'.format(arg, value)) + args = ['{}={!r}'.format(arg, value) for arg, value in self.arguments.items()] return '<{} ({})>'.format(self.__class__.__name__, ', '.join(args)) @@ -2933,8 +2924,7 @@ def _bind(self, args, kwargs, *, partial=False): # We have an '*args'-like argument, let's fill it with # all positional arguments we have left and move on to # the next phase - values = [arg_val] - values.extend(arg_vals) + values = [arg_val, *arg_vals] arguments[param.name] = tuple(values) break diff --git a/Lib/ipaddress.py b/Lib/ipaddress.py index 15507d61dec8f96..397211f75685361 100644 --- a/Lib/ipaddress.py +++ b/Lib/ipaddress.py @@ -769,7 +769,7 @@ def address_exclude(self, other): ValueError: If other is not completely contained by self. """ - if not self._version == other._version: + if self._version != other._version: raise TypeError("%s and %s are not of the same version" % ( self, other)) @@ -1209,10 +1209,7 @@ def _is_valid_netmask(self, netmask): except ValueError: # Found something that isn't an integer or isn't valid return False - for idx, y in enumerate(mask): - if idx > 0 and y > mask[idx - 1]: - return False - return True + return not any(idx > 0 and y > mask[idx - 1] for idx, y in enumerate(mask)) try: netmask = int(netmask) except ValueError: @@ -1236,9 +1233,7 @@ def _is_hostmask(self, ip_str): return False if len(parts) != len(bits): return False - if parts[0] < parts[-1]: - return True - return False + return parts[0] < parts[-1] def _reverse_pointer(self): """Return the reverse DNS pointer name for the IPv4 address. @@ -1386,11 +1381,7 @@ def __init__(self, address): if isinstance(address, tuple): IPv4Address.__init__(self, address[0]) - if len(address) > 1: - self._prefixlen = int(address[1]) - else: - self._prefixlen = self._max_prefixlen - + self._prefixlen = int(address[1]) if len(address) > 1 else self._max_prefixlen self.network = IPv4Network(address, strict=False) self.netmask = self.network.netmask self.hostmask = self.network.hostmask @@ -1550,9 +1541,10 @@ def is_global(self): iana-ipv4-special-registry. """ - return (not (self.network_address in IPv4Network('100.64.0.0/10') and - self.broadcast_address in IPv4Network('100.64.0.0/10')) and - not self.is_private) + return ( + self.network_address not in IPv4Network('100.64.0.0/10') + or self.broadcast_address not in IPv4Network('100.64.0.0/10') + ) and not self.is_private class _IPv4Constants: @@ -2063,10 +2055,7 @@ def __init__(self, address): return if isinstance(address, tuple): IPv6Address.__init__(self, address[0]) - if len(address) > 1: - self._prefixlen = int(address[1]) - else: - self._prefixlen = self._max_prefixlen + self._prefixlen = int(address[1]) if len(address) > 1 else self._max_prefixlen self.network = IPv6Network(address, strict=False) self.netmask = self.network.netmask self.hostmask = self.network.hostmask diff --git a/Lib/keyword.py b/Lib/keyword.py index 431991dcf4ace65..407fde72dd83dda 100755 --- a/Lib/keyword.py +++ b/Lib/keyword.py @@ -59,9 +59,7 @@ def main(): args = sys.argv[1:] iptfile = args and args[0] or "Python/graminit.c" - if len(args) > 1: optfile = args[1] - else: optfile = "Lib/keyword.py" - + optfile = args[1] if len(args) > 1 else "Lib/keyword.py" # load the output skeleton from the target, taking care to preserve its # newline convention. with open(optfile, newline='') as fp: diff --git a/Lib/linecache.py b/Lib/linecache.py index 3afcce1f0a14566..3bef236c8ecad1a 100644 --- a/Lib/linecache.py +++ b/Lib/linecache.py @@ -41,8 +41,7 @@ def getlines(filename, module_globals=None): if filename in cache: entry = cache[filename] if len(entry) != 1: - return cache[filename][2] - + return entry[2] try: return updatecache(filename, module_globals) except MemoryError: @@ -84,9 +83,8 @@ def updatecache(filename, module_globals=None): If something's wrong, print a message, discard the cache entry, and return an empty list.""" - if filename in cache: - if len(cache[filename]) != 1: - del cache[filename] + if filename in cache and len(cache[filename]) != 1: + del cache[filename] if not filename or (filename.startswith('<') and filename.endswith('>')): return [] @@ -158,10 +156,7 @@ def lazycache(filename, module_globals): filename, and the filename must not be already cached. """ if filename in cache: - if len(cache[filename]) == 1: - return True - else: - return False + return len(cache[filename]) == 1 if not filename or (filename.startswith('<') and filename.endswith('>')): return False # Try for a __loader__, if available diff --git a/Lib/locale.py b/Lib/locale.py index f3d3973d038c518..aa4b434408c97d6 100644 --- a/Lib/locale.py +++ b/Lib/locale.py @@ -214,8 +214,8 @@ def format_string(f, val, grouping=False, monetary=False): percents = list(_percent_re.finditer(f)) new_f = _percent_re.sub('%s', f) + new_val = [] if isinstance(val, _collections_abc.Mapping): - new_val = [] for perc in percents: if perc.group()[-1]=='%': new_val.append('%') @@ -224,7 +224,6 @@ def format_string(f, val, grouping=False, monetary=False): else: if not isinstance(val, tuple): val = (val,) - new_val = [] i = 0 for perc in percents: if perc.group()[-1]=='%': @@ -348,10 +347,7 @@ def _test(): _setlocale = setlocale def _replace_encoding(code, encoding): - if '.' in code: - langname = code[:code.index('.')] - else: - langname = code + langname = code[:code.index('.')] if '.' in code else code # Convert the encoding to a C lib compatible encoding string norm_encoding = encodings.normalize_encoding(encoding) #print('norm encoding: %r' % norm_encoding) diff --git a/Lib/macpath.py b/Lib/macpath.py index aacf7235b011fd0..45b4d1073dc79df 100644 --- a/Lib/macpath.py +++ b/Lib/macpath.py @@ -88,7 +88,7 @@ def split(s): for i in range(len(s)): if s[i:i+1] == colon: col = i + 1 path, file = s[:col-1], s[col:] - if path and not colon in path: + if path and colon not in path: path = path + colon return path, file @@ -167,14 +167,13 @@ def normpath(s): i = 1 while i < len(comps)-1: if not comps[i] and comps[i-1]: - if i > 1: - del comps[i-1:i+1] - i = i - 1 - else: + if i <= 1: # best way to handle this is to raise an exception raise norm_error('Cannot use :: immediately after volume name') + del comps[i-1:i+1] + i -= 1 else: - i = i + 1 + i += 1 s = colon.join(comps) @@ -186,10 +185,7 @@ def normpath(s): def abspath(path): """Return an absolute path.""" if not isabs(path): - if isinstance(path, bytes): - cwd = os.getcwdb() - else: - cwd = os.getcwd() + cwd = os.getcwdb() if isinstance(path, bytes) else os.getcwd() path = join(cwd, path) return normpath(path) diff --git a/Lib/mailbox.py b/Lib/mailbox.py index 056251dce0ada3c..a9008b4667044cd 100644 --- a/Lib/mailbox.py +++ b/Lib/mailbox.py @@ -275,12 +275,11 @@ def __init__(self, dirname, factory=None, create=True): 'cur': os.path.join(self._path, 'cur'), } if not os.path.exists(self._path): - if create: - os.mkdir(self._path, 0o700) - for path in self._paths.values(): - os.mkdir(path, 0o700) - else: + if not create: raise NoSuchMailboxError(self._path) + os.mkdir(self._path, 0o700) + for path in self._paths.values(): + os.mkdir(path, 0o700) self._toc = {} self._toc_mtimes = {'cur': 0, 'new': 0} self._last_read = 0 # Records last time we read cur/new @@ -371,10 +370,7 @@ def get_message(self, key): """Return a Message representation or raise a KeyError.""" subpath = self._lookup(key) with open(os.path.join(self._path, subpath), 'rb') as f: - if self._factory: - msg = self._factory(f) - else: - msg = MaildirMessage(f) + msg = self._factory(f) if self._factory else MaildirMessage(f) subdir, name = os.path.split(subpath) msg.set_subdir(subdir) if self.colon in name: @@ -432,12 +428,13 @@ def close(self): def list_folders(self): """Return a list of folder names.""" - result = [] - for entry in os.listdir(self._path): - if len(entry) > 1 and entry[0] == '.' and \ - os.path.isdir(os.path.join(self._path, entry)): - result.append(entry[1:]) - return result + return [ + entry[1:] + for entry in os.listdir(self._path) + if len(entry) > 1 + and entry[0] == '.' + and os.path.isdir(os.path.join(self._path, entry)) + ] def get_folder(self, folder): """Return a Maildir instance for the named folder.""" @@ -936,21 +933,17 @@ def __init__(self, path, factory=None, create=True): """Initialize an MH instance.""" Mailbox.__init__(self, path, factory, create) if not os.path.exists(self._path): - if create: - os.mkdir(self._path, 0o700) - os.close(os.open(os.path.join(self._path, '.mh_sequences'), - os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) - else: + if not create: raise NoSuchMailboxError(self._path) + os.mkdir(self._path, 0o700) + os.close(os.open(os.path.join(self._path, '.mh_sequences'), + os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)) self._locked = False def add(self, message): """Add message and return assigned key.""" keys = self.keys() - if len(keys) == 0: - new_key = 1 - else: - new_key = max(keys) + 1 + new_key = 1 if len(keys) == 0 else max(keys) + 1 new_path = os.path.join(self._path, str(new_key)) f = _create_carefully(new_path) closed = False @@ -1112,11 +1105,11 @@ def close(self): def list_folders(self): """Return a list of folder names.""" - result = [] - for entry in os.listdir(self._path): - if os.path.isdir(os.path.join(self._path, entry)): - result.append(entry) - return result + return [ + entry + for entry in os.listdir(self._path) + if os.path.isdir(os.path.join(self._path, entry)) + ] def get_folder(self, folder): """Return an MH instance for the named folder.""" @@ -1134,9 +1127,7 @@ def remove_folder(self, folder): entries = os.listdir(path) if entries == ['.mh_sequences']: os.remove(os.path.join(path, '.mh_sequences')) - elif entries == []: - pass - else: + elif entries != []: raise NotEmptyError('Folder not empty: %s' % self._path) os.rmdir(path) @@ -1157,7 +1148,7 @@ def get_sequences(self): keys.update(range(start, stop + 1)) results[name] = [key for key in sorted(keys) \ if key in all_keys] - if len(results[name]) == 0: + if not results[name]: del results[name] except ValueError: raise FormatError('Invalid sequence specification: %s' % @@ -1211,7 +1202,7 @@ def pack(self): os.unlink(os.path.join(self._path, str(key))) prev += 1 self._next_key = prev + 1 - if len(changes) == 0: + if not changes: return for name, key_list in sequences.items(): for old, new in changes: @@ -1345,7 +1336,7 @@ def _generate_toc(self): in self._file.readline()[1:].split(b',') if label.strip()] label_lists.append(labels) - elif line == b'\037' or line == b'\037' + linesep: + elif line in [b'\037', b'\037' + linesep]: if len(stops) < len(starts): stops.append(line_pos - len(linesep)) elif not line: @@ -1435,7 +1426,7 @@ def _install_message(self, message): if isinstance(message, str): message = self._string_to_bytes(message) body_start = message.find(b'\n\n') + 2 - if body_start - 2 != -1: + if body_start != 1: self._file.write(message[:body_start].replace(b'\n', linesep)) self._file.write(b'*** EOOH ***' + linesep) self._file.write(message[:body_start].replace(b'\n', linesep)) @@ -1459,12 +1450,11 @@ def _install_message(self, message): line = line[:-1] + b'\n' self._file.write(line.replace(b'\n', linesep)) if line == b'\n' or not line: - if first_pass: - first_pass = False - self._file.write(b'*** EOOH ***' + linesep) - message.seek(original_pos) - else: + if not first_pass: break + first_pass = False + self._file.write(b'*** EOOH ***' + linesep) + message.seek(original_pos) while True: line = message.readline() if not line: @@ -1472,9 +1462,13 @@ def _install_message(self, message): # Universal newline support. if line.endswith(b'\r\n'): line = line[:-2] + linesep - elif line.endswith(b'\r'): - line = line[:-1] + linesep - elif line.endswith(b'\n'): + elif ( + not line.endswith(b'\r\n') + and line.endswith(b'\r') + or not line.endswith(b'\r\n') + and not line.endswith(b'\r') + and line.endswith(b'\n') + ): line = line[:-1] + linesep self._file.write(line) else: @@ -1538,7 +1532,7 @@ def get_subdir(self): def set_subdir(self, subdir): """Set subdir to 'new' or 'cur'.""" - if subdir == 'new' or subdir == 'cur': + if subdir in ['new', 'cur']: self._subdir = subdir else: raise ValueError("subdir must be 'new' or 'cur': %s" % subdir) @@ -1622,9 +1616,7 @@ def _explain_to(self, message): message.add_label('answered') if 'P' in flags: message.add_label('forwarded') - elif isinstance(message, Message): - pass - else: + elif not isinstance(message, Message): raise TypeError('Cannot convert to specified type: %s' % type(message)) @@ -1735,9 +1727,7 @@ def _explain_to(self, message): message.add_label('answered') del message['status'] del message['x-status'] - elif isinstance(message, Message): - pass - else: + elif not isinstance(message, Message): raise TypeError('Cannot convert to specified type: %s' % type(message)) @@ -1767,7 +1757,7 @@ def set_sequences(self, sequences): def add_sequence(self, sequence): """Add sequence to list of sequences including the message.""" if isinstance(sequence, str): - if not sequence in self._sequences: + if sequence not in self._sequences: self._sequences.append(sequence) else: raise TypeError('sequence type must be str: %s' % type(sequence)) @@ -1811,9 +1801,7 @@ def _explain_to(self, message): message.add_label('unseen') if 'replied' in sequences: message.add_label('answered') - elif isinstance(message, Message): - pass - else: + elif not isinstance(message, Message): raise TypeError('Cannot convert to specified type: %s' % type(message)) @@ -1906,9 +1894,7 @@ def _explain_to(self, message): message.set_visible(self.get_visible()) for label in self.get_labels(): message.add_label(label) - elif isinstance(message, Message): - pass - else: + elif not isinstance(message, Message): raise TypeError('Cannot convert to specified type: %s' % type(message)) @@ -1923,10 +1909,7 @@ class _ProxyFile: def __init__(self, f, pos=None): """Initialize a _ProxyFile.""" self._file = f - if pos is None: - self._pos = f.tell() - else: - self._pos = pos + self._pos = f.tell() if pos is None else pos def read(self, size=None): """Read bytes.""" diff --git a/Lib/mailcap.py b/Lib/mailcap.py index bd0fc0981c8c6d7..e9dfd9d972cf1e0 100644 --- a/Lib/mailcap.py +++ b/Lib/mailcap.py @@ -36,10 +36,7 @@ def getcaps(): with fp: morecaps, lineno = _readmailcapfile(fp, lineno) for key, value in morecaps.items(): - if not key in caps: - caps[key] = value - else: - caps[key] = caps[key] + value + caps[key] = value if key not in caps else caps[key] + value return caps def listmailcapfiles(): @@ -179,11 +176,11 @@ def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]): def lookup(caps, MIMEtype, key=None): entries = [] if MIMEtype in caps: - entries = entries + caps[MIMEtype] + entries += caps[MIMEtype] MIMEtypes = MIMEtype.split('/') MIMEtype = MIMEtypes[0] + '/*' if MIMEtype in caps: - entries = entries + caps[MIMEtype] + entries += caps[MIMEtype] if key is not None: entries = [e for e in entries if key in e] entries = sorted(entries, key=lineno_sort_key) diff --git a/Lib/mimetypes.py b/Lib/mimetypes.py index f25872102b8c279..2b354176a2e8d2c 100644 --- a/Lib/mimetypes.py +++ b/Lib/mimetypes.py @@ -126,10 +126,7 @@ def guess_type(self, url, strict=True): # bad data URL return None, None semi = url.find(';', 0, comma) - if semi >= 0: - type = url[:semi] - else: - type = url[:comma] + type = url[:semi] if semi >= 0 else url[:comma] if '=' in type or '/' not in type: type = 'text/plain' return type, None # never compressed, so encoding is None diff --git a/Lib/modulefinder.py b/Lib/modulefinder.py index 10320a74d94249c..d20586c1f147ca3 100644 --- a/Lib/modulefinder.py +++ b/Lib/modulefinder.py @@ -83,7 +83,7 @@ def __init__(self, path=None, debug=0, excludes=[], replace_paths=[]): def msg(self, level, str, *args): if level <= self.debug: - for i in range(self.indent): + for _ in range(self.indent): print(" ", end=' ') print(str, end=' ') for arg in args: @@ -170,10 +170,7 @@ def find_head_package(self, parent, name): else: head = name tail = "" - if parent: - qname = "%s.%s" % (parent.__name__, head) - else: - qname = head + qname = "%s.%s" % (parent.__name__, head) if parent else head q = self.import_module(head, qname, parent) if q: self.msgout(4, "find_head_package ->", (q, tail)) @@ -416,7 +413,7 @@ def load_package(self, fqname, pathname): m.__path__ = [pathname] # As per comment at top of file, simulate runtime __path__ additions. - m.__path__ = m.__path__ + packagePathMap.get(fqname, []) + m.__path__ += packagePathMap.get(fqname, []) fp, buf, stuff = self.find_module("__init__", m.__path__) try: @@ -583,22 +580,18 @@ def test(): exclude = [] for o, a in opts: if o == '-d': - debug = debug + 1 - if o == '-m': + debug += 1 + elif o == '-m': domods = 1 if o == '-p': - addpath = addpath + a.split(os.pathsep) + addpath += a.split(os.pathsep) if o == '-q': debug = 0 - if o == '-x': + elif o == '-x': exclude.append(a) # Provide default arguments - if not args: - script = "hello.py" - else: - script = args[0] - + script = "hello.py" if not args else args[0] # Set the path based on sys.path and the script directory path = sys.path[:] path[0] = os.path.dirname(script) diff --git a/Lib/netrc.py b/Lib/netrc.py index f0ae48cfed9e67e..5b0cf6818522bb4 100644 --- a/Lib/netrc.py +++ b/Lib/netrc.py @@ -70,16 +70,15 @@ def _parse(self, file, fp, default_netrc): tt = lexer.get_token() if (tt.startswith('#') or tt in {'', 'machine', 'default', 'macdef'}): - if password: - self.hosts[entryname] = (login, account, password) - lexer.push_token(tt) - break - else: + if not password: raise NetrcParseError( "malformed %s entry %s terminated by %s" % (toplevel, entryname, repr(tt)), file, lexer.lineno) - elif tt == 'login' or tt == 'user': + self.hosts[entryname] = (login, account, password) + lexer.push_token(tt) + break + elif tt in ['login', 'user']: login = lexer.get_token() elif tt == 'account': account = lexer.get_token() diff --git a/Lib/nntplib.py b/Lib/nntplib.py index 5961a28ab7d9bc9..fb354cb84009096 100644 --- a/Lib/nntplib.py +++ b/Lib/nntplib.py @@ -601,10 +601,7 @@ def list(self, group_pattern=None, *, file=None): - resp: server response if successful - list: list of (group, last, first, flag) (strings) """ - if group_pattern is not None: - command = 'LIST ACTIVE ' + group_pattern - else: - command = 'LIST' + command = 'LIST' if group_pattern is None else 'LIST ACTIVE ' + group_pattern resp, lines = self._longcmdstring(command, file) return resp, self._grouplist(lines) @@ -735,10 +732,7 @@ def head(self, message_spec=None, *, file=None): - resp: server response if successful - ArticleInfo: (article number, message id, list of header lines) """ - if message_spec is not None: - cmd = 'HEAD {0}'.format(message_spec) - else: - cmd = 'HEAD' + cmd = 'HEAD {0}'.format(message_spec) if message_spec is not None else 'HEAD' return self._artcmd(cmd, file) def body(self, message_spec=None, *, file=None): @@ -749,10 +743,7 @@ def body(self, message_spec=None, *, file=None): - resp: server response if successful - ArticleInfo: (article number, message id, list of body lines) """ - if message_spec is not None: - cmd = 'BODY {0}'.format(message_spec) - else: - cmd = 'BODY' + cmd = 'BODY {0}'.format(message_spec) if message_spec is not None else 'BODY' return self._artcmd(cmd, file) def article(self, message_spec=None, *, file=None): @@ -763,10 +754,7 @@ def article(self, message_spec=None, *, file=None): - resp: server response if successful - ArticleInfo: (article number, message id, list of article lines) """ - if message_spec is not None: - cmd = 'ARTICLE {0}'.format(message_spec) - else: - cmd = 'ARTICLE' + cmd = 'ARTICLE' if message_spec is None else 'ARTICLE {0}'.format(message_spec) return self._artcmd(cmd, file) def slave(self): @@ -963,10 +951,9 @@ def login(self, user=None, password=None, usenetrc=True): if resp.startswith('381'): if not password: raise NNTPReplyError(resp) - else: - resp = self._shortcmd('authinfo pass ' + password) - if not resp.startswith('281'): - raise NNTPPermanentError(resp) + resp = self._shortcmd('authinfo pass ' + password) + if not resp.startswith('281'): + raise NNTPPermanentError(resp) # Capabilities might have changed after login self._caps = None self.getcapabilities() diff --git a/Lib/ntpath.py b/Lib/ntpath.py index 2182ec776cc5035..86fd31f188c08da 100644 --- a/Lib/ntpath.py +++ b/Lib/ntpath.py @@ -289,10 +289,7 @@ def expanduser(path): If user or $HOME is unknown, do nothing.""" path = os.fspath(path) - if isinstance(path, bytes): - tilde = b'~' - else: - tilde = '~' + tilde = b'~' if isinstance(path, bytes) else '~' if not path.startswith(tilde): return path i, n = 1, len(path) @@ -303,7 +300,7 @@ def expanduser(path): userhome = os.environ['HOME'] elif 'USERPROFILE' in os.environ: userhome = os.environ['USERPROFILE'] - elif not 'HOMEPATH' in os.environ: + elif 'HOMEPATH' not in os.environ: return path else: try: @@ -506,10 +503,7 @@ def abspath(path): """Return the absolute version of a path.""" path = os.fspath(path) if not isabs(path): - if isinstance(path, bytes): - cwd = os.getcwdb() - else: - cwd = os.getcwd() + cwd = os.getcwdb() if isinstance(path, bytes) else os.getcwd() path = join(cwd, path) return normpath(path) @@ -612,14 +606,14 @@ def commonpath(paths): split_paths = [p.split(sep) for d, p in drivesplits] try: - isabs, = set(p[:1] == sep for d, p in drivesplits) + isabs, = {p[:1] == sep for d, p in drivesplits} except ValueError: raise ValueError("Can't mix absolute and relative paths") from None # Check that all drive letters or UNC paths match. The check is made only # now otherwise type errors for mixing strings and bytes would not be # caught. - if len(set(d for d, p in drivesplits)) != 1: + if len({d for d, p in drivesplits}) != 1: raise ValueError("Paths don't have the same drive") drive, path = splitdrive(paths[0].replace(altsep, sep)) diff --git a/Lib/nturl2path.py b/Lib/nturl2path.py index 853e6608380e92d..516ef17270abd5f 100644 --- a/Lib/nturl2path.py +++ b/Lib/nturl2path.py @@ -17,7 +17,7 @@ def url2pathname(url): import string, urllib.parse # Windows itself uses ":" even in URLs. url = url.replace(':', '|') - if not '|' in url: + if '|' not in url: # No drive specifier, just convert slashes if url[:4] == '////': # path is something like ////host/path/on/remote/host @@ -50,7 +50,7 @@ def pathname2url(p): # becomes # ///C:/foo/bar/spam.foo import urllib.parse - if not ':' in p: + if ':' not in p: # No drive specifier, just convert slashes and quote the name if p[:2] == '\\\\': # path is something like \\host\path\on\remote\host diff --git a/Lib/operator.py b/Lib/operator.py index 0e2e53efc69a77d..be61e34c9bcc510 100644 --- a/Lib/operator.py +++ b/Lib/operator.py @@ -56,7 +56,7 @@ def not_(a): def truth(a): "Return True if a is true, False otherwise." - return True if a else False + return bool(a) def is_(a, b): "Same as a is b." @@ -156,11 +156,7 @@ def contains(a, b): def countOf(a, b): "Return the number of times b occurs in a." - count = 0 - for i in a: - if i == b: - count += 1 - return count + return a.count(b) def delitem(a, b): "Same as del a[b]." @@ -317,8 +313,7 @@ def __call__(self, obj): return getattr(obj, self._name)(*self._args, **self._kwargs) def __repr__(self): - args = [repr(self._name)] - args.extend(map(repr, self._args)) + args = [repr(self._name), *map(repr, self._args)] args.extend('%s=%r' % (k, v) for k, v in self._kwargs.items()) return '%s.%s(%s)' % (self.__class__.__module__, self.__class__.__name__, @@ -327,9 +322,8 @@ def __repr__(self): def __reduce__(self): if not self._kwargs: return self.__class__, (self._name,) + self._args - else: - from functools import partial - return partial(self.__class__, self._name, **self._kwargs), self._args + from functools import partial + return partial(self.__class__, self._name, **self._kwargs), self._args # In-place Operations *********************************************************# diff --git a/Lib/optparse.py b/Lib/optparse.py index e8ac1e156a2b29c..379b5989539fea0 100644 --- a/Lib/optparse.py +++ b/Lib/optparse.py @@ -358,11 +358,7 @@ def format_option_strings(self, option): short_opts = option._short_opts long_opts = option._long_opts - if self.short_first: - opts = short_opts + long_opts - else: - opts = long_opts + short_opts - + opts = short_opts + long_opts if self.short_first else long_opts + short_opts return ", ".join(opts) class IndentedHelpFormatter (HelpFormatter): @@ -435,11 +431,10 @@ def check_builtin(option, opt, value): def check_choice(option, opt, value): if value in option.choices: return value - else: - choices = ", ".join(map(repr, option.choices)) - raise OptionValueError( - _("option %s: invalid choice: %r (choose from %s)") - % (opt, value, choices)) + choices = ", ".join(map(repr, option.choices)) + raise OptionValueError( + _("option %s: invalid choice: %r (choose from %s)") + % (opt, value, choices)) # Not supplying a default is different from a default of None, # so we need an explicit "not supplied" value. @@ -596,14 +591,14 @@ def _set_opt_strings(self, opts): "invalid option string %r: " "must be at least two characters long" % opt, self) elif len(opt) == 2: - if not (opt[0] == "-" and opt[1] != "-"): + if opt[0] != "-" or opt[1] == "-": raise OptionError( "invalid short option string %r: " "must be of the form -x, (x any non-dash char)" % opt, self) self._short_opts.append(opt) else: - if not (opt[0:2] == "--" and opt[2] != "-"): + if opt[0:2] != "--" or opt[2] == "-": raise OptionError( "invalid long option string %r: " "must start with --, followed by non-dash" % opt, @@ -770,7 +765,7 @@ def convert_value(self, opt, value): if self.nargs == 1: return self.check_value(opt, value) else: - return tuple([self.check_value(opt, v) for v in value]) + return tuple(self.check_value(opt, v) for v in value) def process(self, opt, value, values, parser): @@ -966,10 +961,12 @@ def destroy(self): # -- Option-adding methods ----------------------------------------- def _check_conflict(self, option): - conflict_opts = [] - for opt in option._short_opts: - if opt in self._short_opt: - conflict_opts.append((opt, self._short_opt[opt])) + conflict_opts = [ + (opt, self._short_opt[opt]) + for opt in option._short_opts + if opt in self._short_opt + ] + for opt in option._long_opts: if opt in self._long_opt: conflict_opts.append((opt, self._long_opt[opt])) @@ -978,9 +975,13 @@ def _check_conflict(self, option): handler = self.conflict_handler if handler == "error": raise OptionConflictError( - "conflicting option string(s): %s" - % ", ".join([co[0] for co in conflict_opts]), - option) + ( + "conflicting option string(s): %s" + % ", ".join(co[0] for co in conflict_opts) + ), + option, + ) + elif handler == "resolve": for (opt, c_option) in conflict_opts: if opt.startswith("--"): @@ -1055,10 +1056,12 @@ def remove_option(self, opt_str): def format_option_help(self, formatter): if not self.option_list: return "" - result = [] - for option in self.option_list: - if not option.help is SUPPRESS_HELP: - result.append(formatter.format_option(option)) + result = [ + formatter.format_option(option) + for option in self.option_list + if option.help is not SUPPRESS_HELP + ] + return "".join(result) def format_description(self, formatter): @@ -1608,8 +1611,7 @@ def format_option_help(self, formatter=None): if formatter is None: formatter = self.formatter formatter.store_option_strings(self) - result = [] - result.append(formatter.format_heading(_("Options"))) + result = [formatter.format_heading(_("Options"))] formatter.indent() if self.option_list: result.append(OptionContainer.format_option_help(self, formatter)) @@ -1659,19 +1661,18 @@ def _match_abbrev(s, wordmap): # Is there an exact match? if s in wordmap: return s + # Isolate all words with s as a prefix. + possibilities = [word for word in wordmap.keys() + if word.startswith(s)] + # No exact match, so there had better be just one possibility. + if len(possibilities) == 1: + return possibilities[0] + elif not possibilities: + raise BadOptionError(s) else: - # Isolate all words with s as a prefix. - possibilities = [word for word in wordmap.keys() - if word.startswith(s)] - # No exact match, so there had better be just one possibility. - if len(possibilities) == 1: - return possibilities[0] - elif not possibilities: - raise BadOptionError(s) - else: - # More than one possible completion: ambiguous prefix. - possibilities.sort() - raise AmbiguousOptionError(s, possibilities) + # More than one possible completion: ambiguous prefix. + possibilities.sort() + raise AmbiguousOptionError(s, possibilities) # Some day, there might be many Option classes. As of Optik 1.3, the diff --git a/Lib/pathlib.py b/Lib/pathlib.py index 8431c29c1d6516f..2096ec52040aaf3 100644 --- a/Lib/pathlib.py +++ b/Lib/pathlib.py @@ -182,19 +182,18 @@ def resolve(self, path, strict=False): if _getfinalpathname is not None: if strict: return self._ext_to_normal(_getfinalpathname(s)) - else: - tail_parts = [] # End of the path after the first one not found - while True: - try: - s = self._ext_to_normal(_getfinalpathname(s)) - except FileNotFoundError: - previous_s = s - s, tail = os.path.split(s) - tail_parts.append(tail) - if previous_s == s: - return path - else: - return os.path.join(s, *reversed(tail_parts)) + tail_parts = [] # End of the path after the first one not found + while True: + try: + s = self._ext_to_normal(_getfinalpathname(s)) + except FileNotFoundError: + previous_s = s + s, tail = os.path.split(s) + tail_parts.append(tail) + if previous_s == s: + return path + else: + return os.path.join(s, *reversed(tail_parts)) # Means fallback on absolute return None @@ -227,15 +226,15 @@ def is_reserved(self, parts): def make_uri(self, path): # Under Windows, file URIs use the UTF-8 encoding. drive = path.drive - if len(drive) == 2 and drive[1] == ':': - # It's a path on a local drive => 'file:///c:/a/b' - rest = path.as_posix()[2:].lstrip('/') - return 'file:///%s/%s' % ( - drive, urlquote_from_bytes(rest.encode('utf-8'))) - else: + if len(drive) != 2 or drive[1] != ':': # It's a path on a network drive => 'file://host/share/a/b' return 'file:' + urlquote_from_bytes(path.as_posix().encode('utf-8')) + # It's a path on a local drive => 'file:///c:/a/b' + rest = path.as_posix()[2:].lstrip('/') + return 'file:///%s/%s' % ( + drive, urlquote_from_bytes(rest.encode('utf-8'))) + def gethomedir(self, username): if 'HOME' in os.environ: userhome = os.environ['HOME'] @@ -276,20 +275,20 @@ class _PosixFlavour(_Flavour): is_supported = (os.name != 'nt') def splitroot(self, part, sep=sep): - if part and part[0] == sep: - stripped_part = part.lstrip(sep) - # According to POSIX path resolution: - # http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11 - # "A pathname that begins with two successive slashes may be - # interpreted in an implementation-defined manner, although more - # than two leading slashes shall be treated as a single slash". - if len(part) - len(stripped_part) == 2: - return '', sep * 2, stripped_part - else: - return '', sep, stripped_part - else: + if not part or part[0] != sep: return '', '', part + stripped_part = part.lstrip(sep) + # According to POSIX path resolution: + # http://pubs.opengroup.org/onlinepubs/009695399/basedefs/xbd_chap04.html#tag_04_11 + # "A pathname that begins with two successive slashes may be + # interpreted in an implementation-defined manner, although more + # than two leading slashes shall be treated as a single slash". + if len(part) - len(stripped_part) == 2: + return '', sep * 2, stripped_part + else: + return '', sep, stripped_part + def casefold(self, s): return s @@ -489,8 +488,7 @@ def _select_from(self, parent_path, is_dir, exists, scandir): try: path = parent_path._make_child_relpath(self.name) if (is_dir if self.dironly else exists)(path): - for p in self.successor._select_from(path, is_dir, exists, scandir): - yield p + yield from self.successor._select_from(path, is_dir, exists, scandir) except PermissionError: return @@ -511,8 +509,7 @@ def _select_from(self, parent_path, is_dir, exists, scandir): casefolded = cf(name) if self.pat.match(casefolded): path = parent_path._make_child_relpath(name) - for p in self.successor._select_from(path, is_dir, exists, scandir): - yield p + yield from self.successor._select_from(path, is_dir, exists, scandir) except PermissionError: return @@ -530,8 +527,7 @@ def _iterate_directories(self, parent_path, is_dir, scandir): for entry in entries: if entry.is_dir() and not entry.is_symlink(): path = parent_path._make_child_relpath(entry.name) - for p in self._iterate_directories(path, is_dir, scandir): - yield p + yield from self._iterate_directories(path, is_dir, scandir) except PermissionError: return @@ -755,8 +751,7 @@ def __ge__(self, other): @property def anchor(self): """The concatenation of the drive and root, or ''.""" - anchor = self._drv + self._root - return anchor + return self._drv + self._root @property def name(self): @@ -818,10 +813,7 @@ def with_suffix(self, suffix): if not name: raise ValueError("%r has an empty name" % (self,)) old_suffix = self.suffix - if not old_suffix: - name = name + suffix - else: - name = name[:-len(old_suffix)] + suffix + name = name + suffix if not old_suffix else name[:-len(old_suffix)] + suffix return self._from_parsed_parts(self._drv, self._root, self._parts[:-1] + [name]) @@ -839,15 +831,9 @@ def relative_to(self, *other): parts = self._parts drv = self._drv root = self._root - if root: - abs_parts = [drv, root] + parts[1:] - else: - abs_parts = parts + abs_parts = [drv, root] + parts[1:] if root else parts to_drv, to_root, to_parts = self._parse_args(other) - if to_root: - to_abs_parts = [to_drv, to_root] + to_parts[1:] - else: - to_abs_parts = to_parts + to_abs_parts = [to_drv, to_root] + to_parts[1:] if to_root else to_parts n = len(to_abs_parts) cf = self._flavour.casefold_parts if (root or drv) if n == 0 else cf(abs_parts[:n]) != cf(to_abs_parts): @@ -930,10 +916,10 @@ def match(self, path_pattern): pat_parts = pat_parts[1:] elif len(pat_parts) > len(parts): return False - for part, pat in zip(reversed(parts), reversed(pat_parts)): - if not fnmatch.fnmatchcase(part, pat): - return False - return True + return all( + fnmatch.fnmatchcase(part, pat) + for part, pat in zip(reversed(parts), reversed(pat_parts)) + ) # Can't subclass os.PathLike from PurePath and keep the constructor # optimizations in PurePath._parse_args(). @@ -992,10 +978,7 @@ def _init(self, template=None, ): self._closed = False - if template is not None: - self._accessor = template._accessor - else: - self._accessor = _normal_accessor + self._accessor = _normal_accessor if template is None else template._accessor def _make_child_relpath(self, part): # This is an optimization used for dir walking. `part` must be @@ -1079,8 +1062,7 @@ def glob(self, pattern): if drv or root: raise NotImplementedError("Non-relative patterns are unsupported") selector = _make_selector(tuple(pattern_parts)) - for p in selector.select_from(self): - yield p + yield from selector.select_from(self) def rglob(self, pattern): """Recursively yield all existing files (of any kind, including @@ -1091,8 +1073,7 @@ def rglob(self, pattern): if drv or root: raise NotImplementedError("Non-relative patterns are unsupported") selector = _make_selector(("**",) + tuple(pattern_parts)) - for p in selector.select_from(self): - yield p + yield from selector.select_from(self) def absolute(self): """Return an absolute version of this path. This function works @@ -1438,8 +1419,12 @@ def expanduser(self): """ Return a new path with expanded ~ and ~user constructs (as returned by os.path.expanduser) """ - if (not (self._drv or self._root) and - self._parts and self._parts[0][:1] == '~'): + if ( + not self._drv + and not self._root + and self._parts + and self._parts[0][:1] == '~' + ): homedir = self._flavour.gethomedir(self._parts[0][1:]) return self._from_parts([homedir] + self._parts[1:]) diff --git a/Lib/pdb.py b/Lib/pdb.py index 60bdb7675c81316..b6e0d80ed9470b1 100755 --- a/Lib/pdb.py +++ b/Lib/pdb.py @@ -231,13 +231,12 @@ def execRcLines(self): self.rcLines = [] while rcLines: line = rcLines.pop().strip() - if line and line[0] != '#': - if self.onecmd(line): - # if onecmd returns True, the command wants to exit - # from the interaction, save leftover rc lines - # to execute before next interaction - self.rcLines += reversed(rcLines) - return True + if line and line[0] != '#' and self.onecmd(line): + # if onecmd returns True, the command wants to exit + # from the interaction, save leftover rc lines + # to execute before next interaction + self.rcLines += reversed(rcLines) + return True # Override Bdb methods @@ -267,22 +266,24 @@ def bp_commands(self, frame): Returns True if the normal interaction function must be called, False otherwise.""" # self.currentbp is set in bdb in Bdb.break_here if a breakpoint was hit - if getattr(self, "currentbp", False) and \ - self.currentbp in self.commands: - currentbp = self.currentbp - self.currentbp = 0 - lastcmd_back = self.lastcmd - self.setup(frame, None) - for line in self.commands[currentbp]: - self.onecmd(line) - self.lastcmd = lastcmd_back - if not self.commands_silent[currentbp]: - self.print_stack_entry(self.stack[self.curindex]) - if self.commands_doprompt[currentbp]: - self._cmdloop() - self.forget() - return - return 1 + if ( + not getattr(self, "currentbp", False) + or self.currentbp not in self.commands + ): + return 1 + currentbp = self.currentbp + self.currentbp = 0 + lastcmd_back = self.lastcmd + self.setup(frame, None) + for line in self.commands[currentbp]: + self.onecmd(line) + self.lastcmd = lastcmd_back + if not self.commands_silent[currentbp]: + self.print_stack_entry(self.stack[self.curindex]) + if self.commands_doprompt[currentbp]: + self._cmdloop() + self.forget() + return def user_return(self, frame, return_value): """This function is called when a return trap is set here.""" @@ -389,11 +390,9 @@ def precmd(self, line): args = line.split() while args[0] in self.aliases: line = self.aliases[args[0]] - ii = 1 - for tmpArg in args[1:]: + for ii, tmpArg in enumerate(args[1:], start=1): line = line.replace("%" + str(ii), tmpArg) - ii += 1 line = line.replace("%*", ' '.join(args[1:])) args = line.split() # split into ';;' separated commands @@ -493,23 +492,23 @@ def _complete_expression(self, text, line, begidx, endidx): # leave them out. ns = self.curframe.f_globals.copy() ns.update(self.curframe_locals) - if '.' in text: - # Walk an attribute chain up to the last part, similar to what - # rlcompleter does. This will bail if any of the parts are not - # simple attribute access, which is what we want. - dotted = text.split('.') - try: - obj = ns[dotted[0]] - for part in dotted[1:-1]: - obj = getattr(obj, part) - except (KeyError, AttributeError): - return [] - prefix = '.'.join(dotted[:-1]) + '.' - return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])] - else: + if '.' not in text: # Complete a simple name. return [n for n in ns.keys() if n.startswith(text)] + # Walk an attribute chain up to the last part, similar to what + # rlcompleter does. This will bail if any of the parts are not + # simple attribute access, which is what we want. + dotted = text.split('.') + try: + obj = ns[dotted[0]] + for part in dotted[1:-1]: + obj = getattr(obj, part) + except (KeyError, AttributeError): + return [] + prefix = '.'.join(dotted[:-1]) + '.' + return [prefix + n for n in dir(obj) if n.startswith(dotted[-1])] + # Command definitions, called by cmdloop() # The argument is the remaining string on the command line # Return true to exit from the command loop @@ -848,10 +847,7 @@ def do_ignore(self, arg): else: bp.ignore = count if count > 0: - if count > 1: - countstr = '%d crossings' % count - else: - countstr = '1 crossing' + countstr = '%d crossings' % count if count > 1 else '1 crossing' self.message('Will ignore next %s of breakpoint %d.' % (countstr, bp.number)) else: @@ -942,10 +938,7 @@ def do_up(self, arg): except ValueError: self.error('Invalid frame count (%s)' % arg) return - if count < 0: - newframe = 0 - else: - newframe = max(0, self.curindex - count) + newframe = 0 if count < 0 else max(0, self.curindex - count) self._select_frame(newframe) do_u = do_up @@ -1284,10 +1277,7 @@ def _print_lines(self, lines, start, breaks=(), frame=None): s = str(lineno).rjust(3) if len(s) < 4: s += ' ' - if lineno in breaks: - s += 'B' - else: - s += ' ' + s += 'B' if lineno in breaks else ' ' if lineno == current_lineno: s += '->' elif lineno == exc_lineno: @@ -1445,10 +1435,7 @@ def print_stack_trace(self): def print_stack_entry(self, frame_lineno, prompt_prefix=line_prefix): frame, lineno = frame_lineno - if frame is self.curframe: - prefix = '> ' - else: - prefix = ' ' + prefix = '> ' if frame is self.curframe else ' ' self.message(prefix + self.format_stack_entry(frame_lineno, prompt_prefix)) diff --git a/setup.py b/setup.py index 170ade81c4f80a9..a72e8d767a6b906 100644 --- a/setup.py +++ b/setup.py @@ -92,11 +92,7 @@ def macosx_sdk_root(): """ cflags = sysconfig.get_config_var('CFLAGS') m = re.search(r'-isysroot\s+(\S+)', cflags) - if m is None: - sysroot = '/' - else: - sysroot = m.group(1) - return sysroot + return '/' if m is None else m.group(1) def is_macosx_sdk_path(path): """ @@ -375,10 +371,9 @@ def print_three_column(lst): def build_extension(self, ext): - if ext.name == '_ctypes': - if not self.configure_ctypes(ext): - self.failed.append(ext.name) - return + if ext.name == '_ctypes' and not self.configure_ctypes(ext): + self.failed.append(ext.name) + return try: build_ext.build_extension(self, ext) @@ -943,9 +938,7 @@ def allow_db_ver(db_ver): Args: db_ver: A tuple of the version to verify. """ - if not (min_db_ver <= db_ver <= max_db_ver): - return False - return True + return min_db_ver <= db_ver <= max_db_ver def gen_db_minor_ver_nums(major): if major == 4: