JuliaPy / PythonCall.jl

Python and Julia in harmony.
https://juliapy.github.io/PythonCall.jl/stable/
MIT License
776 stars 63 forks source link

Raising python errors from Julia functions #357

Closed lassepe closed 1 year ago

lassepe commented 1 year ago

Some python package apis require the user the raise specific errors in certain scenarios. For example, Optuna requires the user to conditionally TrialPruned() error. In the current implementation of PythonCall, raising such errors from julia functions does not seem to be possible.

@pyeval `raise optuna.TrialPruned()`

fails with Python: SyntaxError: invalid syntax.

It would be handy to have a function like pyraise to throw such errors manually.

cjdoris commented 1 year ago

You want @pyexec (for executing arbitrary python code) not @pyeval (which evaluates a single expression):

julia> using PythonCall

julia> @pyeval `raise ValueError("hello")`
ERROR: Python: SyntaxError: invalid syntax (REPL[2]:1, line 1)

julia> @pyexec `raise ValueError("hello")`
ERROR: Python: ValueError: hello
lassepe commented 1 year ago

Nice, this works like charm! Thank you :)