bpo-29762: More use "raise from None". (#569)

This hides unwanted implementation details from tracebacks.
This commit is contained in:
Serhiy Storchaka 2017-04-05 09:37:24 +03:00 committed by GitHub
parent 43ba8861e0
commit 5affd23e6f
30 changed files with 50 additions and 48 deletions

View File

@ -589,7 +589,7 @@ class MutableSet(Set):
try: try:
value = next(it) value = next(it)
except StopIteration: except StopIteration:
raise KeyError raise KeyError from None
self.discard(value) self.discard(value)
return value return value
@ -808,7 +808,7 @@ class MutableMapping(Mapping):
try: try:
key = next(iter(self)) key = next(iter(self))
except StopIteration: except StopIteration:
raise KeyError raise KeyError from None
value = self[key] value = self[key]
del self[key] del self[key]
return key, value return key, value

View File

@ -98,7 +98,7 @@ class WeakSet:
try: try:
itemref = self.data.pop() itemref = self.data.pop()
except KeyError: except KeyError:
raise KeyError('pop from empty WeakSet') raise KeyError('pop from empty WeakSet') from None
item = itemref() item = itemref()
if item is not None: if item is not None:
return item return item

View File

@ -149,25 +149,25 @@ def _read_long(file):
try: try:
return struct.unpack('>l', file.read(4))[0] return struct.unpack('>l', file.read(4))[0]
except struct.error: except struct.error:
raise EOFError raise EOFError from None
def _read_ulong(file): def _read_ulong(file):
try: try:
return struct.unpack('>L', file.read(4))[0] return struct.unpack('>L', file.read(4))[0]
except struct.error: except struct.error:
raise EOFError raise EOFError from None
def _read_short(file): def _read_short(file):
try: try:
return struct.unpack('>h', file.read(2))[0] return struct.unpack('>h', file.read(2))[0]
except struct.error: except struct.error:
raise EOFError raise EOFError from None
def _read_ushort(file): def _read_ushort(file):
try: try:
return struct.unpack('>H', file.read(2))[0] return struct.unpack('>H', file.read(2))[0]
except struct.error: except struct.error:
raise EOFError raise EOFError from None
def _read_string(file): def _read_string(file):
length = ord(file.read(1)) length = ord(file.read(1))

View File

@ -1043,7 +1043,7 @@ class BaseEventLoop(events.AbstractEventLoop):
except OSError as err: except OSError as err:
raise OSError(err.errno, 'error while attempting ' raise OSError(err.errno, 'error while attempting '
'to bind on address %r: %s' 'to bind on address %r: %s'
% (sa, err.strerror.lower())) % (sa, err.strerror.lower())) from None
completed = True completed = True
finally: finally:
if not completed: if not completed:

View File

@ -336,11 +336,11 @@ class Bdb:
try: try:
number = int(arg) number = int(arg)
except ValueError: except ValueError:
raise ValueError('Non-numeric breakpoint number %s' % arg) raise ValueError('Non-numeric breakpoint number %s' % arg) from None
try: try:
bp = Breakpoint.bpbynumber[number] bp = Breakpoint.bpbynumber[number]
except IndexError: 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: if bp is None:
raise ValueError('Breakpoint %d already deleted' % number) raise ValueError('Breakpoint %d already deleted' % number)
return bp return bp

View File

@ -64,7 +64,7 @@ class Chunk:
try: try:
self.chunksize = struct.unpack_from(strflag+'L', file.read(4))[0] self.chunksize = struct.unpack_from(strflag+'L', file.read(4))[0]
except struct.error: except struct.error:
raise EOFError raise EOFError from None
if inclheader: if inclheader:
self.chunksize = self.chunksize - 8 # subtract header self.chunksize = self.chunksize - 8 # subtract header
self.size_read = 0 self.size_read = 0

View File

@ -1138,7 +1138,7 @@ class RawConfigParser(MutableMapping):
sectiondict = self._sections[section] sectiondict = self._sections[section]
except KeyError: except KeyError:
if section != self.default_section: if section != self.default_section:
raise NoSectionError(section) raise NoSectionError(section) from None
# Update with the entry specific variables # Update with the entry specific variables
vardict = {} vardict = {}
if vars: if vars:

View File

@ -70,7 +70,7 @@ def _reduce_ex(self, proto):
except AttributeError: except AttributeError:
if getattr(self, "__slots__", None): if getattr(self, "__slots__", None):
raise TypeError("a class that defines __slots__ without " raise TypeError("a class that defines __slots__ without "
"defining __getstate__ cannot be pickled") "defining __getstate__ cannot be pickled") from None
try: try:
dict = self.__dict__ dict = self.__dict__
except AttributeError: except AttributeError:

View File

@ -2079,7 +2079,7 @@ def restore(delta, which):
tag = {1: "- ", 2: "+ "}[int(which)] tag = {1: "- ", 2: "+ "}[int(which)]
except KeyError: except KeyError:
raise ValueError('unknown delta choice (must be 1 or 2): %r' raise ValueError('unknown delta choice (must be 1 or 2): %r'
% which) % which) from None
prefixes = (" ", tag) prefixes = (" ", tag)
for line in delta: for line in delta:
if line[:2] in prefixes: if line[:2] in prefixes:

View File

@ -72,7 +72,7 @@ def distb(tb=None, *, file=None):
try: try:
tb = sys.last_traceback tb = sys.last_traceback
except AttributeError: 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 while tb.tb_next: tb = tb.tb_next
disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file) disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file)

