Implement an enum_ property "name"

The property returns the enum_ value as a string.
For example:

>>> import module
>>> module.enum.VALUE
enum.VALUE
>>> str(module.enum.VALUE)
'enum.VALUE'
>>> module.enum.VALUE.name
'VALUE'

This is actually the equivalent of Boost.Python "name" property.
This commit is contained in:
Boris Staletic
2018-04-02 23:26:48 +02:00
committed by Jason Rhinelander
parent 6862cb9b35
commit 289e5d9cc2
3 changed files with 39 additions and 0 deletions

View File

@@ -1364,6 +1364,7 @@ detail::initimpl::pickle_factory<GetState, SetState> pickle(GetState &&g, SetSta
template <typename Type> class enum_ : public class_<Type> {
public:
using class_<Type>::def;
using class_<Type>::def_property_readonly;
using class_<Type>::def_property_readonly_static;
using Scalar = typename std::underlying_type<Type>::type;
@@ -1381,6 +1382,13 @@ public:
}
return pybind11::str("{}.???").format(name);
});
def_property_readonly("name", [m_entries_ptr](Type value) -> pybind11::str {
for (const auto &kv : reinterpret_borrow<dict>(m_entries_ptr)) {
if (pybind11::cast<Type>(kv.second[int_(0)]) == value)
return pybind11::str(kv.first);
}
return pybind11::str("???");
});
def_property_readonly_static("__doc__", [m_entries_ptr](handle self) {
std::string docstring;
const char *tp_doc = ((PyTypeObject *) self.ptr())->tp_doc;