From 293dd23477eef6e7c1b1e26b5bb2c1e0d79ac3c2 Mon Sep 17 00:00:00 2001 From: Pablo Galindo Date: Tue, 19 Nov 2019 21:34:03 +0000 Subject: [PATCH] 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 --- Lib/asynchat.py | 2 +- Lib/asyncio/proactor_events.py | 2 +- Lib/asyncio/unix_events.py | 4 ++-- Lib/codeop.py | 2 +- Lib/ctypes/util.py | 2 +- Lib/enum.py | 2 +- Lib/filecmp.py | 4 ++-- Lib/getpass.py | 2 +- Lib/importlib/abc.py | 2 +- Lib/lib2to3/main.py | 4 ++-- Lib/msilib/__init__.py | 2 +- Lib/multiprocessing/managers.py | 4 ++-- Lib/multiprocessing/popen_fork.py | 2 +- Lib/poplib.py | 2 +- Lib/test/pythoninfo.py | 2 +- Lib/test/test_cgitb.py | 2 +- Lib/test/test_class.py | 2 +- Lib/test/test_codecs.py | 2 +- Lib/test/test_decimal.py | 4 ++-- Lib/test/test_ftplib.py | 2 +- Lib/test/test_sys_settrace.py | 6 +++--- Lib/test/test_time.py | 2 +- Lib/test/test_traceback.py | 10 +++++----- Lib/test/test_urllib2net.py | 2 +- Lib/test/test_uuid.py | 2 +- Lib/unittest/case.py | 2 +- Lib/urllib/request.py | 2 +- Lib/xml/sax/__init__.py | 2 +- 28 files changed, 39 insertions(+), 39 deletions(-) diff --git a/Lib/asynchat.py b/Lib/asynchat.py index fc1146adbb1..f4ba361bd4a 100644 --- a/Lib/asynchat.py +++ b/Lib/asynchat.py @@ -117,7 +117,7 @@ class async_chat(asyncore.dispatcher): data = self.recv(self.ac_in_buffer_size) except BlockingIOError: return - except OSError as why: + except OSError: self.handle_error() return diff --git a/Lib/asyncio/proactor_events.py b/Lib/asyncio/proactor_events.py index 830d8edc32f..8338449aaa0 100644 --- a/Lib/asyncio/proactor_events.py +++ b/Lib/asyncio/proactor_events.py @@ -711,7 +711,7 @@ class BaseProactorEventLoop(base_events.BaseEventLoop): raise exceptions.SendfileNotAvailableError("not a regular file") try: fsize = os.fstat(fileno).st_size - except OSError as err: + except OSError: raise exceptions.SendfileNotAvailableError("not a regular file") blocksize = count if count else fsize if not blocksize: diff --git a/Lib/asyncio/unix_events.py b/Lib/asyncio/unix_events.py index 66213728a3d..632546ad008 100644 --- a/Lib/asyncio/unix_events.py +++ b/Lib/asyncio/unix_events.py @@ -330,7 +330,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop): async def _sock_sendfile_native(self, sock, file, offset, count): try: os.sendfile - except AttributeError as exc: + except AttributeError: raise exceptions.SendfileNotAvailableError( "os.sendfile() is not available") try: @@ -339,7 +339,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop): raise exceptions.SendfileNotAvailableError("not a regular file") try: fsize = os.fstat(fileno).st_size - except OSError as err: + except OSError: raise exceptions.SendfileNotAvailableError("not a regular file") blocksize = count if count else fsize if not blocksize: diff --git a/Lib/codeop.py b/Lib/codeop.py index e5c7adea54f..fc7e1e70cea 100644 --- a/Lib/codeop.py +++ b/Lib/codeop.py @@ -80,7 +80,7 @@ def _maybe_compile(compiler, source, filename, symbol): try: code = compiler(source, filename, symbol) - except SyntaxError as err: + except SyntaxError: pass try: diff --git a/Lib/ctypes/util.py b/Lib/ctypes/util.py index 97973bce001..01176bf9696 100644 --- a/Lib/ctypes/util.py +++ b/Lib/ctypes/util.py @@ -302,7 +302,7 @@ elif os.name == "posix": res = re.search(expr, os.fsdecode(out)) if res: result = res.group(0) - except Exception as e: + except Exception: pass # result will be None return result diff --git a/Lib/enum.py b/Lib/enum.py index 8a6e5d2e46d..06f42a97803 100644 --- a/Lib/enum.py +++ b/Lib/enum.py @@ -420,7 +420,7 @@ class EnumMeta(type): if module is None: try: module = sys._getframe(2).f_globals['__name__'] - except (AttributeError, ValueError, KeyError) as exc: + except (AttributeError, ValueError, KeyError): pass if module is None: _make_class_unpicklable(enum_class) diff --git a/Lib/filecmp.py b/Lib/filecmp.py index e5ad8397e4c..cfdca1e924f 100644 --- a/Lib/filecmp.py +++ b/Lib/filecmp.py @@ -156,12 +156,12 @@ class dircmp: ok = 1 try: a_stat = os.stat(a_path) - except OSError as why: + except OSError: # print('Can\'t stat', a_path, ':', why.args[1]) ok = 0 try: b_stat = os.stat(b_path) - except OSError as why: + except OSError: # print('Can\'t stat', b_path, ':', why.args[1]) ok = 0 diff --git a/Lib/getpass.py b/Lib/getpass.py index 36e17e4cb69..6911f41d1f2 100644 --- a/Lib/getpass.py +++ b/Lib/getpass.py @@ -52,7 +52,7 @@ def unix_getpass(prompt='Password: ', stream=None): stack.enter_context(input) if not stream: stream = input - except OSError as e: + except OSError: # If that fails, see if stdin can be controlled. stack.close() try: diff --git a/Lib/importlib/abc.py b/Lib/importlib/abc.py index 4b2d3de6d96..b1b5ccce4bd 100644 --- a/Lib/importlib/abc.py +++ b/Lib/importlib/abc.py @@ -10,7 +10,7 @@ except ImportError as exc: _frozen_importlib = None try: import _frozen_importlib_external -except ImportError as exc: +except ImportError: _frozen_importlib_external = _bootstrap_external import abc import warnings diff --git a/Lib/lib2to3/main.py b/Lib/lib2to3/main.py index d6b708848ed..c51626babf8 100644 --- a/Lib/lib2to3/main.py +++ b/Lib/lib2to3/main.py @@ -90,11 +90,11 @@ class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool): if os.path.lexists(backup): try: os.remove(backup) - except OSError as err: + except OSError: self.log_message("Can't remove backup %s", backup) try: os.rename(filename, backup) - except OSError as err: + except OSError: self.log_message("Can't rename %s to %s", filename, backup) # Actually write the new file write = super(StdoutRefactoringTool, self).write_file diff --git a/Lib/msilib/__init__.py b/Lib/msilib/__init__.py index 0bc8dd99524..0e85aa28967 100644 --- a/Lib/msilib/__init__.py +++ b/Lib/msilib/__init__.py @@ -116,7 +116,7 @@ def add_data(db, table, values): raise TypeError("Unsupported type %s" % field.__class__.__name__) try: v.Modify(MSIMODIFY_INSERT, r) - except Exception as e: + except Exception: raise MSIError("Could not insert "+repr(values)+" into "+table) r.ClearData() diff --git a/Lib/multiprocessing/managers.py b/Lib/multiprocessing/managers.py index 75b5150f821..1f9c2daa25d 100644 --- a/Lib/multiprocessing/managers.py +++ b/Lib/multiprocessing/managers.py @@ -248,7 +248,7 @@ class Server(object): try: obj, exposed, gettypeid = \ self.id_to_local_proxy_obj[ident] - except KeyError as second_ke: + except KeyError: raise ke if methodname not in exposed: @@ -296,7 +296,7 @@ class Server(object): try: try: send(msg) - except Exception as e: + except Exception: send(('#UNSERIALIZABLE', format_exc())) except Exception as e: util.info('exception in thread serving %r', diff --git a/Lib/multiprocessing/popen_fork.py b/Lib/multiprocessing/popen_fork.py index 11e216072d0..a65b06f1b2c 100644 --- a/Lib/multiprocessing/popen_fork.py +++ b/Lib/multiprocessing/popen_fork.py @@ -25,7 +25,7 @@ class Popen(object): if self.returncode is None: try: pid, sts = os.waitpid(self.pid, flag) - except OSError as e: + except OSError: # Child process not yet created. See #1731717 # e.errno == errno.ECHILD == 10 return None diff --git a/Lib/poplib.py b/Lib/poplib.py index e3bd2ab1ebc..0b6750d2303 100644 --- a/Lib/poplib.py +++ b/Lib/poplib.py @@ -385,7 +385,7 @@ class POP3: for capline in rawcaps: capnm, capargs = _parsecap(capline) caps[capnm] = capargs - except error_proto as _err: + except error_proto: raise error_proto('-ERR CAPA not supported by server') return caps diff --git a/Lib/test/pythoninfo.py b/Lib/test/pythoninfo.py index 797b3af7d30..eab82c3631f 100644 --- a/Lib/test/pythoninfo.py +++ b/Lib/test/pythoninfo.py @@ -754,7 +754,7 @@ def collect_info(info): ): try: collect_func(info_add) - except Exception as exc: + except Exception: error = True print("ERROR: %s() failed" % (collect_func.__name__), file=sys.stderr) diff --git a/Lib/test/test_cgitb.py b/Lib/test/test_cgitb.py index e299ec3ec6c..8991bc1ff34 100644 --- a/Lib/test/test_cgitb.py +++ b/Lib/test/test_cgitb.py @@ -31,7 +31,7 @@ class TestCgitb(unittest.TestCase): def test_text(self): try: raise ValueError("Hello World") - except ValueError as err: + except ValueError: text = cgitb.text(sys.exc_info()) self.assertIn("ValueError", text) self.assertIn("Hello World", text) diff --git a/Lib/test/test_class.py b/Lib/test/test_class.py index 456f1be30be..7524f58a3ce 100644 --- a/Lib/test/test_class.py +++ b/Lib/test/test_class.py @@ -529,7 +529,7 @@ class ClassTests(unittest.TestCase): # In debug mode, printed XXX undetected error and # raises AttributeError I() - except AttributeError as x: + except AttributeError: pass else: self.fail("attribute error for I.__init__ got masked") diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py index e1638c11168..3aec34c7f16 100644 --- a/Lib/test/test_codecs.py +++ b/Lib/test/test_codecs.py @@ -11,7 +11,7 @@ from test import support try: import _testcapi -except ImportError as exc: +except ImportError: _testcapi = None try: diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py index 1f37b5372a3..fe0cfc7b66d 100644 --- a/Lib/test/test_decimal.py +++ b/Lib/test/test_decimal.py @@ -5600,13 +5600,13 @@ class SignatureTest(unittest.TestCase): args, kwds = mkargs(C, c_sig) try: getattr(c_type(9), attr)(*args, **kwds) - except Exception as err: + except Exception: raise TestFailed("invalid signature for %s: %s %s" % (c_func, args, kwds)) args, kwds = mkargs(P, p_sig) try: getattr(p_type(9), attr)(*args, **kwds) - except Exception as err: + except Exception: raise TestFailed("invalid signature for %s: %s %s" % (p_func, args, kwds)) doit('Decimal') diff --git a/Lib/test/test_ftplib.py b/Lib/test/test_ftplib.py index b0e46411a2e..b8eef82b15f 100644 --- a/Lib/test/test_ftplib.py +++ b/Lib/test/test_ftplib.py @@ -346,7 +346,7 @@ if ssl is not None: if err.args[0] in (ssl.SSL_ERROR_WANT_READ, ssl.SSL_ERROR_WANT_WRITE): return - except OSError as err: + except OSError: # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return # from OpenSSL's SSL_shutdown(), corresponding to a # closed socket condition. See also: diff --git a/Lib/test/test_sys_settrace.py b/Lib/test/test_sys_settrace.py index fdd789475d0..d4e1ac2c83e 100644 --- a/Lib/test/test_sys_settrace.py +++ b/Lib/test/test_sys_settrace.py @@ -161,8 +161,8 @@ def raises(): def test_raise(): try: raises() - except Exception as exc: - x = 1 + except Exception: + pass test_raise.events = [(0, 'call'), (1, 'line'), @@ -191,7 +191,7 @@ def _settrace_and_raise(tracefunc): def settrace_and_raise(tracefunc): try: _settrace_and_raise(tracefunc) - except RuntimeError as exc: + except RuntimeError: pass settrace_and_raise.events = [(2, 'exception'), diff --git a/Lib/test/test_time.py b/Lib/test/test_time.py index 8d8d31e7825..80e43fafad8 100644 --- a/Lib/test/test_time.py +++ b/Lib/test/test_time.py @@ -825,7 +825,7 @@ class CPyTimeTestCase: try: result = pytime_converter(value, time_rnd) expected = expected_func(value) - except Exception as exc: + except Exception: self.fail("Error on timestamp conversion: %s" % debug_info) self.assertEqual(result, expected, diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py index 72dc7afb8c5..7135d997d54 100644 --- a/Lib/test/test_traceback.py +++ b/Lib/test/test_traceback.py @@ -313,7 +313,7 @@ class TracebackFormatTests(unittest.TestCase): with captured_output("stderr") as stderr_f: try: f() - except RecursionError as exc: + except RecursionError: render_exc() else: self.fail("no recursion occurred") @@ -360,7 +360,7 @@ class TracebackFormatTests(unittest.TestCase): with captured_output("stderr") as stderr_g: try: g() - except ValueError as exc: + except ValueError: render_exc() else: self.fail("no value error was raised") @@ -396,7 +396,7 @@ class TracebackFormatTests(unittest.TestCase): with captured_output("stderr") as stderr_h: try: h() - except ValueError as exc: + except ValueError: render_exc() else: self.fail("no value error was raised") @@ -424,7 +424,7 @@ class TracebackFormatTests(unittest.TestCase): with captured_output("stderr") as stderr_g: try: g(traceback._RECURSIVE_CUTOFF) - except ValueError as exc: + except ValueError: render_exc() else: self.fail("no error raised") @@ -452,7 +452,7 @@ class TracebackFormatTests(unittest.TestCase): with captured_output("stderr") as stderr_g: try: g(traceback._RECURSIVE_CUTOFF + 1) - except ValueError as exc: + except ValueError: render_exc() else: self.fail("no error raised") diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py index 040a2ce276d..bb0500e12a4 100644 --- a/Lib/test/test_urllib2net.py +++ b/Lib/test/test_urllib2net.py @@ -199,7 +199,7 @@ class OtherNetworkTests(unittest.TestCase): try: with urllib.request.urlopen(URL) as res: pass - except ValueError as e: + except ValueError: self.fail("urlopen failed for site not sending \ Connection:close") else: diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py index ddf7e6dc1b8..b76c60e1ce2 100644 --- a/Lib/test/test_uuid.py +++ b/Lib/test/test_uuid.py @@ -471,7 +471,7 @@ class BaseTestUUID: # the value from too_large_getter above. try: self.uuid.uuid1(node=node) - except ValueError as e: + except ValueError: self.fail('uuid1 was given an invalid node ID') def test_uuid1(self): diff --git a/Lib/unittest/case.py b/Lib/unittest/case.py index bac9789c943..fa64a6ea237 100644 --- a/Lib/unittest/case.py +++ b/Lib/unittest/case.py @@ -712,7 +712,7 @@ class TestCase(object): function, args, kwargs = cls._class_cleanups.pop() try: function(*args, **kwargs) - except Exception as exc: + except Exception: cls.tearDown_exceptions.append(sys.exc_info()) def __call__(self, *args, **kwds): diff --git a/Lib/urllib/request.py b/Lib/urllib/request.py index 721c152179e..ebc41184f83 100644 --- a/Lib/urllib/request.py +++ b/Lib/urllib/request.py @@ -1778,7 +1778,7 @@ class URLopener: hdrs = fp.info() fp.close() return url2pathname(_splithost(url1)[1]), hdrs - except OSError as msg: + except OSError: pass fp = self.open(url, data) try: diff --git a/Lib/xml/sax/__init__.py b/Lib/xml/sax/__init__.py index a0f5d40b200..17b75879eba 100644 --- a/Lib/xml/sax/__init__.py +++ b/Lib/xml/sax/__init__.py @@ -78,7 +78,7 @@ def make_parser(parser_list=()): for parser_name in list(parser_list) + default_parser_list: try: return _create_parser(parser_name) - except ImportError as e: + except ImportError: import sys if parser_name in sys.modules: # The parser module was found, but importing it