From e7054a81e126cf69ce5eea26cbd10741ea67fe2d Mon Sep 17 00:00:00 2001 From: Bernhard Kaindl Date: Mon, 26 Jun 2023 15:19:07 +0200 Subject: [PATCH] src/lib/pythongen.ml: Fix InternalError(str(exception)) for Py3 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In `src/lib/pythongen.ml`, fix `return InternalError(str(exn)).failure()`: For Python3, `compat_block` defines `str = bytes`: ```ml ; Line "if sys.version_info[0] > 2:" ; Block [ Line "long = int"; Line "unicode = str"; Line "str = bytes" ] ``` The easy fix is to get a copy of `str` and use it to convert `exn` to `str`: ```py get_str = str if PY3: str = bytes ... # In the generated code: return InternalError(get_str(exn).failure()) ``` (Instead, we could also prepend `def get_str(a): return str(a)`, this is just shorter. It would be fine either way.) Without this fix, `str(Exception())`, `compat_block` causes it to be `bytes(Exception())` on Py3. This would raise a `TypeError` because `Exception` can't be converted to `bytes`: ```py $ python3 -c 'str = bytes; str(Exception("hi"))' Traceback (most recent call last): File "", line 1, in TypeError: cannot convert 'Exception' object to bytes ``` Setting `get_str()` to be `str()` for Py2 and Py3 fixes it and gets a `str` for `InternalError.__init__(arg)` (which expects a `str` value as argument) Co-authored-by: Edwin Török Signed-off-by: Bernhard Kaindl --- src/lib/pythongen.ml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/lib/pythongen.ml b/src/lib/pythongen.ml index 424c65d..ead82af 100644 --- a/src/lib/pythongen.ml +++ b/src/lib/pythongen.ml @@ -97,7 +97,8 @@ class ListAction(argparse.Action): let compat_block = - [ Line "if sys.version_info[0] > 2:" + [ Line "get_str = str" + ; Line "if sys.version_info[0] > 2:" ; Block [ Line "long = int"; Line "unicode = str"; Line "str = bytes" ] ; Line "" ] @@ -847,7 +848,7 @@ let of_interfaces ?(helpers = inline_defaults) i = ; Block [ Line {|logging.log("caught %s", exn)|} ; Line "traceback.print_exc()" - ; Line "return InternalError(str(exn)).failure()" + ; Line "return InternalError(get_str(exn)).failure()" ] ] ]