From 7b8e3f9ec83f86b8356d3849162a9853f8722d0b Mon Sep 17 00:00:00 2001 From: Jason Rhinelander Date: Sat, 1 Oct 2016 20:41:14 -0400 Subject: [PATCH] Re-add (but deprecated) bool operator for attr/items PR #425 removed the bool operator from attribute accessors. This is likely in use by existing code as it was the only way before #425 added the `hasattr` function to check for the existence of an attribute, via: if (obj.attr("foo")) { ... } This commit adds it back in for attr and item accessors, but with a deprecation warning to use `hasattr(obj, ...)` or `obj.contains(...)` instead. --- include/pybind11/pytypes.h | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/include/pybind11/pytypes.h b/include/pybind11/pytypes.h index d4c6f39ae..4e5d7f3f8 100644 --- a/include/pybind11/pytypes.h +++ b/include/pybind11/pytypes.h @@ -206,6 +206,18 @@ public: void operator=(handle value) && { Policy::set(obj, key, value); } void operator=(handle value) & { get_cache() = object(value, true); } + template + PYBIND11_DEPRECATED("Use of obj.attr(...) as bool is deprecated in favor of pybind11::hasattr(obj, ...)") + operator enable_if_t::value || + std::is_same::value, bool>() const { + return hasattr(obj, key); + } + template + PYBIND11_DEPRECATED("Use of obj[key] as bool is deprecated in favor of obj.contains(key)") + operator enable_if_t::value, bool>() const { + return obj.contains(key); + } + operator object() const { return get_cache(); } PyObject *ptr() const { return get_cache().ptr(); } template T cast() const { return get_cache().template cast(); }