Skip to content

Commit

Permalink
src/lib/pythongen.ml: Fix InternalError(str(exception)) for Py3
Browse files Browse the repository at this point in the history
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 "<string>", line 1, in <module>
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 <[email protected]>
Signed-off-by: Bernhard Kaindl <[email protected]>
  • Loading branch information
bernhardkaindl and edwintorok committed Jun 26, 2023
1 parent 13ff10a commit e7054a8
Showing 1 changed file with 3 additions and 2 deletions.
5 changes: 3 additions & 2 deletions src/lib/pythongen.ml
Original file line number Diff line number Diff line change
Expand Up @@ -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 ""
]
Expand Down Expand Up @@ -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()"
]
]
]
Expand Down

0 comments on commit e7054a8

Please sign in to comment.