View File

@ -103,7 +103,8 @@ def py_scanstring(s, end, strict=True,
try: try:
esc = s[end] esc = s[end]
except IndexError: 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 not a unicode escape sequence, must be in the lookup table
if esc != 'u': if esc != 'u':
try: try:

View File

@ -29,7 +29,7 @@ def py_make_scanner(context):
try: try:
nextchar = string[idx] nextchar = string[idx]
except IndexError: except IndexError:
raise StopIteration(idx) raise StopIteration(idx) from None
if nextchar == '"': if nextchar == '"':
return parse_string(string, idx + 1, strict) return parse_string(string, idx + 1, strict)

View File

@ -59,7 +59,7 @@ class PatternCompiler(object):
try: try:
root = self.driver.parse_tokens(tokens, debug=debug) root = self.driver.parse_tokens(tokens, debug=debug)
except parse.ParseError as e: except parse.ParseError as e:
raise PatternSyntaxError(str(e)) raise PatternSyntaxError(str(e)) from None
if with_tree: if with_tree:
return self.compile_node(root), root return self.compile_node(root), root
else: else:

View File

@ -29,12 +29,12 @@ def escape(m):
try: try:
i = int(hexes, 16) i = int(hexes, 16)
except ValueError: except ValueError:
raise ValueError("invalid hex string escape ('\\%s')" % tail) raise ValueError("invalid hex string escape ('\\%s')" % tail) from None
else: else:
try: try:
i = int(tail, 8) i = int(tail, 8)
except ValueError: except ValueError:
raise ValueError("invalid octal string escape ('\\%s')" % tail) raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
return chr(i) return chr(i)
def evalString(s): def evalString(s):

View File

@ -248,7 +248,7 @@ class RefactoringTool(object):
try: try:
fix_class = getattr(mod, class_name) fix_class = getattr(mod, class_name)
except AttributeError: 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) fixer = fix_class(self.options, self.fixer_log)
if fixer.explicit and self.explicit is not True and \ if fixer.explicit and self.explicit is not True and \
fix_mod_path not in self.explicit: fix_mod_path not in self.explicit:

View File

@ -512,7 +512,8 @@ def _build_localename(localetuple):
else: else:
return language + '.' + encoding return language + '.' + encoding
except (TypeError, ValueError): 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')): def getdefaultlocale(envvars=('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE')):

View File

@ -555,7 +555,7 @@ class Maildir(Mailbox):
try: try:
return self._toc[key] return self._toc[key]
except KeyError: 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. # This method is for backward compatibility only.
def next(self): def next(self):
@ -741,7 +741,7 @@ class _singlefileMailbox(Mailbox):
try: try:
return self._toc[key] return self._toc[key]
except KeyError: 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): def _append_message(self, message):
"""Append message to mailbox and return (start, stop) offsets.""" """Append message to mailbox and return (start, stop) offsets."""
@ -1572,7 +1572,7 @@ class MaildirMessage(Message):
try: try:
self._date = float(date) self._date = float(date)
except ValueError: 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): def get_info(self):
"""Get the message's "info" as a string.""" """Get the message's "info" as a string."""

