Skip to content
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

test_eval: Show example of working closure #2743

Merged
merged 3 commits into from
Aug 6, 2021
Merged
Show file tree
Hide file tree
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
18 changes: 18 additions & 0 deletions tests/test_eval.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -98,4 +98,22 @@ TEST_SUBMODULE(eval_, m) {
auto int_class = py::eval("isinstance(42, int)", global);
return global;
});

// test_eval_closure
m.def("test_eval_closure", []() {
py::dict global;
global["closure_value"] = 42;
py::dict local;
local["closure_value"] = 0;
py::exec(R"(
local_value = closure_value

def func_global():
return closure_value

def func_local():
return local_value
)", global, local);
return std::make_pair(global, local);
});
}
17 changes: 17 additions & 0 deletions tests/test_eval.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,20 @@ def test_eval_empty_globals():
g = {}
assert "__builtins__" in m.eval_empty_globals(g)
assert "__builtins__" in g


def test_eval_closure():
global_, local = m.test_eval_closure()

assert global_["closure_value"] == 42
assert local["closure_value"] == 0

assert "local_value" not in global_
assert local["local_value"] == 0

assert "func_global" not in global_
assert local["func_global"]() == 42

assert "func_local" not in global_
with pytest.raises(NameError):
local["func_local"]()