From 6ac8efe52dfd8b15caec0e376d677cadd9bec38c Mon Sep 17 00:00:00 2001 From: Eric Cousineau Date: Fri, 6 Aug 2021 15:51:53 -0400 Subject: [PATCH] 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 Co-authored-by: Aaron Gokaslan --- tests/test_eval.cpp | 18 ++++++++++++++++++ tests/test_eval.py | 17 +++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/tests/test_eval.cpp b/tests/test_eval.cpp index 16cdf17f2..29366f679 100644 --- a/tests/test_eval.cpp +++ b/tests/test_eval.cpp @@ -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); + }); } diff --git a/tests/test_eval.py b/tests/test_eval.py index 1bb05af05..601e526f4 100644 --- a/tests/test_eval.py +++ b/tests/test_eval.py @@ -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"]()