Skip to content

Commit

Permalink
Merge pull request #247 from bluetech/no-sys-exc-info
Browse files Browse the repository at this point in the history
Avoid using sys.exc_info
  • Loading branch information
bluetech authored Feb 24, 2024
2 parents 678df09 + 5cdc09f commit 1900890
Show file tree
Hide file tree
Showing 6 changed files with 40 additions and 48 deletions.
6 changes: 2 additions & 4 deletions src/execnet/gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
import inspect
import linecache
import os
import sys
import textwrap
import types

Expand Down Expand Up @@ -56,10 +55,9 @@ def exit(self):
self._send(Message.GATEWAY_TERMINATE)
self._trace("--> io.close_write")
self._io.close_write()
except (ValueError, EOFError, OSError):
v = sys.exc_info()[1]
except (ValueError, EOFError, OSError) as exc:
self._trace("io-error: could not send termination sequence")
self._trace(" exception: %r" % v)
self._trace(" exception: %r" % exc)

def reconfigure(self, py2str_as_py3str=True, py3str_as_py2str=False):
"""
Expand Down
56 changes: 27 additions & 29 deletions src/execnet/gateway_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -289,7 +289,7 @@ def get(self, timeout=None):
try:
return self._result
except AttributeError:
raise self._excinfo[1].with_traceback(self._excinfo[2])
raise self._exc

def waitfinish(self, timeout=None):
if not self._result_ready.wait(timeout):
Expand All @@ -300,10 +300,8 @@ def run(self):
try:
try:
self._result = func(*args, **kwargs)
except BaseException:
# sys may be already None when shutting down the interpreter
if sys is not None:
self._excinfo = sys.exc_info()
except BaseException as exc:
self._exc = exc
finally:
self._result_ready.set()
self.running = False
Expand Down Expand Up @@ -460,10 +458,9 @@ def trace(*msg):
line = " ".join(map(str, msg))
debugfile.write(line + "\n")
debugfile.flush()
except Exception:
except Exception as exc:
try:
v = sys.exc_info()[1]
sys.stderr.write(f"[{pid}] exception during tracing: {v!r}\n")
sys.stderr.write(f"[{pid}] exception during tracing: {exc!r}\n")
except Exception:
pass # nothing we can do, likely interpreter-shutdown

Expand Down Expand Up @@ -530,8 +527,7 @@ def from_io(io):
header = io.read(9) # type 1, channel 4, payload 4
if not header:
raise EOFError("empty read")
except EOFError:
e = sys.exc_info()[1]
except EOFError as e:
raise EOFError("couldn't load message header, " + e.args[0])
msgtype, channel, payload = struct.unpack("!bii", header)
return Message(msgtype, channel, io.read(payload))
Expand Down Expand Up @@ -617,14 +613,20 @@ class GatewayReceivedTerminate(Exception):
"""Receiverthread got termination message."""


def geterrortext(excinfo, format_exception=traceback.format_exception, sysex=sysex):
def geterrortext(
exc: BaseException,
format_exception=traceback.format_exception,
sysex=sysex,
) -> str:
try:
l = format_exception(*excinfo) # noqa:E741
# In py310, can change this to:
# l = format_exception(exc)
l = format_exception(type(exc), exc, exc.__traceback__)
errortext = "".join(l)
except sysex:
raise
except BaseException:
errortext = f"{excinfo[0].__name__}: {excinfo[1]}"
errortext = f"{type(exc).__name__}: {exc}"
return errortext


Expand Down Expand Up @@ -963,10 +965,9 @@ def _local_receive(self, id, data):
try:
data = loads_internal(data, channel, strconfig)
callback(data) # even if channel may be already closed
except Exception:
excinfo = sys.exc_info()
self.gateway._trace("exception during callback: %s" % excinfo[1])
errortext = self.gateway._geterrortext(excinfo)
except Exception as exc:
self.gateway._trace("exception during callback: %s" % exc)
errortext = self.gateway._geterrortext(exc)
self.gateway._send(
Message.CHANNEL_CLOSE_ERROR, id, dumps_internal(errortext)
)
Expand Down Expand Up @@ -1043,7 +1044,6 @@ def readline(self):


class BaseGateway:
exc_info = sys.exc_info
_sysex = sysex
id = "<worker>"

Expand Down Expand Up @@ -1080,11 +1080,11 @@ def log(*msg):
del msg
except (KeyboardInterrupt, GatewayReceivedTerminate):
pass
except EOFError:
except EOFError as exc:
log("EOF without prior gateway termination message")
self._error = self.exc_info()[1]
except Exception:
log(self._geterrortext(self.exc_info()))
self._error = exc
except Exception as exc:
log(self._geterrortext(exc))
log("finishing receiving thread")
# wake up and terminate any execution waiting to receive
self._channelfactory._finished_receiving()
Expand All @@ -1105,8 +1105,7 @@ def _send(self, msgcode, channelid=0, data=b""):
try:
message.to_io(self._io)
self._trace("sent", message)
except (OSError, ValueError):
e = sys.exc_info()[1]
except (OSError, ValueError) as e:
self._trace("failed to send", message, e)
# ValueError might be because the IO is already closed
raise OSError("cannot send (already closed?)")
Expand Down Expand Up @@ -1212,12 +1211,11 @@ def executetask(self, item):
except KeyboardInterrupt:
channel.close(INTERRUPT_TEXT)
raise
except BaseException:
excinfo = self.exc_info()
if not isinstance(excinfo[1], EOFError):
except BaseException as exc:
if not isinstance(exc, EOFError):
if not channel.gateway._channelfactory.finished:
self._trace(f"got exception: {excinfo[1]!r}")
errortext = self._geterrortext(excinfo)
self._trace(f"got exception: {exc!r}")
errortext = self._geterrortext(exc)
channel.close(errortext)
return
self._trace("ignoring EOFError because receiving finished")
Expand Down
4 changes: 2 additions & 2 deletions src/execnet/gateway_socket.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,6 @@ def create_io(spec, group, execmodel):
io.remoteaddress = "%s:%d" % (host, port)
try:
sock.connect((host, port))
except execmodel.socket.gaierror:
raise HostNotFound(str(sys.exc_info()[1]))
except execmodel.socket.gaierror as e:
raise HostNotFound() from e
return io
7 changes: 3 additions & 4 deletions src/execnet/multi.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
(c) 2008-2014, Holger Krekel and others
"""
import atexit
import sys
from functools import partial
from threading import Lock

