Skip to content

Ensure pythonx application is started before eval #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 11, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 22 additions & 6 deletions lib/pythonx.ex
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,11 @@ defmodule Pythonx do
{Object.t() | nil, %{optional(String.t()) => Object.t()}}
def eval(code, globals, opts \\ [])
when is_binary(code) and is_map(globals) and is_list(opts) do
if not pythonx_started?() do
raise RuntimeError,
"the :pythonx application needs to be started before calling Pythonx.eval/3"
end

opts = Keyword.validate!(opts, [:stdout_device, :stderr_device])

globals =
Expand Down Expand Up @@ -244,6 +249,10 @@ defmodule Pythonx do
result
end

defp pythonx_started?() do
Process.whereis(Pythonx.Supervisor) != nil
end

@doc ~S'''
Convenience macro for Python code evaluation.

Expand Down Expand Up @@ -313,12 +322,19 @@ defmodule Pythonx do
result
end
rescue
RuntimeError ->
raise RuntimeError,
"using ~PY sigil requires the Python interpreter to be already initialized. " <>
"This sigil is designed for dynamic evaluation environments, such as IEx or Livebook. " <>
"If that is your case, make sure you initialized the interpreter first, otherwise " <>
"use Pythonx.eval/2 instead. For more details see Pythonx.sigil_PY/2 docs"
error in RuntimeError ->
message = Exception.message(error)

if message =~ "has not been initialized" do
raise RuntimeError,
Exception.message(error) <>
"using ~PY sigil requires the Python interpreter to be already initialized. " <>
"This sigil is designed for dynamic evaluation environments, such as IEx or Livebook. " <>
"If that is your case, make sure you initialized the interpreter first, otherwise " <>
"use Pythonx.eval/2 instead. For more details see Pythonx.sigil_PY/2 docs"
else
reraise(error, __STACKTRACE__)
end
end

@doc """
Expand Down