[C++-sig] Checking for or null PyObject* or PyNone
Jim Bosch
talljimbo at gmail.com
Mon Feb 8 03:32:32 CET 2010
On Sun, 2010-02-07 at 11:47 +0100, Murray Cumming wrote:
> Doing this
> boost::python::object obj = get_some_object();
> if(obj)
> {
> //do something
> }
> seems to check a bool value inside the underlying PyObject, though I
> guess that could throw an exception if it doesn't contain actually
> contain a bool. Is that right?
> The reference documentation is not very clear about this:
> http://www.boost.org/doc/libs/1_42_0/libs/python/doc/v2/object.html
>
>
> I had wrongly guessed that it would check if the underlying PyObject*
> was 0. I did this because I had wrapped a PyObject* in a
> boost::python::object for convenience, without checking for 0 first.
>
I believe the checking happens typically in boost::python::handle, which
is an intermediate between PyObject* and boost::python::object. When
you construct a handle, you can pass wrap it with null_ok if you don't
want it to throw on NULL; otherwise I think it would. How are you
making the boost::python::object? I always construct a handle first.
> Is there any correct way to check, other than doing
> if(obj.ptr())
> ?
>
>
> And what's the correct way to check for PyNone other than
> if (obj == boost::python::object())
> ?
>
I think that's the standard way. I suppose
if (obj.ptr() == Py_None)
might be faster on some compilers, but it's almost certainly not worth
worrying about.
Jim Bosch
More information about the Cplusplus-sig
mailing list