Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
12 changes: 10 additions & 2 deletions lib/pythonx.ex
Original file line number Diff line number Diff line change
Expand Up @@ -281,9 +281,17 @@ defmodule Pythonx do
defmacro sigil_PY({:<<>>, _meta, [code]}, []) when is_binary(code) do
%{referenced: referenced, defined: defined} = Pythonx.AST.scan_globals(code)

versioned_vars = __CALLER__.versioned_vars
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@josevalim let me know if you have any concerns with this approach :)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let’s use this function instead: https://hexdocs.pm/elixir/Macro.Env.html#has_var?/2

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ohh perfect, I was almost certain we had this function, it's since v1.7 so I don't know how I missed it :D Thanks!


globals_entries =
for name <- referenced do
{name, {String.to_atom(name), [], nil}}
for name <- referenced,
name_atom = String.to_atom(name),
# We only reference variables that are actually defined.
# This way, if an undefined variable is referenced in the
# Python code, it results in an informative Python error,
# rather than Elixir compile error.
Map.has_key?(versioned_vars, {name_atom, nil}) do
{name, {name_atom, [], nil}}
end

assignments =
Expand Down
17 changes: 16 additions & 1 deletion test/pythonx_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,21 @@ defmodule PythonxTest do
assert Keyword.keys(binding) == [:x]
end

test "results in a Python error when a variable is undefined" do
assert_raise Pythonx.Error, ~r/NameError: name 'x' is not defined/, fn ->
Code.eval_string(
~S'''
import Pythonx

~PY"""
x + 1
"""
''',
[]
)
end
end

test "global redefinition" do
{_result, binding} =
Code.eval_string(
Expand Down Expand Up @@ -414,7 +429,7 @@ defmodule PythonxTest do
assert repr(result) == "43"
end

test "does not result in unused variables" do
test "does not result in unused variables diagnostics" do
{_result, diagnostics} =
Code.with_diagnostics(fn ->
Code.eval_string(~s'''
Expand Down
Loading