7 #ifndef MDS_UTILS_PYTHON_OBJ_HPP_INCLUDED 8 #define MDS_UTILS_PYTHON_OBJ_HPP_INCLUDED 42 Obj get<Obj>(PyObject *po);
103 void reset_m_attr() {
111 m_o(o),attr_name(attr),
120 m_attr = PyObject_GetAttrString(m_o,attr_name.c_str());
128 operator PyObject* () {
149 if (PyObject_SetAttrString(m_o,attr_name.c_str(),m_attr) == -1) {
150 throw std::runtime_error(
"Cannot assign to attribute " +
177 throw std::logic_error(
"The object is not callable");
190 if (result == NULL) {
191 throw std::runtime_error(
"Object call failed.");
198 Obj() : decref_on_destroy(0),m_po(NULL) {}
210 Obj(
const Obj& rhs) : decref_on_destroy(0),m_po(rhs.m_po) {
253 Obj(PyObject *po) : decref_on_destroy(0),m_po(po) {}
258 if (&rhs ==
this)
return *
this;
285 virtual Obj& operator =(PyObject *po) {
286 if (m_po == po)
return *
this;
308 Obj& operator =(
const T& val) {
338 operator PyObject* ()
const {
352 PyObject *pret(m_po);
370 if (decref_on_destroy > 0) {
387 return PyObject_HasAttrString(m_po,name.c_str()) == 1;
421 return PyCallable_Check(m_po) == 1;
440 result(PyObject_CallObject(*
this,NULL));
472 result(PyObject_CallObject(*
this,args));
509 result(PyObject_Call(*
this,args,kw));
527 inline Obj get<Obj>(PyObject *po) {
Proxy class for managing attribute access.
void reset()
Resets the object to the state given by the default constructor.
void check_call_result(PyObject *result)
Checks if the result of the object call was successful.
virtual void incref()
Increments the reference count using Py_XINCREF.
PyObject * to_python(void)
Converts a value into a Python object.
Main namespace of all Michele De Stefano's C++ utilities.
Obj(const Obj &rhs)
The copy-constructor.
Obj()
Default constructor.
bool is_callable() const
Checks if the object is callable.
Obj operator()(const Obj &args, const Obj &kw)
Calling operator, with positional and keyword arguments.
PyObject * m_po
Underlying pointer to the wrapped Python object.
bool has_attr(const std::string &name) const
Tests if the object has a particular attribute.
Obj(Obj &&rhs)
Move constructor.
virtual ~Obj()
Destructor.
void check_callable()
Checks if the object is callable.
void get_ownership()
Used in place of incref, when the wrapped PyObject* was increfed already.
Obj operator()()
Calling operator.
virtual PyObject * transfer()
Returns the Python object with transferred ownership.
Obj(ProxyAttr &&rhs)
Move constructor from ProxyAttr objects.
ProxyAttr attr(const std::string &name)
Retrieves an attribute.
virtual void decref()
Decrements the reference count using Py_XDECREF.
PyObject * getPyObject() const
Returns the underlying PyObject.
Utilities for converting data from/to Python.
Obj operator()(const Obj &args)
Calling operator, with positional arguments.
Obj(PyObject *po)
Construct from a Python object.
This is a simple wrapper around the PyObject* datatype.