Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add nb::globals #311

Merged
merged 10 commits into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions docs/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,13 @@ 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.6.2 (TBA)
-------------------

* Added :cpp:func:`nb::globals() <globals>`. (PR `#311
<https://github.com/wjakob/nanobind/pull/311>`__).


Version 1.6.1 (Oct 2, 2023)
-------------------

Expand Down
8 changes: 8 additions & 0 deletions include/nanobind/nb_misc.h
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,12 @@ inline void set_implicit_cast_warnings(bool value) noexcept {
detail::set_implicit_cast_warnings(value);
}

/// \ingroup python_builtins
/// Return a dictionary representing the global variables in the current execution frame,
nschloe marked this conversation as resolved.
Show resolved Hide resolved
/// or ``__main__.__dict__`` if there is no frame.
inline dict globals() {
PyObject *p = PyEval_GetGlobals();
nschloe marked this conversation as resolved.
Show resolved Hide resolved
return borrow<dict>(p ? p : module_::import_("__main__").attr("__dict__").ptr());
}

NAMESPACE_END(NB_NAMESPACE)
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