31 #ifndef PYBIND_DICT_UTILS_H_ 32 #define PYBIND_DICT_UTILS_H_ 34 #include <pybind11/pybind11.h> 36 #include <dictobject.h> 55 inline py::object
get(
const py::dict& dict,
const char* key, py::handle default_ = py::none(),
bool noneIsEmpty =
true)
57 PyObject* result = PyDict_GetItemString(dict.ptr(), key);
58 if (result && (!noneIsEmpty || result != Py_None)) {
59 return py::reinterpret_borrow<py::object>(result);
63 return py::reinterpret_borrow<py::object>(default_);
81 template<typename T, typename std::enable_if<!std::is_pointer<T>::value,
int>::type = 0>
82 inline T
get_cast(
const py::dict& dict,
const char* key, T default_,
bool noneIsEmpty =
true)
84 PyObject* result = PyDict_GetItemString(dict.ptr(), key);
85 if (result && (!noneIsEmpty || result != Py_None)) {
86 return py::handle(result).cast<T>();
90 return std::forward<T>(default_);
101 struct cast_pointer_proxy
104 py::detail::make_caster<T> caster;
107 cast_pointer_proxy(T* val)
112 cast_pointer_proxy(
const py::handle& handle)
114 if (handle.is_none()) {
119 py::detail::load_type(caster, handle);
120 ptr = py::detail::cast_op<T*>(caster);
153 template<typename T, typename std::enable_if<std::is_pointer<T>::value,
int>::type = 0>
154 inline detail::cast_pointer_proxy<typename std::remove_pointer<T>::type>
155 get_cast(
const py::dict& dict,
const char* key, T&& default_ = NULL)
157 if (PyObject* result = PyDict_GetItemString(dict.ptr(), key)) {
179 inline bool try_get(
const py::dict& dict,
const char* key, T& var)
181 if (PyObject* result = PyDict_GetItemString(dict.ptr(), key)) {
182 var = pybind11::handle(result).cast<T>();
203 inline bool try_get(
const py::dict& dict,
const std::string& key, T& var)
205 if (PyObject* result = PyDict_GetItemString(dict.ptr(), key.c_str())) {
206 var = pybind11::handle(result).cast<T>();
T get_cast(const py::dict &dict, const char *key, T default_, bool noneIsEmpty=true)
bool try_get(const py::dict &dict, const char *key, T &var)