Skip to content

Commit 5affd23

Browse files
bpo-29762: More use "raise from None". (#569)
This hides unwanted implementation details from tracebacks.
1 parent 43ba886 commit 5affd23

30 files changed

+50
-48
lines changed

Lib/_collections_abc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -589,7 +589,7 @@ def pop(self):
589589
try:
590590
value = next(it)
591591
except StopIteration:
592-
raise KeyError
592+
raise KeyError from None
593593
self.discard(value)
594594
return value
595595

@@ -808,7 +808,7 @@ def popitem(self):
808808
try:
809809
key = next(iter(self))
810810
except StopIteration:
811-
raise KeyError
811+
raise KeyError from None
812812
value = self[key]
813813
del self[key]
814814
return key, value

Lib/_weakrefset.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ def pop(self):
9898
try:
9999
itemref = self.data.pop()
100100
except KeyError:
101-
raise KeyError('pop from empty WeakSet')
101+
raise KeyError('pop from empty WeakSet') from None
102102
item = itemref()
103103
if item is not None:
104104
return item

Lib/aifc.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,25 +149,25 @@ def _read_long(file):
149149
try:
150150
return struct.unpack('>l', file.read(4))[0]
151151
except struct.error:
152-
raise EOFError
152+
raise EOFError from None
153153

154154
def _read_ulong(file):
155155
try:
156156
return struct.unpack('>L', file.read(4))[0]
157157
except struct.error:
158-
raise EOFError
158+
raise EOFError from None
159159

160160
def _read_short(file):
161161
try:
162162
return struct.unpack('>h', file.read(2))[0]
163163
except struct.error:
164-
raise EOFError
164+
raise EOFError from None
165165

166166
def _read_ushort(file):
167167
try:
168168
return struct.unpack('>H', file.read(2))[0]
169169
except struct.error:
170-
raise EOFError
170+
raise EOFError from None
171171

172172
def _read_string(file):
173173
length = ord(file.read(1))

Lib/asyncio/base_events.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1043,7 +1043,7 @@ def create_server(self, protocol_factory, host=None, port=None,
10431043
except OSError as err:
10441044
raise OSError(err.errno, 'error while attempting '
10451045
'to bind on address %r: %s'
1046-
% (sa, err.strerror.lower()))
1046+
% (sa, err.strerror.lower())) from None
10471047
completed = True
10481048
finally:
10491049
if not completed:

Lib/bdb.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -336,11 +336,11 @@ def get_bpbynumber(self, arg):
336336
try:
337337
number = int(arg)
338338
except ValueError:
339-
raise ValueError('Non-numeric breakpoint number %s' % arg)
339+
raise ValueError('Non-numeric breakpoint number %s' % arg) from None
340340
try:
341341
bp = Breakpoint.bpbynumber[number]
342342
except IndexError:
343-
raise ValueError('Breakpoint number %d out of range' % number)
343+
raise ValueError('Breakpoint number %d out of range' % number) from None
344344
if bp is None:
345345
raise ValueError('Breakpoint %d already deleted' % number)
346346
return bp

Lib/chunk.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ def __init__(self, file, align=True, bigendian=True, inclheader=False):
6464
try:
6565
self.chunksize = struct.unpack_from(strflag+'L', file.read(4))[0]
6666
except struct.error:
67-
raise EOFError
67+
raise EOFError from None
6868
if inclheader:
6969
self.chunksize = self.chunksize - 8 # subtract header
7070
self.size_read = 0

Lib/configparser.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1138,7 +1138,7 @@ def _unify_values(self, section, vars):
11381138
sectiondict = self._sections[section]
11391139
except KeyError:
11401140
if section != self.default_section:
1141-
raise NoSectionError(section)
1141+
raise NoSectionError(section) from None
11421142
# Update with the entry specific variables
11431143
vardict = {}
11441144
if vars:

Lib/copyreg.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def _reduce_ex(self, proto):
7070
except AttributeError:
7171
if getattr(self, "__slots__", None):
7272
raise TypeError("a class that defines __slots__ without "
73-
"defining __getstate__ cannot be pickled")
73+
"defining __getstate__ cannot be pickled") from None
7474
try:
7575
dict = self.__dict__
7676
except AttributeError:

