Skip to content

Commit 6ac8efe

Browse files
EricCousineau-TRIYannickJadoulSkylion007
authored
test_eval: Show example of working closure (#2743)
* test_eval: Show example of working closure * Extend test_eval_closure with weirder examples of closures for py::eval Co-authored-by: Yannick Jadoul <yannick.jadoul@belgacom.net> Co-authored-by: Aaron Gokaslan <skylion.aaron@gmail.com>
1 parent af70073 commit 6ac8efe

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

tests/test_eval.cpp

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,4 +98,22 @@ TEST_SUBMODULE(eval_, m) {
9898
auto int_class = py::eval("isinstance(42, int)", global);
9999
return global;
100100
});
101+
102+
// test_eval_closure
103+
m.def("test_eval_closure", []() {
104+
py::dict global;
105+
global["closure_value"] = 42;
106+
py::dict local;
107+
local["closure_value"] = 0;
108+
py::exec(R"(
109+
local_value = closure_value
110+
111+
def func_global():
112+
return closure_value
113+
114+
def func_local():
115+
return local_value
116+
)", global, local);
117+
return std::make_pair(global, local);
118+
});
101119
}

tests/test_eval.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,20 @@ def test_eval_empty_globals():
3333
g = {}
3434
assert "__builtins__" in m.eval_empty_globals(g)
3535
assert "__builtins__" in g
36+
37+
38+
def test_eval_closure():
39+
global_, local = m.test_eval_closure()
40+
41+
assert global_["closure_value"] == 42
42+
assert local["closure_value"] == 0
43+
44+
assert "local_value" not in global_
45+
assert local["local_value"] == 0
46+
47+
assert "func_global" not in global_
48+
assert local["func_global"]() == 42
49+
50+
assert "func_local" not in global_
51+
with pytest.raises(NameError):
52+
local["func_local"]()

0 commit comments

Comments
 (0)