Expand Down Expand Up @@ -285,11 +284,11 @@ def waitclose(self):
for ch in self._channels:
try:
ch.waitclose()
except ch.RemoteError:
except ch.RemoteError as exc:
if first is None:
first = sys.exc_info()
first = exc
if first:
raise first[1].with_traceback(first[2])
raise first


def safe_terminate(execmodel, timeout, list_of_paired_functions):
Expand Down
5 changes: 2 additions & 3 deletions src/execnet/script/socketserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,14 +94,13 @@ def startserver(serversock, loop=False):
exec_from_one_connection(serversock)
except (KeyboardInterrupt, SystemExit):
raise
except BaseException:
except BaseException as exc:
if debug:
import traceback

traceback.print_exc()
else:
excinfo = sys.exc_info()
print_("got exception", excinfo[1])
print_("got exception", exc)
os.chdir(execute_path)
if not loop:
break
Expand Down
10 changes: 4 additions & 6 deletions testing/test_basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,16 +229,14 @@ def test_geterrortext(checker):
out = checker.run_check(
inspect.getsource(gateway_base)
+ """
class Arg:
class Arg(Exception):
pass
errortext = geterrortext((Arg, "1", 4))
errortext = geterrortext(Arg())
assert "Arg" in errortext
import sys
try:
raise ValueError("17")
except ValueError:
excinfo = sys.exc_info()
s = geterrortext(excinfo)
except ValueError as exc:
s = geterrortext(exc)
assert "17" in s
print ("all passed")
"""
Expand Down

0 comments on commit 1900890

Please sign in to comment.