View File

@ -189,7 +189,7 @@ class BaseContext(object):
try: try:
ctx = _concrete_contexts[method] ctx = _concrete_contexts[method]
except KeyError: except KeyError:
raise ValueError('cannot find context for %r' % method) raise ValueError('cannot find context for %r' % method) from None
ctx._check_available() ctx._check_available()
return ctx return ctx

View File

@ -720,14 +720,14 @@ class IMapIterator(object):
item = self._items.popleft() item = self._items.popleft()
except IndexError: except IndexError:
if self._index == self._length: if self._index == self._length:
raise StopIteration raise StopIteration from None
self._cond.wait(timeout) self._cond.wait(timeout)
try: try:
item = self._items.popleft() item = self._items.popleft()
except IndexError: except IndexError:
if self._index == self._length: if self._index == self._length:
raise StopIteration raise StopIteration from None
raise TimeoutError raise TimeoutError from None
success, value = item success, value = item
if success: if success:

View File

@ -199,7 +199,7 @@ class BaseProcess(object):
try: try:
return self._sentinel return self._sentinel
except AttributeError: except AttributeError:
raise ValueError("process not started") raise ValueError("process not started") from None
def __repr__(self): def __repr__(self):
if self is _current_process: if self is _current_process:

View File

@ -26,7 +26,7 @@ class netrc:
try: try:
file = os.path.join(os.environ['HOME'], ".netrc") file = os.path.join(os.environ['HOME'], ".netrc")
except KeyError: 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.hosts = {}
self.macros = {} self.macros = {}
with open(file) as fp: with open(file) as fp:

View File

@ -866,7 +866,7 @@ class _NNTPBase:
try: try:
[resp_num, path] = resp.split() [resp_num, path] = resp.split()
except ValueError: except ValueError:
raise NNTPReplyError(resp) raise NNTPReplyError(resp) from None
else: else:
return resp, path return resp, path

View File