Lib/difflib.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2079,7 +2079,7 @@ def restore(delta, which):
20792079
tag = {1: "- ", 2: "+ "}[int(which)]
20802080
except KeyError:
20812081
raise ValueError('unknown delta choice (must be 1 or 2): %r'
2082-
% which)
2082+
% which) from None
20832083
prefixes = (" ", tag)
20842084
for line in delta:
20852085
if line[:2] in prefixes:

Lib/dis.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,7 @@ def distb(tb=None, *, file=None):
7272
try:
7373
tb = sys.last_traceback
7474
except AttributeError:
75-
raise RuntimeError("no last traceback to disassemble")
75+
raise RuntimeError("no last traceback to disassemble") from None
7676
while tb.tb_next: tb = tb.tb_next
7777
disassemble(tb.tb_frame.f_code, tb.tb_lasti, file=file)
7878

Lib/json/decoder.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,8 @@ def py_scanstring(s, end, strict=True,
103103
try:
104104
esc = s[end]
105105
except IndexError:
106-
raise JSONDecodeError("Unterminated string starting at", s, begin)
106+
raise JSONDecodeError("Unterminated string starting at",
107+
s, begin) from None
107108
# If not a unicode escape sequence, must be in the lookup table
108109
if esc != 'u':
109110
try:

Lib/json/scanner.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ def _scan_once(string, idx):
2929
try:
3030
nextchar = string[idx]
3131
except IndexError:
32-
raise StopIteration(idx)
32+
raise StopIteration(idx) from None
3333

3434
if nextchar == '"':
3535
return parse_string(string, idx + 1, strict)

Lib/lib2to3/patcomp.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def compile_pattern(self, input, debug=False, with_tree=False):
5959
try:
6060
root = self.driver.parse_tokens(tokens, debug=debug)
6161
except parse.ParseError as e:
62-
raise PatternSyntaxError(str(e))
62+
raise PatternSyntaxError(str(e)) from None
6363
if with_tree:
6464
return self.compile_node(root), root
6565
else:

Lib/lib2to3/pgen2/literals.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@ def escape(m):
2929
try:
3030
i = int(hexes, 16)
3131
except ValueError:
32-
raise ValueError("invalid hex string escape ('\\%s')" % tail)
32+
raise ValueError("invalid hex string escape ('\\%s')" % tail) from None
3333
else:
3434
try:
3535
i = int(tail, 8)
3636
except ValueError:
37-
raise ValueError("invalid octal string escape ('\\%s')" % tail)
37+
raise ValueError("invalid octal string escape ('\\%s')" % tail) from None
3838
return chr(i)
3939

4040
def evalString(s):

Lib/lib2to3/refactor.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ def get_fixers(self):
248248
try:
249249
fix_class = getattr(mod, class_name)
250250
except AttributeError:
251-
raise FixerError("Can't find %s.%s" % (fix_name, class_name))
251+
raise FixerError("Can't find %s.%s" % (fix_name, class_name)) from None
252252
fixer = fix_class(self.options, self.fixer_log)
253253
if fixer.explicit and self.explicit is not True and \
254254
fix_mod_path not in self.explicit:

Lib/locale.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -512,7 +512,8 @@ def _build_localename(localetuple):
512512
else:
513513
return language + '.' + encoding
514514
except (TypeError, ValueError):
515-
raise TypeError('Locale must be None, a string, or an iterable of two strings -- language code, encoding.')
515+
raise TypeError('Locale must be None, a string, or an iterable of '
516+
'two strings -- language code, encoding.') from None
516517

517518
def getdefaultlocale(envvars=('LC_ALL', 'LC_CTYPE', 'LANG', 'LANGUAGE')):
518519

Lib/mailbox.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -555,7 +555,7 @@ def _lookup(self, key):
555555
try:
556556
return self._toc[key]
557557
except KeyError:
558-
raise KeyError('No message with key: %s' % key)
558+
raise KeyError('No message with key: %s' % key) from None
559559

560560
# This method is for backward compatibility only.
561561
def next(self):
@@ -741,7 +741,7 @@ def _lookup(self, key=None):
741741
try:
742742
return self._toc[key]
743743
except KeyError:
744-
raise KeyError('No message with key: %s' % key)
744+
raise KeyError('No message with key: %s' % key) from None
745745

746746
def _append_message(self, message):
747747
"""Append message to mailbox and return (start, stop) offsets."""
@@ -1572,7 +1572,7 @@ def set_date(self, date):
15721572
try:
15731573
self._date = float(date)
15741574
except ValueError:
1575-
raise TypeError("can't convert to float: %s" % date)
1575+
raise TypeError("can't convert to float: %s" % date) from None
15761576

15771577
def get_info(self):
15781578
"""Get the message's "info" as a string."""

Lib/multiprocessing/context.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ def get_context(self, method=None):
189189
try:
190190
ctx = _concrete_contexts[method]
191191
except KeyError:
192-
raise ValueError('cannot find context for %r' % method)
192+
raise ValueError('cannot find context for %r' % method) from None
193193
ctx._check_available()
194194
return ctx
195195

Lib/multiprocessing/pool.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -720,14 +720,14 @@ def next(self, timeout=None):
720720
item = self._items.popleft()
721721
except IndexError:
722722
if self._index == self._length:
723-
raise StopIteration
723+
raise StopIteration from None
724724
self._cond.wait(timeout)
725725
try:
726726
item = self._items.popleft()
727727
except IndexError:
728728
if self._index == self._length:
729-
raise StopIteration
730-
raise TimeoutError
729+
raise StopIteration from None
730+
raise TimeoutError from None
731731

732732
success, value = item
733733
if success:

Lib/multiprocessing/process.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ def sentinel(self):
199199
try:
200200
return self._sentinel
201201
except AttributeError:
202-
raise ValueError("process not started")
202+
raise ValueError("process not started") from None
203203

204204
def __repr__(self):
205205
if self is _current_process:

Lib/netrc.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ def __init__(self, file=None):
2626
try:
2727
file = os.path.join(os.environ['HOME'], ".netrc")
2828
except KeyError:
29-
raise OSError("Could not find .netrc: $HOME is not set")
29+
raise OSError("Could not find .netrc: $HOME is not set") from None
3030
self.hosts = {}
3131
self.macros = {}
3232
with open(file) as fp:

Lib/nntplib.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -866,7 +866,7 @@ def xpath(self, id):
866866
try:
867867
[resp_num, path] = resp.split()
868868
except ValueError:
869-
raise NNTPReplyError(resp)
869+
raise NNTPReplyError(resp) from None
870870
else:
871871
return resp, path
872872

Lib/pickle.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,7 @@ def _getattribute(obj, name):
269269
obj = getattr(obj, subpath)
270270
except AttributeError:
271271
raise AttributeError("Can't get attribute {!r} on {!r}"
272-
.format(name, obj))
272+
.format(name, obj)) from None
273273
return obj, parent
274274

