Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Lib/_collections_abc.py
Original file line number Diff line number Diff line change
Expand Up @@ -589,7 +589,7 @@ def pop(self):
try:
value = next(it)
except StopIteration:
raise KeyError
raise KeyError from None
self.discard(value)
return value

Expand Down Expand Up @@ -808,7 +808,7 @@ def popitem(self):
try:
key = next(iter(self))
except StopIteration:
raise KeyError
raise KeyError from None
value = self[key]
del self[key]
return key, value
Expand Down
2 changes: 1 addition & 1 deletion Lib/_weakrefset.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def pop(self):
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
Expand Down
8 changes: 4 additions & 4 deletions Lib/aifc.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down
2 changes: 1 addition & 1 deletion Lib/asyncio/base_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -1043,7 +1043,7 @@ def create_server(self, protocol_factory, host=None, port=None,
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:
Expand Down
4 changes: 2 additions & 2 deletions Lib/bdb.py
Original file line number Diff line number Diff line change
Expand Up @@ -336,11 +336,11 @@ def get_bpbynumber(self, arg):
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
Expand Down
2 changes: 1 addition & 1 deletion Lib/chunk.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ def __init__(self, file, align=True, bigendian=True, inclheader=False):
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
Expand Down
2 changes: 1 addition & 1 deletion Lib/configparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1138,7 +1138,7 @@ def _unify_values(self, section, vars):
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:
Expand Down
2 changes: 1 addition & 1 deletion Lib/copyreg.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion Lib/difflib.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion Lib/dis.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
2 changes: 1 addition & 1 deletion Lib/encodings/punycode.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ def decode_generalized_number(extended, extpos, bias, errors):
char = ord(extended[extpos])
except IndexError:
if errors == "strict":
raise UnicodeError("incomplete punicode string")
raise UnicodeError("incomplete punicode string") from None
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

information about extpos is lost here

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done. And there are other bugs in this codec.

return extpos + 1, None
extpos += 1
if 0x41 <= char <= 0x5A: # A-Z
Expand Down
3 changes: 2 additions & 1 deletion Lib/json/decoder.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion Lib/json/scanner.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ def _scan_once(string, idx):
try:
nextchar = string[idx]
except IndexError:
raise StopIteration(idx)
raise StopIteration(idx) from None

if nextchar == '"':
return parse_string(string, idx + 1, strict)
Expand Down
2 changes: 1 addition & 1 deletion Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def main():
obj = json.load(infile,
object_pairs_hook=collections.OrderedDict)
except ValueError as e:
raise SystemExit(e)
raise SystemExit(e) from None
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm note sure about this one.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree. It just doesn't have any visible effect. The original exception is passes to SystemExit, and str(e) is printed to stderr at exit. __cause__ and __context__ are ignored.

with outfile:
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
outfile.write('\n')
Expand Down
2 changes: 1 addition & 1 deletion Lib/lib2to3/patcomp.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def compile_pattern(self, input, debug=False, with_tree=False):
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:
Expand Down
4 changes: 2 additions & 2 deletions Lib/lib2to3/pgen2/literals.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion Lib/lib2to3/refactor.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ def get_fixers(self):
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:
Expand Down
3 changes: 2 additions & 1 deletion Lib/locale.py
Original file line number Diff line number Diff line change
Expand Up @@ -507,7 +507,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')):

Expand Down
8 changes: 4 additions & 4 deletions Lib/mailbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ def _string_to_bytes(self, message):
return message.encode('ascii')
except UnicodeError:
raise ValueError("String input must be ASCII-only; "
"use bytes or a Message instead")
"use bytes or a Message instead") from None
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

information about problematic character in the string is lost

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done.


# Whether each message must end in a newline
_append_newline = False
Expand Down Expand Up @@ -555,7 +555,7 @@ def _lookup(self, key):
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):
Expand Down Expand Up @@ -741,7 +741,7 @@ def _lookup(self, key=None):
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."""
Expand Down Expand Up @@ -1572,7 +1572,7 @@ def set_date(self, date):
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."""
Expand Down
2 changes: 1 addition & 1 deletion Lib/multiprocessing/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ def get_context(self, method=None):
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

Expand Down
6 changes: 3 additions & 3 deletions Lib/multiprocessing/pool.py
Original file line number Diff line number Diff line change
Expand Up @@ -684,14 +684,14 @@ def next(self, timeout=None):
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:
Expand Down
2 changes: 1 addition & 1 deletion Lib/multiprocessing/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@ def sentinel(self):
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:
Expand Down
2 changes: 1 addition & 1 deletion Lib/netrc.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ def __init__(self, file=None):
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:
Expand Down
2 changes: 1 addition & 1 deletion Lib/nntplib.py
Original file line number Diff line number Diff line change
Expand Up @@ -866,7 +866,7 @@ def xpath(self, id):
try:
[resp_num, path] = resp.split()
except ValueError:
raise NNTPReplyError(resp)
raise NNTPReplyError(resp) from None
else:
return resp, path

Expand Down
6 changes: 3 additions & 3 deletions Lib/pickle.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -919,7 +919,7 @@ def save_global(self, obj, name=None):
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(
Expand Down Expand Up @@ -964,7 +964,7 @@ def save_global(self, obj, name=None):
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)

Expand Down
4 changes: 2 additions & 2 deletions Lib/shutil.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down Expand Up @@ -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]))
Expand Down
2 changes: 1 addition & 1 deletion Lib/sysconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
8 changes: 4 additions & 4 deletions Lib/warnings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -233,19 +233,19 @@ 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]
klass = category[i+1:]
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
Expand Down
2 changes: 1 addition & 1 deletion Lib/xml/dom/xmlbuilder.py
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def setFeature(self, name, state):
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)
Expand Down
2 changes: 1 addition & 1 deletion Lib/xml/etree/ElementPath.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading