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
This commit is contained in:
Pablo Galindo 2019-11-19 21:34:03 +00:00 committed by GitHub
parent c6b20be85c
commit 293dd23477
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
28 changed files with 39 additions and 39 deletions

View File

@ -117,7 +117,7 @@ class async_chat(asyncore.dispatcher):
data = self.recv(self.ac_in_buffer_size) data = self.recv(self.ac_in_buffer_size)
except BlockingIOError: except BlockingIOError:
return return
except OSError as why: except OSError:
self.handle_error() self.handle_error()
return return

View File

@ -711,7 +711,7 @@ class BaseProactorEventLoop(base_events.BaseEventLoop):
raise exceptions.SendfileNotAvailableError("not a regular file") raise exceptions.SendfileNotAvailableError("not a regular file")
try: try:
fsize = os.fstat(fileno).st_size fsize = os.fstat(fileno).st_size
except OSError as err: except OSError:
raise exceptions.SendfileNotAvailableError("not a regular file") raise exceptions.SendfileNotAvailableError("not a regular file")
blocksize = count if count else fsize blocksize = count if count else fsize
if not blocksize: if not blocksize:

View File

@ -330,7 +330,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
async def _sock_sendfile_native(self, sock, file, offset, count): async def _sock_sendfile_native(self, sock, file, offset, count):
try: try:
os.sendfile os.sendfile
except AttributeError as exc: except AttributeError:
raise exceptions.SendfileNotAvailableError( raise exceptions.SendfileNotAvailableError(
"os.sendfile() is not available") "os.sendfile() is not available")
try: try:
@ -339,7 +339,7 @@ class _UnixSelectorEventLoop(selector_events.BaseSelectorEventLoop):
raise exceptions.SendfileNotAvailableError("not a regular file") raise exceptions.SendfileNotAvailableError("not a regular file")
try: try:
fsize = os.fstat(fileno).st_size fsize = os.fstat(fileno).st_size
except OSError as err: except OSError:
raise exceptions.SendfileNotAvailableError("not a regular file") raise exceptions.SendfileNotAvailableError("not a regular file")
blocksize = count if count else fsize blocksize = count if count else fsize
if not blocksize: if not blocksize:

View File

@ -80,7 +80,7 @@ def _maybe_compile(compiler, source, filename, symbol):
try: try:
code = compiler(source, filename, symbol) code = compiler(source, filename, symbol)
except SyntaxError as err: except SyntaxError:
pass pass
try: try:

View File

@ -302,7 +302,7 @@ elif os.name == "posix":
res = re.search(expr, os.fsdecode(out)) res = re.search(expr, os.fsdecode(out))
if res: if res:
result = res.group(0) result = res.group(0)
except Exception as e: except Exception:
pass # result will be None pass # result will be None
return result return result

View File

@ -420,7 +420,7 @@ class EnumMeta(type):
if module is None: if module is None:
try: try:
module = sys._getframe(2).f_globals['__name__'] module = sys._getframe(2).f_globals['__name__']
except (AttributeError, ValueError, KeyError) as exc: except (AttributeError, ValueError, KeyError):
pass pass
if module is None: if module is None:
_make_class_unpicklable(enum_class) _make_class_unpicklable(enum_class)

View File

@ -156,12 +156,12 @@ class dircmp:
ok = 1 ok = 1
try: try:
a_stat = os.stat(a_path) a_stat = os.stat(a_path)
except OSError as why: except OSError:
# print('Can\'t stat', a_path, ':', why.args[1]) # print('Can\'t stat', a_path, ':', why.args[1])
ok = 0 ok = 0
try: try:
b_stat = os.stat(b_path) b_stat = os.stat(b_path)
except OSError as why: except OSError:
# print('Can\'t stat', b_path, ':', why.args[1]) # print('Can\'t stat', b_path, ':', why.args[1])
ok = 0 ok = 0

View File

@ -52,7 +52,7 @@ def unix_getpass(prompt='Password: ', stream=None):
stack.enter_context(input) stack.enter_context(input)
if not stream: if not stream:
stream = input stream = input
except OSError as e: except OSError:
# If that fails, see if stdin can be controlled. # If that fails, see if stdin can be controlled.
stack.close() stack.close()
try: try:

View File

@ -10,7 +10,7 @@ except ImportError as exc:
_frozen_importlib = None _frozen_importlib = None
try: try:
import _frozen_importlib_external import _frozen_importlib_external
except ImportError as exc: except ImportError:
_frozen_importlib_external = _bootstrap_external _frozen_importlib_external = _bootstrap_external
import abc import abc
import warnings import warnings

View File

@ -90,11 +90,11 @@ class StdoutRefactoringTool(refactor.MultiprocessRefactoringTool):
if os.path.lexists(backup): if os.path.lexists(backup):
try: try:
os.remove(backup) os.remove(backup)
except OSError as err: except OSError:
self.log_message("Can't remove backup %s", backup) self.log_message("Can't remove backup %s", backup)
try: try:
os.rename(filename, backup) os.rename(filename, backup)
except OSError as err: except OSError:
self.log_message("Can't rename %s to %s", filename, backup) self.log_message("Can't rename %s to %s", filename, backup)
# Actually write the new file # Actually write the new file
write = super(StdoutRefactoringTool, self).write_file write = super(StdoutRefactoringTool, self).write_file

View File

@ -116,7 +116,7 @@ def add_data(db, table, values):
raise TypeError("Unsupported type %s" % field.__class__.__name__) raise TypeError("Unsupported type %s" % field.__class__.__name__)
try: try:
v.Modify(MSIMODIFY_INSERT, r) v.Modify(MSIMODIFY_INSERT, r)
except Exception as e: except Exception:
raise MSIError("Could not insert "+repr(values)+" into "+table) raise MSIError("Could not insert "+repr(values)+" into "+table)
r.ClearData() r.ClearData()

View File

@ -248,7 +248,7 @@ class Server(object):
try: try:
obj, exposed, gettypeid = \ obj, exposed, gettypeid = \
self.id_to_local_proxy_obj[ident] self.id_to_local_proxy_obj[ident]
except KeyError as second_ke: except KeyError:
raise ke raise ke
if methodname not in exposed: if methodname not in exposed:
@ -296,7 +296,7 @@ class Server(object):
try: try:
try: try:
send(msg) send(msg)
except Exception as e: except Exception:
send(('#UNSERIALIZABLE', format_exc())) send(('#UNSERIALIZABLE', format_exc()))
except Exception as e: except Exception as e:
util.info('exception in thread serving %r', util.info('exception in thread serving %r',

View File

@ -25,7 +25,7 @@ class Popen(object):
if self.returncode is None: if self.returncode is None:
try: try:
pid, sts = os.waitpid(self.pid, flag) pid, sts = os.waitpid(self.pid, flag)
except OSError as e: except OSError:
# Child process not yet created. See #1731717 # Child process not yet created. See #1731717
# e.errno == errno.ECHILD == 10 # e.errno == errno.ECHILD == 10
return None return None

View File

@ -385,7 +385,7 @@ class POP3:
for capline in rawcaps: for capline in rawcaps:
capnm, capargs = _parsecap(capline) capnm, capargs = _parsecap(capline)
caps[capnm] = capargs caps[capnm] = capargs
except error_proto as _err: except error_proto:
raise error_proto('-ERR CAPA not supported by server') raise error_proto('-ERR CAPA not supported by server')
return caps return caps

View File

@ -754,7 +754,7 @@ def collect_info(info):
): ):
try: try:
collect_func(info_add) collect_func(info_add)
except Exception as exc: except Exception:
error = True error = True
print("ERROR: %s() failed" % (collect_func.__name__), print("ERROR: %s() failed" % (collect_func.__name__),
file=sys.stderr) file=sys.stderr)

View File

@ -31,7 +31,7 @@ class TestCgitb(unittest.TestCase):
def test_text(self): def test_text(self):
try: try:
raise ValueError("Hello World") raise ValueError("Hello World")
except ValueError as err: except ValueError:
text = cgitb.text(sys.exc_info()) text = cgitb.text(sys.exc_info())
self.assertIn("ValueError", text) self.assertIn("ValueError", text)
self.assertIn("Hello World", text) self.assertIn("Hello World", text)

View File

@ -529,7 +529,7 @@ class ClassTests(unittest.TestCase):
# In debug mode, printed XXX undetected error and # In debug mode, printed XXX undetected error and
# raises AttributeError # raises AttributeError
I() I()
except AttributeError as x: except AttributeError:
pass pass
else: else:
self.fail("attribute error for I.__init__ got masked") self.fail("attribute error for I.__init__ got masked")

View File

@ -11,7 +11,7 @@ from test import support
try: try:
import _testcapi import _testcapi
except ImportError as exc: except ImportError:
_testcapi = None _testcapi = None
try: try:

View File

@ -5600,13 +5600,13 @@ class SignatureTest(unittest.TestCase):
args, kwds = mkargs(C, c_sig) args, kwds = mkargs(C, c_sig)
try: try:
getattr(c_type(9), attr)(*args, **kwds) 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)) raise TestFailed("invalid signature for %s: %s %s" % (c_func, args, kwds))
args, kwds = mkargs(P, p_sig) args, kwds = mkargs(P, p_sig)
try: try:
getattr(p_type(9), attr)(*args, **kwds) 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)) raise TestFailed("invalid signature for %s: %s %s" % (p_func, args, kwds))
doit('Decimal') doit('Decimal')

View File

@ -346,7 +346,7 @@ if ssl is not None:
if err.args[0] in (ssl.SSL_ERROR_WANT_READ, if err.args[0] in (ssl.SSL_ERROR_WANT_READ,
ssl.SSL_ERROR_WANT_WRITE): ssl.SSL_ERROR_WANT_WRITE):
return return
except OSError as err: except OSError:
# Any "socket error" corresponds to a SSL_ERROR_SYSCALL return # Any "socket error" corresponds to a SSL_ERROR_SYSCALL return
# from OpenSSL's SSL_shutdown(), corresponding to a # from OpenSSL's SSL_shutdown(), corresponding to a
# closed socket condition. See also: # closed socket condition. See also:

View File