275275
def whichmodule(obj, name):
@@ -919,7 +919,7 @@ def save_global(self, obj, name=None):
919919
except (ImportError, KeyError, AttributeError):
920920
raise PicklingError(
921921
"Can't pickle %r: it's not found as %s.%s" %
922-
(obj, module_name, name))
922+
(obj, module_name, name)) from None
923923
else:
924924
if obj2 is not obj:
925925
raise PicklingError(
@@ -964,7 +964,7 @@ def save_global(self, obj, name=None):
964964
except UnicodeEncodeError:
965965
raise PicklingError(
966966
"can't pickle global identifier '%s.%s' using "
967-
"pickle protocol %i" % (module, name, self.proto))
967+
"pickle protocol %i" % (module, name, self.proto)) from None
968968

969969
self.memoize(obj)
970970

Lib/shutil.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -786,7 +786,7 @@ def make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
786786
try:
787787
format_info = _ARCHIVE_FORMATS[format]
788788
except KeyError:
789-
raise ValueError("unknown archive format '%s'" % format)
789+
raise ValueError("unknown archive format '%s'" % format) from None
790790

791791
func = format_info[0]
792792
for arg, val in format_info[1]:
@@ -962,7 +962,7 @@ def unpack_archive(filename, extract_dir=None, format=None):
962962
try:
963963
format_info = _UNPACK_FORMATS[format]
964964
except KeyError:
965-
raise ValueError("Unknown unpack format '{0}'".format(format))
965+
raise ValueError("Unknown unpack format '{0}'".format(format)) from None
966966

