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 f0a9ebd
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 0 deletions.
6 changes: 6 additions & 0 deletions docs/changelog.rst
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
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
10 changes: 10 additions & 0 deletions tests/test_eval.cpp
Expand Up @@ -74,4 +74,14 @@ NB_MODULE(test_eval_ext, m) {
local);
return std::make_pair(global, local);
});

m.def("globals_contains_a", []() {
return nb::globals().contains("a");
});

m.def("globals_add_b", []() {
auto globals = nb::globals();
globals["b"] = 123;
return globals;
});
}
11 changes: 11 additions & 0 deletions tests/test_eval.py
Expand Up @@ -31,3 +31,14 @@ def test_eval_closure():
assert "func_local" not in global_
with pytest.raises(NameError):
local["func_local"]()

a = 1

def test_read_globals():
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 f0a9ebd

Please sign in to comment.