Skip to content

Commit 56addfa

Browse files
Make globals() cheaper.
1 parent eaeca55 commit 56addfa

File tree

3 files changed

+6
-4
lines changed

3 files changed

+6
-4
lines changed

include/pybind11/detail/non_limited_api.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -186,7 +186,7 @@ PYBIND11_NONLIMITEDAPI_FUNC(PyInterpreterState *, PyInterpreterState_Get, (), ()
186186
PYBIND11_NONLIMITEDAPI_FUNC(PyObject *, PyInterpreterState_GetDict, (PyInterpreterState *state), (state))
187187
PYBIND11_NONLIMITEDAPI_FUNC(int, pybind11_traverse, (PyObject *self, visitproc visit, void *arg), (self, visit, arg))
188188
PYBIND11_NONLIMITEDAPI_FUNC(int, pybind11_clear, (PyObject *self), (self))
189-
PYBIND11_NONLIMITEDAPI_FUNC(void, globals, (dict &out), (out))
189+
PYBIND11_NONLIMITEDAPI_FUNC(void, globals, (std::optional<dict> &out), (out))
190190
PYBIND11_NONLIMITEDAPI_FUNC(PyObject *, dict_getitemstringref, (PyObject *v, const char *key), (v, key))
191191

192192
PYBIND11_NAMESPACE_END(non_limited_api)

include/pybind11/pybind11.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1065,9 +1065,9 @@ using module = module_;
10651065
/// Return a dictionary representing the global variables in the current execution frame,
10661066
/// or ``__main__.__dict__`` if there is no frame (usually when the interpreter is embedded).
10671067
inline dict globals() {
1068-
dict ret;
1068+
std::optional<dict> ret;
10691069
non_limited_api::globals(ret);
1070-
return ret;
1070+
return ret.value();
10711071
}
10721072

10731073
template <typename... Args, typename = detail::enable_if_t<args_are_all_keyword_or_ds<Args...>()>>

source/non_limited_api/non_limited_api.cpp

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1876,8 +1876,10 @@ int pybind11::non_limited_api::pybind11NLA_pybind11_clear(PyObject *self)
18761876
return 0;
18771877
}
18781878

1879-
void pybind11::non_limited_api::pybind11NLA_globals(dict &out)
1879+
void pybind11::non_limited_api::pybind11NLA_globals(std::optional<dict> &out)
18801880
{
1881+
// Here we return via `std::optional`, since default-constructing the receiving dict is apparently not free as I hoped.
1882+
18811883
#if PY_VERSION_HEX >= 0x030d0000
18821884
PyObject *p = PyEval_GetFrameGlobals();
18831885
out = p ? reinterpret_steal<dict>(p)

0 commit comments

Comments
 (0)