@ -269,7 +269,7 @@ def _getattribute(obj, name):
obj = getattr(obj, subpath) obj = getattr(obj, subpath)
except AttributeError: except AttributeError:
raise AttributeError("Can't get attribute {!r} on {!r}" raise AttributeError("Can't get attribute {!r} on {!r}"
.format(name, obj)) .format(name, obj)) from None
return obj, parent return obj, parent
def whichmodule(obj, name): def whichmodule(obj, name):
@ -919,7 +919,7 @@ class _Pickler:
except (ImportError, KeyError, AttributeError): except (ImportError, KeyError, AttributeError):
raise PicklingError( raise PicklingError(
"Can't pickle %r: it's not found as %s.%s" % "Can't pickle %r: it's not found as %s.%s" %
(obj, module_name, name)) (obj, module_name, name)) from None
else: else:
if obj2 is not obj: if obj2 is not obj:
raise PicklingError( raise PicklingError(
@ -964,7 +964,7 @@ class _Pickler:
except UnicodeEncodeError: except UnicodeEncodeError:
raise PicklingError( raise PicklingError(
"can't pickle global identifier '%s.%s' using " "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) self.memoize(obj)

View File

@ -786,7 +786,7 @@ def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
try: try:
format_info = _ARCHIVE_FORMATS[format] format_info = _ARCHIVE_FORMATS[format]
except KeyError: except KeyError:
raise ValueError("unknown archive format '%s'" % format) raise ValueError("unknown archive format '%s'" % format) from None
func = format_info[0] func = format_info[0]
for arg, val in format_info[1]: for arg, val in format_info[1]:
@ -962,7 +962,7 @@ def unpack_archive(filename, extract_dir=None, format=None):
try: try:
format_info = _UNPACK_FORMATS[format] format_info = _UNPACK_FORMATS[format]
except KeyError: 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 = format_info[1]
func(filename, extract_dir, **dict(format_info[2])) func(filename, extract_dir, **dict(format_info[2]))

View File

@ -147,7 +147,7 @@ def _subst_vars(s, local_vars):
try: try:
return s.format(**os.environ) return s.format(**os.environ)
except KeyError as var: except KeyError as var:
raise AttributeError('{%s}' % var) raise AttributeError('{%s}' % var) from None
def _extend_dict(target_dict, other_dict): def _extend_dict(target_dict, other_dict):
target_keys = target_dict.keys() target_keys = target_dict.keys()

View File

@ -209,7 +209,7 @@ def _setoption(arg):
if lineno < 0: if lineno < 0:
raise ValueError raise ValueError
except (ValueError, OverflowError): except (ValueError, OverflowError):
raise _OptionError("invalid lineno %r" % (lineno,)) raise _OptionError("invalid lineno %r" % (lineno,)) from None
else: else:
lineno = 0 lineno = 0
filterwarnings(action, message, category, module, lineno) filterwarnings(action, message, category, module, lineno)
@ -233,7 +233,7 @@ def _getcategory(category):
try: try:
cat = eval(category) cat = eval(category)
except NameError: except NameError:
raise _OptionError("unknown warning category: %r" % (category,)) raise _OptionError("unknown warning category: %r" % (category,)) from None
else: else:
i = category.rfind(".") i = category.rfind(".")
module = category[:i] module = category[:i]
@ -241,11 +241,11 @@ def _getcategory(category):
try: try:
m = __import__(module, None, None, [klass]) m = __import__(module, None, None, [klass])
except ImportError: except ImportError:
raise _OptionError("invalid module name: %r" % (module,)) raise _OptionError("invalid module name: %r" % (module,)) from None
try: try:
cat = getattr(m, klass) cat = getattr(m, klass)
except AttributeError: except AttributeError:
raise _OptionError("unknown warning category: %r" % (category,)) raise _OptionError("unknown warning category: %r" % (category,)) from None
if not issubclass(cat, Warning): if not issubclass(cat, Warning):
raise _OptionError("invalid warning category: %r" % (category,)) raise _OptionError("invalid warning category: %r" % (category,))
return cat return cat

View File

@ -80,7 +80,7 @@ class DOMBuilder:
settings = self._settings[(_name_xform(name), state)] settings = self._settings[(_name_xform(name), state)]
except KeyError: except KeyError:
raise xml.dom.NotSupportedErr( raise xml.dom.NotSupportedErr(
"unsupported feature: %r" % (name,)) "unsupported feature: %r" % (name,)) from None
else: else:
for name, value in settings: for name, value in settings:
setattr(self._options, name, value) setattr(self._options, name, value)

View File

@ -80,7 +80,7 @@ def xpath_tokenizer(pattern, namespaces=None):
raise KeyError raise KeyError
yield token[0], "{%s}%s" % (namespaces[prefix], uri) yield token[0], "{%s}%s" % (namespaces[prefix], uri)
except KeyError: 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: else:
yield token yield token

View File

@ -39,7 +39,7 @@ def get_custom_entry_point(subsystem):
try: try:
return subsystem_details[subsystem][:2] return subsystem_details[subsystem][:2]
except KeyError: 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): def makemakefile(outfp, vars, files, target):

View File

@ -87,7 +87,7 @@ class ColorDB:
try: try:
return self.__byrgb[rgbtuple] return self.__byrgb[rgbtuple]
except KeyError: except KeyError:
raise BadColor(rgbtuple) raise BadColor(rgbtuple) from None
def find_byname(self, name): def find_byname(self, name):
"""Return (red, green, blue) for name""" """Return (red, green, blue) for name"""
@ -95,7 +95,7 @@ class ColorDB:
try: try:
return self.__byname[name] return self.__byname[name]
except KeyError: except KeyError:
raise BadColor(name) raise BadColor(name) from None
def nearest(self, red, green, blue): def nearest(self, red, green, blue):
"""Return the name of color nearest (red, green, blue)""" """Return the name of color nearest (red, green, blue)"""
@ -128,7 +128,7 @@ class ColorDB:
try: try:
name, aliases = self.__byrgb[(red, green, blue)] name, aliases = self.__byrgb[(red, green, blue)]
except KeyError: except KeyError:
raise BadColor((red, green, blue)) raise BadColor((red, green, blue)) from None
return [name] + aliases return [name] + aliases