Skip to content

Commit 293dd23

Browse files
authored
Remove binding of captured exceptions when not used to reduce the chances of creating cycles (GH-17246)
Capturing exceptions into names can lead to reference cycles though the __traceback__ attribute of the exceptions in some obscure cases that have been reported previously and fixed individually. As these variables are not used anyway, we can remove the binding to reduce the chances of creating reference cycles. See for example GH-13135
1 parent c6b20be commit 293dd23

28 files changed

+39
-39
lines changed

Lib/asynchat.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -117,7 +117,7 @@ def handle_read(self):
117117
data = self.recv(self.ac_in_buffer_size)
118118
except BlockingIOError:
119119
return
120-
except OSError as why:
120+
except OSError:
121121
self.handle_error()
122122
return
123123

Lib/asyncio/proactor_events.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -711,7 +711,7 @@ async def _sock_sendfile_native(self, sock, file, offset, count):
711711
raise exceptions.SendfileNotAvailableError("not a regular file")
712712
try:
713713
fsize = os.fstat(fileno).st_size
714-
except OSError as err:
714+
except OSError:
715715
raise exceptions.SendfileNotAvailableError("not a regular file")
716716
blocksize = count if count else fsize
717717
if not blocksize:

Lib/asyncio/unix_events.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -330,7 +330,7 @@ async def create_unix_server(
330330
async def _sock_sendfile_native(self, sock, file, offset, count):
331331
try:
332332
os.sendfile
333-
except AttributeError as exc:
333+
except AttributeError:
334334
raise exceptions.SendfileNotAvailableError(
335335
"os.sendfile() is not available")
336336
try:
@@ -339,7 +339,7 @@ async def _sock_sendfile_native(self, sock, file, offset, count):
339339
raise exceptions.SendfileNotAvailableError("not a regular file")
340340
try:
341341
fsize = os.fstat(fileno).st_size
342-
except OSError as err:
342+
except OSError:
343343
raise exceptions.SendfileNotAvailableError("not a regular file")
344344
blocksize = count if count else fsize
345345
if not blocksize:

Lib/codeop.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def _maybe_compile(compiler, source, filename, symbol):
8080

8181
try:
8282
code = compiler(source, filename, symbol)
83-
except SyntaxError as err:
83+
except SyntaxError:
8484
pass
8585

8686
try:

Lib/ctypes/util.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ def _findLib_ld(name):
302302
res = re.search(expr, os.fsdecode(out))
303303
if res:
304304
result = res.group(0)
305-
except Exception as e:
305+
except Exception:
306306
pass # result will be None
307307
return result
308308

Lib/enum.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -420,7 +420,7 @@ def _create_(cls, class_name, names, *, module=None, qualname=None, type=None, s
420420
if module is None:
421421
try:
422422
module = sys._getframe(2).f_globals['__name__']
423-
except (AttributeError, ValueError, KeyError) as exc:
423+
except (AttributeError, ValueError, KeyError):
424424
pass
425425
if module is None:
426426
_make_class_unpicklable(enum_class)

Lib/filecmp.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -156,12 +156,12 @@ def phase2(self): # Distinguish files, directories, funnies
156156
ok = 1
157157
try:
158158
a_stat = os.stat(a_path)
159-
except OSError as why:
159+
except OSError:
160160
# print('Can\'t stat', a_path, ':', why.args[1])
161161
ok = 0
162162
try:
163163
b_stat = os.stat(b_path)
164-
except OSError as why:
164+
except OSError:
165165
# print('Can\'t stat', b_path, ':', why.args[1])
166166
ok = 0
167167

Lib/getpass.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ def unix_getpass(prompt='Password: ', stream=None):
5252
stack.enter_context(input)
5353
if not stream:
5454
stream = input
55-
except OSError as e:
55+
except OSError:
5656
# If that fails, see if stdin can be controlled.
5757
stack.close()
5858
try:

Lib/importlib/abc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
_frozen_importlib = None
1111
try:
1212
import _frozen_importlib_external
13-
except ImportError as exc:
13+
except ImportError:
1414
_frozen_importlib_external = _bootstrap_external
1515
import abc
1616
import warnings

Lib/lib2to3/main.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -90,11 +90,11 @@ def write_file(self, new_text, filename, old_text, encoding):
9090
if os.path.lexists(backup):
9191
try:
9292
os.remove(backup)
93-
except OSError as err:
93+
except OSError:
9494
self.log_message("Can't remove backup %s", backup)
9595
try:
9696
os.rename(filename, backup)
97-
except OSError as err:
97+
except OSError:
9898
self.log_message("Can't rename %s to %s", filename, backup)
9999
# Actually write the new file
100100
write = super(StdoutRefactoringTool, self).write_file

Lib/msilib/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ def add_data(db, table, values):
116116
raise TypeError("Unsupported type %s" % field.__class__.__name__)
117117
try:
118118
v.Modify(MSIMODIFY_INSERT, r)
119-
except Exception as e:
119+
except Exception:
120120
raise MSIError("Could not insert "+repr(values)+" into "+table)
121121

122122
r.ClearData()

Lib/multiprocessing/managers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,7 @@ def serve_client(self, conn):
248248
try:
249249
obj, exposed, gettypeid = \
250250
self.id_to_local_proxy_obj[ident]
251-
except KeyError as second_ke:
251+
except KeyError:
252252
raise ke
253253

254254
if methodname not in exposed:
@@ -296,7 +296,7 @@ def serve_client(self, conn):
296296
try:
297297
try:
298298
send(msg)
299-
except Exception as e:
299+
except Exception:
300300
send(('#UNSERIALIZABLE', format_exc()))
301301
except Exception as e:
302302
util.info('exception in thread serving %r',

Lib/multiprocessing/popen_fork.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def poll(self, flag=os.WNOHANG):
2525
if self.returncode is None:
2626
try:
2727
pid, sts = os.waitpid(self.pid, flag)
28-
except OSError as e:
28+
except OSError:
2929
# Child process not yet created. See #1731717
3030
# e.errno == errno.ECHILD == 10
3131
return None

Lib/poplib.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ def _parsecap(line):
385385
for capline in rawcaps:
386386
capnm, capargs = _parsecap(capline)
387387
caps[capnm] = capargs
388-
except error_proto as _err:
388+
except error_proto:
389389
raise error_proto('-ERR CAPA not supported by server')
390390
return caps
391391

Lib/test/pythoninfo.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -754,7 +754,7 @@ def collect_info(info):
754754
):
755755
try:
756756
collect_func(info_add)
757-
except Exception as exc:
757+
except Exception:
758758
error = True
759759
print("ERROR: %s() failed" % (collect_func.__name__),
760760
file=sys.stderr)

Lib/test/test_cgitb.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def test_html(self):
3131
def test_text(self):
3232
try:
3333
raise ValueError("Hello World")
34-
except ValueError as err:
34+
except ValueError:
3535
text = cgitb.text(sys.exc_info())
3636
self.assertIn("ValueError", text)
3737
self.assertIn("Hello World", text)

Lib/test/test_class.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -529,7 +529,7 @@ class I:
529529
# In debug mode, printed XXX undetected error and
530530
# raises AttributeError
531531
I()
532-
except AttributeError as x:
532+
except AttributeError:
533533
pass
534534
else:
535535
self.fail("attribute error for I.__init__ got masked")

Lib/test/test_codecs.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
try:
1313
import _testcapi
14-
except ImportError as exc:
14+
except ImportError:
1515
_testcapi = None
1616

1717
try:

Lib/test/test_decimal.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -5600,13 +5600,13 @@ def doit(ty):
56005600
args, kwds = mkargs(C, c_sig)
56015601
try:
56025602
getattr(c_type(9), attr)(*args, **kwds)
5603-
except Exception as err:
5603+
except Exception:
56045604
raise TestFailed("invalid signature for %s: %s %s" % (c_func, args, kwds))
56055605

56065606
args, kwds = mkargs(P, p_sig)
56075607
try:
56085608
getattr(p_type(9), attr)(*args, **kwds)
5609-
except Exception as err:
5609+
except Exception:
56105610
raise TestFailed("invalid signature for %s: %s %s" % (p_func, args, kwds))
56115611

56125612
doit('Decimal')

Lib/test/test_ftplib.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -346,7 +346,7 @@ def _do_ssl_shutdown(self):
346346
if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
347347
ssl.SSL_ERROR_WANT_WRITE):
348348
return
349-
except OSError as err:
349+
except OSError:
350350
# Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
351351
# from OpenSSL's SSL_shutdown(), corresponding to a
352352
# closed socket condition. See also:

Lib/test/test_sys_settrace.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -161,8 +161,8 @@ def raises():
161161
def test_raise():
162162
try:
163163
raises()
164-
except Exception as exc:
165-
x = 1
164+
except Exception:
165+
pass
166166

167167
test_raise.events = [(0, 'call'),
168168
(1, 'line'),
@@ -191,7 +191,7 @@ def _settrace_and_raise(tracefunc):
191191
def settrace_and_raise(tracefunc):
192192
try:
193193
_settrace_and_raise(tracefunc)
194-
except RuntimeError as exc:
194+
except RuntimeError:
195195
pass
196196

197197
settrace_and_raise.events = [(2, 'exception'),

Lib/test/test_time.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -825,7 +825,7 @@ def convert_values(ns_timestamps):
825825
try:
826826
result = pytime_converter(value, time_rnd)
827827
expected = expected_func(value)
828-
except Exception as exc:
828+
except Exception:
829829
self.fail("Error on timestamp conversion: %s" % debug_info)
830830
self.assertEqual(result,
831831
expected,

Lib/test/test_traceback.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ def f():
313313
with captured_output("stderr") as stderr_f:
314314
try:
315315
f()
316-
except RecursionError as exc:
316+
except RecursionError:
317317
render_exc()
318318
else:
319319
self.fail("no recursion occurred")
@@ -360,7 +360,7 @@ def g(count=10):
360360
with captured_output("stderr") as stderr_g:
361361
try:
362362
g()
363-
except ValueError as exc:
363+
except ValueError:
364364
render_exc()
365365
else:
366366
self.fail("no value error was raised")
@@ -396,7 +396,7 @@ def h(count=10):
396396
with captured_output("stderr") as stderr_h:
397397
try:
398398
h()
399-
except ValueError as exc:
399+
except ValueError:
400400
render_exc()
401401
else:
402402
self.fail("no value error was raised")
@@ -424,7 +424,7 @@ def h(count=10):
424424
with captured_output("stderr") as stderr_g:
425425
try:
426426
g(traceback._RECURSIVE_CUTOFF)
427-
except ValueError as exc:
427+
except ValueError:
428428
render_exc()
429429
else:
430430
self.fail("no error raised")
@@ -452,7 +452,7 @@ def h(count=10):
452452
with captured_output("stderr") as stderr_g:
453453
try:
454454
g(traceback._RECURSIVE_CUTOFF + 1)
455-
except ValueError as exc:
455+
except ValueError:
456456
render_exc()
457457
else:
458458
self.fail("no error raised")

Lib/test/test_urllib2net.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -199,7 +199,7 @@ def test_sites_no_connection_close(self):
199199
try:
200200
with urllib.request.urlopen(URL) as res:
201201
pass
202-
except ValueError as e:
202+
except ValueError:
203203
self.fail("urlopen failed for site not sending \
204204
Connection:close")
205205
else:

Lib/test/test_uuid.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ def test_uuid1_eui64(self):
471471
# the value from too_large_getter above.
472472
try:
473473
self.uuid.uuid1(node=node)
474-
except ValueError as e:
474+
except ValueError:
475475
self.fail('uuid1 was given an invalid node ID')
476476

477477
def test_uuid1(self):

Lib/unittest/case.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -712,7 +712,7 @@ def doClassCleanups(cls):
712712
function, args, kwargs = cls._class_cleanups.pop()
713713
try:
714714
function(*args, **kwargs)
715-
except Exception as exc:
715+
except Exception:
716716
cls.tearDown_exceptions.append(sys.exc_info())
717717

718718
def __call__(self, *args, **kwds):

Lib/urllib/request.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1778,7 +1778,7 @@ def retrieve(self, url, filename=None, reporthook=None, data=None):
17781778
hdrs = fp.info()
17791779
fp.close()
17801780
return url2pathname(_splithost(url1)[1]), hdrs
1781-
except OSError as msg:
1781+
except OSError:
17821782
pass
17831783
fp = self.open(url, data)
17841784
try:

Lib/xml/sax/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def make_parser(parser_list=()):
7878
for parser_name in list(parser_list) + default_parser_list:
7979
try:
8080
return _create_parser(parser_name)
81-
except ImportError as e:
81+
except ImportError:
8282
import sys
8383
if parser_name in sys.modules:
8484
# The parser module was found, but importing it

0 commit comments

Comments
 (0)