diff --git a/docs/changelog.rst b/docs/changelog.rst index c50a8bfb..6123508f 100644 --- a/docs/changelog.rst +++ b/docs/changelog.rst @@ -15,6 +15,12 @@ case, both modules must use the same nanobind ABI version, or they will be isolated from each other. Releases that don't explicitly mention an ABI version below inherit that of the preceding release. +Version 1.7.0 (TBA) +------------------- + +* Added :cpp:func:`nb::globals() `. (PR `#311 + `__). + Version 1.6.2 (Oct 3, 2023) ------------------- diff --git a/include/nanobind/nb_misc.h b/include/nanobind/nb_misc.h index 9f93a7b2..319fbda6 100644 --- a/include/nanobind/nb_misc.h +++ b/include/nanobind/nb_misc.h @@ -39,6 +39,13 @@ inline void set_implicit_cast_warnings(bool value) noexcept { detail::set_implicit_cast_warnings(value); } +inline dict globals() { + PyObject *p = PyEval_GetGlobals(); + if (!p) + detail::raise("nanobind::globals(): no frame is currently executing!"); + return borrow(p); +} + inline bool is_alive() noexcept { return detail::is_alive(); } diff --git a/tests/test_globals.cpp b/tests/test_globals.cpp new file mode 100644 index 00000000..59aaf4e5 --- /dev/null +++ b/tests/test_globals.cpp @@ -0,0 +1,15 @@ +#include + +namespace nb = nanobind; + +NB_MODULE(test_eval_ext, m) { + m.def("globals_contains_a", []() { + return nb::globals().contains("a"); + }); + + m.def("globals_add_b", []() { + auto globals = nb::globals(); + globals["b"] = 123; + return globals; + }); +} diff --git a/tests/test_globals.py b/tests/test_globals.py new file mode 100644 index 00000000..45cc9c40 --- /dev/null +++ b/tests/test_globals.py @@ -0,0 +1,10 @@ + +def test_read_globals(): + a = 1 + assert m.globals_contains_a() + + +def test_write_globals(): + assert "b" not in globals() + m.globals_add_b() + assert globals()["b"] == 123