[C++-sig] howto check for an attr from c++?

Stefan Seefeld seefeld at sympatico.ca
Fri Apr 13 15:57:23 CEST 2007


Neal Becker wrote:
> Stefan Seefeld wrote:
> 
>> Neal Becker wrote:
>>> I need to check if an object has an attribute from c++.
>>>
>>> I'm using this low-level approach:
>>> (r is an object):
>>>     if (PyObject_HasAttrString (r.ptr(), "__len__")) {
>>>
>>> Nothing wrong with that, but is there something in the boost::python api
>>> to handle this?
>> boost::python does provide getattr(), setattr(), and delattr().
>>
>> HTH,
>> Stefan
>>
> 
> If I call getattr() on a nonexistent attribute, what happens?  Does python
> throw an exception?  (I believe it does). If so, how do I intercept it from
> c++?  I'm trying to test is an attribute is defined.

Unfortunately I couldn't find any documentation for the above. (David ?)

However, I did find two versions of getattr(), one taking two arguments,
one taking three. The latter allows to pass a default return value, as supported
by python's own "getattr(o, key, default)". So, at least that last one clearly
doesn't throw (and I would expect the former to simply use a default of None,
i.e. object().

Just try it !

HTH,
		Stefan

-- 

      ...ich hab' noch einen Koffer in Berlin...



More information about the Cplusplus-sig mailing list