From 5affd23e6f42125998724787025080a24839266e Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Wed, 5 Apr 2017 09:37:24 +0300 Subject: bpo-29762: More use "raise from None". (#569) This hides unwanted implementation details from tracebacks. --- Lib/_collections_abc.py | 4 ++-- Lib/_weakrefset.py | 2 +- Lib/aifc.py | 8 ++++---- Lib/asyncio/base_events.py | 2 +- Lib/bdb.py | 4 ++-- Lib/chunk.py | 2 +- Lib/configparser.py | 2 +- Lib/copyreg.py | 2 +- Lib/difflib.py | 2 +- Lib/dis.py | 2 +- Lib/json/decoder.py | 3 ++- Lib/json/scanner.py | 2 +- Lib/lib2to3/patcomp.py | 2 +- Lib/lib2to3/pgen2/literals.py | 4 ++-- Lib/lib2to3/refactor.py | 2 +- Lib/locale.py | 3 ++- Lib/mailbox.py | 6 +++--- Lib/multiprocessing/context.py | 2 +- Lib/multiprocessing/pool.py | 6 +++--- Lib/multiprocessing/process.py | 2 +- Lib/netrc.py | 2 +- Lib/nntplib.py | 2 +- Lib/pickle.py | 6 +++--- Lib/shutil.py | 4 ++-- Lib/sysconfig.py | 2 +- Lib/warnings.py | 8 ++++---- Lib/xml/dom/xmlbuilder.py | 2 +- Lib/xml/etree/ElementPath.py | 2 +- Tools/freeze/winmakemakefile.py | 2 +- Tools/pynche/ColorDB.py | 6 +++--- 30 files changed, 50 insertions(+), 48 deletions(-) diff --git a/Lib/_collections_abc.py b/Lib/_collections_abc.py index 005d884..e89e84b 100644 --- a/Lib/_collections_abc.py +++ b/Lib/_collections_abc.py @@ -589,7 +589,7 @@ class MutableSet(Set): try: value = next(it) except StopIteration: - raise KeyError + raise KeyError from None self.discard(value) return value @@ -808,7 +808,7 @@ class MutableMapping(Mapping): try: key = next(iter(self)) except StopIteration: - raise KeyError + raise KeyError from None value = self[key] del self[key] return key, value diff --git a/Lib/_weakrefset.py b/Lib/_weakrefset.py index 7f9923c..4d0de8c 100644 --- a/Lib/_weakrefset.py +++ b/Lib/_weakrefset.py @@ -98,7 +98,7 @@ class WeakSet: try: itemref = self.data.pop() except KeyError: - raise KeyError('pop from empty WeakSet') + raise KeyError('pop from empty WeakSet') from None item = itemref() if item is not None: return item diff --git a/Lib/aifc.py b/Lib/aifc.py index 13ad7dc..49a456a 100644 --- a/Lib/aifc.py +++ b/Lib/aifc.py @@ -149,25 +149,25 @@ def _read_long(file): try: return struct.unpack('>l', file.read(4))[0] except struct.error: - raise EOFError + raise EOFError from None def _read_ulong(file): try: return struct.unpack('>L', file.read(4))[0] except struct.error: - raise EOFError + raise EOFError from None def _read_short(file): try: return struct.unpack('>h', file.read(2))[0] except struct.error: - raise EOFError + raise EOFError from None def _read_ushort(file): try: return struct.unpack('>H', file.read(2))[0] except struct.error: - raise EOFError + raise EOFError from None def _read_string(file): length = ord(file.read(1)) diff --git a/Lib/asyncio/base_events.py b/Lib/asyncio/base_events.py index ee34996..f94ec92 100644 --- a/Lib/asyncio/base_events.py +++ b/Lib/asyncio/base_events.py @@ -1043,7 +1043,7 @@ class BaseEventLoop(events.AbstractEventLoop): except OSError as err: raise OSError(err.errno, 'error while attempting ' 'to bind on address %r: %s' - % (sa, err.strerror.lower())) + % (sa, err.strerror.lower())) from None completed = True finally: if not completed: diff --git a/Lib/bdb.py b/Lib/bdb.py index 67a0846..5a80fa8 100644 --- a/Lib/bdb.py +++ b/Lib/bdb.py @@ -336,11 +336,11 @@ class Bdb: try: number = int(arg) except ValueError: - raise ValueError('Non-numeric breakpoint number %s' % arg) + raise ValueError('Non-numeric breakpoint number %s' % arg) from None try: bp = Breakpoint.bpbynumber[number] except IndexError: - raise ValueError('Breakpoint number %d out of range' % number) + raise ValueError('Breakpoint number %d out of range' % number) from None if bp is None: raise ValueError('Breakpoint %d already deleted' % number) return bp diff --git a/Lib/chunk.py b/Lib/chunk.py index d94dd39..870c39f 100644 --- a/Lib/chunk.py +++ b/Lib/chunk.py @@ -64,7 +64,7 @@ class Chunk: try: self.chunksize = struct.unpack_from(strflag+'L', file.read(4))[0] except struct.error: - raise EOFError + raise EOFError from None if inclheader: self.chunksize = self.chunksize - 8 # subtract header self.size_read = 0 diff --git a/Lib/configparser.py b/Lib/configparser.py index 230ab2b..ea971f3 100644 --- a/Lib/configparser.py +++ b/Lib/configparser.py @@ -1138,7 +1138,7 @@ class RawConfigParser(MutableMapping): sectiondict = self._sections[section] except KeyError: if section != self.default_section: - raise NoSectionError(section) + raise NoSectionError(section) from None # Update with the entry specific variables vardict = {} if vars: diff --git a/Lib/copyreg.py b/Lib/copyreg.py index 67f5bb0..ed29d71 100644 --- a/Lib/copyreg.py +++ b/Lib/copyreg.py @@ -70,7 +70,7 @@ def _reduce_ex(self, proto): except AttributeError: if getattr(self, "__slots__", None): raise TypeError("a class that defines __slots__ without " - "defining __getstate__ cannot be pickled") + "defining __getstate__ cannot be pickled") from None try: dict = self.__dict__ except AttributeError: diff --git a/Lib/difflib.py b/Lib/difflib.py index 2095a5e..8296471 100644 --- a/Lib/difflib.py +++ b/Lib/difflib.py @@ -2079,7 +2079,7 @@ def restore(delta, which): tag = {1: "- ", 2: "+ "}[int(which)] except KeyError: raise ValueError('unknown delta choice (must be 1 or 2): %r' - % which) + % which) from None prefixes = (" ", tag) for line in delta: if line[:2] in prefixes: diff --git a/Lib/dis.py b/Lib/dis.py index 0794b7f..f93d5b2 100644 --- a/Lib/dis.py +++ b/Lib/dis.py @@ -72,7 +72,7 @@ def distb(tb=None, *, file=None): try: tb = sys.last_traceback except AttributeError: - raise RuntimeError("no last traceback to disassemble") + raise RuntimeError("no last traceback to disassemble") from None while tb.tb_next: tb = tb.tb_next disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file) diff --git a/Lib/json/decoder.py b/Lib/json/decoder.py index 2422c6a..3741dee 100644 --- a/Lib/json/decoder.py +++ b/Lib/json/decoder.py @@ -103,7 +103,8 @@ def py_scanstring(s, end, strict=True, try: esc = s[end] except IndexError: - raise JSONDecodeError("Unterminated string starting at", s, begin) + raise JSONDecodeError("Unterminated string starting at", + s, begin) from None # If not a unicode escape sequence, must be in the lookup table if esc != 'u': try: diff --git a/Lib/json/scanner.py b/Lib/json/scanner.py index 86426cd..c451eba 100644 --- a/Lib/json/scanner.py +++ b/Lib/json/scanner.py @@ -29,7 +29,7 @@ def py_make_scanner(context): try: nextchar = string[idx] except IndexError: - raise StopIteration(idx) + raise StopIteration(idx) from None if nextchar == '"': return parse_string(string, idx + 1, strict) diff --git a/Lib/lib2to3/patcomp.py b/Lib/lib2to3/patcomp.py index 06a4b9d..0fefa9a 100644 --- a/Lib/lib2to3/patcomp.py +++ b/Lib/lib2to3/patcomp.py @@ -59,7 +59,7 @@ class PatternCompiler(object): try: root = self.driver.parse_tokens(tokens, debug=debug) except parse.ParseError as e: - raise PatternSyntaxError(str(e)) + raise PatternSyntaxError(str(e)) from None if with_tree: return self.compile_node(root), root else: diff --git a/Lib/lib2to3/pgen2/literals.py b/Lib/lib2to3/pgen2/literals.py index 4f50d31..b9b63e6 100644 --- a/Lib/lib2to3/pgen2/literals.py +++ b/Lib/lib2to3/pgen2/literals.py @@ -29,12 +29,12 @@ def escape(m): try: i = int(hexes, 16) except ValueError: - raise ValueError("invalid hex string escape ('\\%s')" % tail) + raise ValueError("invalid hex string escape ('\\%s')" % tail) from None else: try: i = int(tail, 8) except ValueError: - raise ValueError("invalid octal string escape ('\\%s')" % tail) + raise ValueError("invalid octal string escape ('\\%s')" % tail) from None return chr(i) def evalString(s): diff --git a/Lib/lib2to3/refactor.py b/Lib/lib2to3/refactor.py index c5a1aa2..70b2a00 100644 --- a/Lib/lib2to3/refactor.py +++ b/Lib/lib2to3/refactor.py @@ -248,7 +248,7 @@ class RefactoringTool(object): try: fix_class = getattr(mod, class_name) except AttributeError: - raise FixerError("Can't find %s.%s" % (fix_name, class_name)) + raise FixerError("Can't find %s.%s" % (fix_name, class_name)) from None fixer = fix_class(self.options, self.fixer_log) if fixer.explicit and self.explicit is not True and \ fix_mod_path not in self.explicit: diff --git a/Lib/locale.py b/Lib/locale.py index 73fc94d..5763b14 100644 --- a/Lib/locale.py +++ b/Lib/locale.py @@ -512,7 +512,8 @@ def _build_localename(localetuple): else: return language + '.' + encoding except (TypeError, ValueError): - raise TypeError('Locale must be None, a string, or an iterable of two strings -- language code, encoding.') + raise TypeError('Locale must be None, a string, or an iterable of ' + 'two strings -- language code, encoding.') from None def getdefaultlocale(envvars=('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE')): diff --git a/Lib/mailbox.py b/Lib/mailbox.py index 39f24f9..056251d 100644 --- a/Lib/mailbox.py +++ b/Lib/mailbox.py @@ -555,7 +555,7 @@ class Maildir(Mailbox): try: return self._toc[key] except KeyError: - raise KeyError('No message with key: %s' % key) + raise KeyError('No message with key: %s' % key) from None # This method is for backward compatibility only. def next(self): @@ -741,7 +741,7 @@ class _singlefileMailbox(Mailbox): try: return self._toc[key] except KeyError: - raise KeyError('No message with key: %s' % key) + raise KeyError('No message with key: %s' % key) from None def _append_message(self, message): """Append message to mailbox and return (start, stop) offsets.""" @@ -1572,7 +1572,7 @@ class MaildirMessage(Message): try: self._date = float(date) except ValueError: - raise TypeError("can't convert to float: %s" % date) + raise TypeError("can't convert to float: %s" % date) from None def get_info(self): """Get the message's "info" as a string.""" diff --git a/Lib/multiprocessing/context.py b/Lib/multiprocessing/context.py index 623f6fb..a3d491b 100644 --- a/Lib/multiprocessing/context.py +++ b/Lib/multiprocessing/context.py @@ -189,7 +189,7 @@ class BaseContext(object): try: ctx = _concrete_contexts[method] except KeyError: - raise ValueError('cannot find context for %r' % method) + raise ValueError('cannot find context for %r' % method) from None ctx._check_available() return ctx diff --git a/Lib/multiprocessing/pool.py b/Lib/multiprocessing/pool.py index a545f3c..c2364ab 100644 --- a/Lib/multiprocessing/pool.py +++ b/Lib/multiprocessing/pool.py @@ -720,14 +720,14 @@ class IMapIterator(object): item = self._items.popleft() except IndexError: if self._index == self._length: - raise StopIteration + raise StopIteration from None self._cond.wait(timeout) try: item = self._items.popleft() except IndexError: if self._index == self._length: - raise StopIteration - raise TimeoutError + raise StopIteration from None + raise TimeoutError from None success, value = item if success: diff --git a/Lib/multiprocessing/process.py b/Lib/multiprocessing/process.py index bca8b7a..37365f2 100644 --- a/Lib/multiprocessing/process.py +++ b/Lib/multiprocessing/process.py @@ -199,7 +199,7 @@ class BaseProcess(object): try: return self._sentinel except AttributeError: - raise ValueError("process not started") + raise ValueError("process not started") from None def __repr__(self): if self is _current_process: diff --git a/Lib/netrc.py b/Lib/netrc.py index bbb3d23..aa8eea3 100644 --- a/Lib/netrc.py +++ b/Lib/netrc.py @@ -26,7 +26,7 @@ class netrc: try: file = os.path.join(os.environ['HOME'], ".netrc") except KeyError: - raise OSError("Could not find .netrc: $HOME is not set") + raise OSError("Could not find .netrc: $HOME is not set") from None self.hosts = {} self.macros = {} with open(file) as fp: diff --git a/Lib/nntplib.py b/Lib/nntplib.py index 28cd099..5961a28 100644 --- a/Lib/nntplib.py +++ b/Lib/nntplib.py @@ -866,7 +866,7 @@ class _NNTPBase: try: [resp_num, path] = resp.split() except ValueError: - raise NNTPReplyError(resp) + raise NNTPReplyError(resp) from None else: return resp, path diff --git a/Lib/pickle.py b/Lib/pickle.py index 702b0b3..faa8fd7 100644 --- a/Lib/pickle.py +++ b/Lib/pickle.py @@ -269,7 +269,7 @@ def _getattribute(obj, name): obj = getattr(obj, subpath) except AttributeError: raise AttributeError("Can't get attribute {!r} on {!r}" - .format(name, obj)) + .format(name, obj)) from None return obj, parent def whichmodule(obj, name): @@ -919,7 +919,7 @@ class _Pickler: except (ImportError, KeyError, AttributeError): raise PicklingError( "Can't pickle %r: it's not found as %s.%s" % - (obj, module_name, name)) + (obj, module_name, name)) from None else: if obj2 is not obj: raise PicklingError( @@ -964,7 +964,7 @@ class _Pickler: except UnicodeEncodeError: raise PicklingError( "can't pickle global identifier '%s.%s' using " - "pickle protocol %i" % (module, name, self.proto)) + "pickle protocol %i" % (module, name, self.proto)) from None self.memoize(obj) diff --git a/Lib/shutil.py b/Lib/shutil.py index bd4760f..31536fe 100644 --- a/Lib/shutil.py +++ b/Lib/shutil.py @@ -786,7 +786,7 @@ def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0, try: format_info = _ARCHIVE_FORMATS[format] except KeyError: - raise ValueError("unknown archive format '%s'" % format) + raise ValueError("unknown archive format '%s'" % format) from None func = format_info[0] for arg, val in format_info[1]: @@ -962,7 +962,7 @@ def unpack_archive(filename, extract_dir=None, format=None): try: format_info = _UNPACK_FORMATS[format] except KeyError: - raise ValueError("Unknown unpack format '{0}'".format(format)) + raise ValueError("Unknown unpack format '{0}'".format(format)) from None func = format_info[1] func(filename, extract_dir, **dict(format_info[2])) diff --git a/Lib/sysconfig.py b/Lib/sysconfig.py index 9314e71..ed0a34d 100644 --- a/Lib/sysconfig.py +++ b/Lib/sysconfig.py @@ -147,7 +147,7 @@ def _subst_vars(s, local_vars): try: return s.format(**os.environ) except KeyError as var: - raise AttributeError('{%s}' % var) + raise AttributeError('{%s}' % var) from None def _extend_dict(target_dict, other_dict): target_keys = target_dict.keys() diff --git a/Lib/warnings.py b/Lib/warnings.py index 5badb0b..d7d88d3 100644 --- a/Lib/warnings.py +++ b/Lib/warnings.py @@ -209,7 +209,7 @@ def _setoption(arg): if lineno < 0: raise ValueError except (ValueError, OverflowError): - raise _OptionError("invalid lineno %r" % (lineno,)) + raise _OptionError("invalid lineno %r" % (lineno,)) from None else: lineno = 0 filterwarnings(action, message, category, module, lineno) @@ -233,7 +233,7 @@ def _getcategory(category): try: cat = eval(category) except NameError: - raise _OptionError("unknown warning category: %r" % (category,)) + raise _OptionError("unknown warning category: %r" % (category,)) from None else: i = category.rfind(".") module = category[:i] @@ -241,11 +241,11 @@ def _getcategory(category): try: m = __import__(module, None, None, [klass]) except ImportError: - raise _OptionError("invalid module name: %r" % (module,)) + raise _OptionError("invalid module name: %r" % (module,)) from None try: cat = getattr(m, klass) except AttributeError: - raise _OptionError("unknown warning category: %r" % (category,)) + raise _OptionError("unknown warning category: %r" % (category,)) from None if not issubclass(cat, Warning): raise _OptionError("invalid warning category: %r" % (category,)) return cat diff --git a/Lib/xml/dom/xmlbuilder.py b/Lib/xml/dom/xmlbuilder.py index e9a1536..60a2bc3 100644 --- a/Lib/xml/dom/xmlbuilder.py +++ b/Lib/xml/dom/xmlbuilder.py @@ -80,7 +80,7 @@ class DOMBuilder: settings = self._settings[(_name_xform(name), state)] except KeyError: raise xml.dom.NotSupportedErr( - "unsupported feature: %r" % (name,)) + "unsupported feature: %r" % (name,)) from None else: for name, value in settings: setattr(self._options, name, value) diff --git a/Lib/xml/etree/ElementPath.py b/Lib/xml/etree/ElementPath.py index ab6b79a..361f6d5 100644 --- a/Lib/xml/etree/ElementPath.py +++ b/Lib/xml/etree/ElementPath.py @@ -80,7 +80,7 @@ def xpath_tokenizer(pattern, namespaces=None): raise KeyError yield token[0], "{%s}%s" % (namespaces[prefix], uri) except KeyError: - raise SyntaxError("prefix %r not found in prefix map" % prefix) + raise SyntaxError("prefix %r not found in prefix map" % prefix) from None else: yield token diff --git a/Tools/freeze/winmakemakefile.py b/Tools/freeze/winmakemakefile.py index 9bb3e6e..e283848 100644 --- a/Tools/freeze/winmakemakefile.py +++ b/Tools/freeze/winmakemakefile.py @@ -39,7 +39,7 @@ def get_custom_entry_point(subsystem): try: return subsystem_details[subsystem][:2] except KeyError: - raise ValueError("The subsystem %s is not known" % subsystem) + raise ValueError("The subsystem %s is not known" % subsystem) from None def makemakefile(outfp, vars, files, target): diff --git a/Tools/pynche/ColorDB.py b/Tools/pynche/ColorDB.py index 0348148..eb76d40 100644 --- a/Tools/pynche/ColorDB.py +++ b/Tools/pynche/ColorDB.py @@ -87,7 +87,7 @@ class ColorDB: try: return self.__byrgb[rgbtuple] except KeyError: - raise BadColor(rgbtuple) + raise BadColor(rgbtuple) from None def find_byname(self, name): """Return (red, green, blue) for name""" @@ -95,7 +95,7 @@ class ColorDB: try: return self.__byname[name] except KeyError: - raise BadColor(name) + raise BadColor(name) from None def nearest(self, red, green, blue): """Return the name of color nearest (red, green, blue)""" @@ -128,7 +128,7 @@ class ColorDB: try: name, aliases = self.__byrgb[(red, green, blue)] except KeyError: - raise BadColor((red, green, blue)) + raise BadColor((red, green, blue)) from None return [name] + aliases -- cgit v0.12