Skip to content

Commit

Permalink
added nb::globals() function wrapping PyEval_GetGlobals() (#311)
Browse files Browse the repository at this point in the history
  • Loading branch information
nschloe authored and wjakob committed Oct 6, 2023
1 parent 7e4a88b commit 57a6ff0
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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() <globals>`. (PR `#311
<https://github.com/wjakob/nanobind/pull/311>`__).

Version 1.6.2 (Oct 3, 2023)
-------------------

Expand Down
7 changes: 7 additions & 0 deletions include/nanobind/nb_misc.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<dict>(p);
}

inline bool is_alive() noexcept {
return detail::is_alive();
}
Expand Down
15 changes: 15 additions & 0 deletions tests/test_globals.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include <nanobind/nanobind.h>

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;
});
}
10 changes: 10 additions & 0 deletions tests/test_globals.py
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 57a6ff0

Please sign in to comment.