@ -161,8 +161,8 @@ def raises():
def test_raise(): def test_raise():
try: try:
raises() raises()
except Exception as exc: except Exception:
x = 1 pass
test_raise.events = [(0, 'call'), test_raise.events = [(0, 'call'),
(1, 'line'), (1, 'line'),
@ -191,7 +191,7 @@ def _settrace_and_raise(tracefunc):
def settrace_and_raise(tracefunc): def settrace_and_raise(tracefunc):
try: try:
_settrace_and_raise(tracefunc) _settrace_and_raise(tracefunc)
except RuntimeError as exc: except RuntimeError:
pass pass
settrace_and_raise.events = [(2, 'exception'), settrace_and_raise.events = [(2, 'exception'),

View File

@ -825,7 +825,7 @@ class CPyTimeTestCase:
try: try:
result = pytime_converter(value, time_rnd) result = pytime_converter(value, time_rnd)
expected = expected_func(value) expected = expected_func(value)
except Exception as exc: except Exception:
self.fail("Error on timestamp conversion: %s" % debug_info) self.fail("Error on timestamp conversion: %s" % debug_info)
self.assertEqual(result, self.assertEqual(result,
expected, expected,

View File

@ -313,7 +313,7 @@ class TracebackFormatTests(unittest.TestCase):
with captured_output("stderr") as stderr_f: with captured_output("stderr") as stderr_f:
try: try:
f() f()
except RecursionError as exc: except RecursionError:
render_exc() render_exc()
else: else:
self.fail("no recursion occurred") self.fail("no recursion occurred")
@ -360,7 +360,7 @@ class TracebackFormatTests(unittest.TestCase):
with captured_output("stderr") as stderr_g: with captured_output("stderr") as stderr_g:
try: try:
g() g()
except ValueError as exc: except ValueError:
render_exc() render_exc()
else: else:
self.fail("no value error was raised") self.fail("no value error was raised")
@ -396,7 +396,7 @@ class TracebackFormatTests(unittest.TestCase):
with captured_output("stderr") as stderr_h: with captured_output("stderr") as stderr_h:
try: try:
h() h()
except ValueError as exc: except ValueError:
render_exc() render_exc()
else: else:
self.fail("no value error was raised") self.fail("no value error was raised")
@ -424,7 +424,7 @@ class TracebackFormatTests(unittest.TestCase):
with captured_output("stderr") as stderr_g: with captured_output("stderr") as stderr_g:
try: try:
g(traceback._RECURSIVE_CUTOFF) g(traceback._RECURSIVE_CUTOFF)
except ValueError as exc: except ValueError:
render_exc() render_exc()
else: else:
self.fail("no error raised") self.fail("no error raised")
@ -452,7 +452,7 @@ class TracebackFormatTests(unittest.TestCase):
with captured_output("stderr") as stderr_g: with captured_output("stderr") as stderr_g:
try: try:
g(traceback._RECURSIVE_CUTOFF + 1) g(traceback._RECURSIVE_CUTOFF + 1)
except ValueError as exc: except ValueError:
render_exc() render_exc()
else: else:
self.fail("no error raised") self.fail("no error raised")

View File

@ -199,7 +199,7 @@ class OtherNetworkTests(unittest.TestCase):
try: try:
with urllib.request.urlopen(URL) as res: with urllib.request.urlopen(URL) as res:
pass pass
except ValueError as e: except ValueError:
self.fail("urlopen failed for site not sending \ self.fail("urlopen failed for site not sending \
Connection:close") Connection:close")
else: else:

View File

@ -471,7 +471,7 @@ class BaseTestUUID:
# the value from too_large_getter above. # the value from too_large_getter above.
try: try:
self.uuid.uuid1(node=node) self.uuid.uuid1(node=node)
except ValueError as e: except ValueError:
self.fail('uuid1 was given an invalid node ID') self.fail('uuid1 was given an invalid node ID')
def test_uuid1(self): def test_uuid1(self):

View File

@ -712,7 +712,7 @@ class TestCase(object):
function, args, kwargs = cls._class_cleanups.pop() function, args, kwargs = cls._class_cleanups.pop()
try: try:
function(*args, **kwargs) function(*args, **kwargs)
except Exception as exc: except Exception:
cls.tearDown_exceptions.append(sys.exc_info()) cls.tearDown_exceptions.append(sys.exc_info())
def __call__(self, *args, **kwds): def __call__(self, *args, **kwds):

View File

@ -1778,7 +1778,7 @@ class URLopener:
hdrs = fp.info() hdrs = fp.info()
fp.close() fp.close()
return url2pathname(_splithost(url1)[1]), hdrs return url2pathname(_splithost(url1)[1]), hdrs
except OSError as msg: except OSError:
pass pass
fp = self.open(url, data) fp = self.open(url, data)
try: try:

View File

@ -78,7 +78,7 @@ def make_parser(parser_list=()):
for parser_name in list(parser_list) + default_parser_list: for parser_name in list(parser_list) + default_parser_list:
try: try:
return _create_parser(parser_name) return _create_parser(parser_name)
except ImportError as e: except ImportError:
import sys import sys
if parser_name in sys.modules: if parser_name in sys.modules:
# The parser module was found, but importing it # The parser module was found, but importing it