967967
func = format_info[1]
968968
func(filename, extract_dir, **dict(format_info[2]))

Lib/sysconfig.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def _subst_vars(s, local_vars):
147147
try:
148148
return s.format(**os.environ)
149149
except KeyError as var:
150-
raise AttributeError('{%s}' % var)
150+
raise AttributeError('{%s}' % var) from None
151151

152152
def _extend_dict(target_dict, other_dict):
153153
target_keys = target_dict.keys()

Lib/warnings.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -209,7 +209,7 @@ def _setoption(arg):
209209
if lineno < 0:
210210
raise ValueError
211211
except (ValueError, OverflowError):
212-
raise _OptionError("invalid lineno %r" % (lineno,))
212+
raise _OptionError("invalid lineno %r" % (lineno,)) from None
213213
else:
214214
lineno = 0
215215
filterwarnings(action, message, category, module, lineno)
@@ -233,19 +233,19 @@ def _getcategory(category):
233233
try:
234234
cat = eval(category)
235235
except NameError:
236-
raise _OptionError("unknown warning category: %r" % (category,))
236+
raise _OptionError("unknown warning category: %r" % (category,)) from None
237237
else:
238238
i = category.rfind(".")
239239
module = category[:i]
240240
klass = category[i+1:]
241241
try:
242242
m = __import__(module, None, None, [klass])
243243
except ImportError:
244-
raise _OptionError("invalid module name: %r" % (module,))
244+
raise _OptionError("invalid module name: %r" % (module,)) from None
245245
try:
246246
cat = getattr(m, klass)
247247
except AttributeError:
248-
raise _OptionError("unknown warning category: %r" % (category,))
248+
raise _OptionError("unknown warning category: %r" % (category,)) from None
249249
if not issubclass(cat, Warning):
250250
raise _OptionError("invalid warning category: %r" % (category,))
251251
return cat

Lib/xml/dom/xmlbuilder.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def setFeature(self, name, state):
8080
settings = self._settings[(_name_xform(name), state)]
8181
except KeyError:
8282
raise xml.dom.NotSupportedErr(
83-
"unsupported feature: %r" % (name,))
83+
"unsupported feature: %r" % (name,)) from None
8484
else:
8585
for name, value in settings:
8686
setattr(self._options, name, value)

Lib/xml/etree/ElementPath.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def xpath_tokenizer(pattern, namespaces=None):
8080
raise KeyError
8181
yield token[0], "{%s}%s" % (namespaces[prefix], uri)
8282
except KeyError:
83-
raise SyntaxError("prefix %r not found in prefix map" % prefix)
83+
raise SyntaxError("prefix %r not found in prefix map" % prefix) from None
8484
else:
8585
yield token
8686

Tools/freeze/winmakemakefile.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def get_custom_entry_point(subsystem):
3939
try:
4040
return subsystem_details[subsystem][:2]
4141
except KeyError:
42-
raise ValueError("The subsystem %s is not known" % subsystem)
42+
raise ValueError("The subsystem %s is not known" % subsystem) from None
4343

4444

4545
def makemakefile(outfp, vars, files, target):

0 commit comments

Comments
 (0)