[C++-sig] checking passed arg is python type
Jim Bosch
talljimbo at gmail.com
Thu Mar 14 23:47:47 CET 2013
On 03/14/2013 06:12 PM, Neal Becker wrote:
> I'm expecting a numpy.random.RandomState object to be passed to me. I want to
> check it is. The best I could think of is below. Anything more boost::python-
> ish to do this task?
>
> static object rs_obj;
>
> template<typename out_type=uint32_t>
> struct engine {
> typedef out_type result_type;
> bp::object rs; // RandomState object
>
> void verify (object const& o) {
> if (!PyObject_IsInstance(o.ptr(), rs_obj.ptr()))
> throw std::runtime_error ("engine: expected RandomState");
> }
>
> engine (bp::object const& _rs) : rs (_rs) { verify (_rs); }
> ...
>
> BOOST_PYTHON_MODULE...
>
> object mod = object (handle<> ((PyImport_ImportModule("numpy.random"))));
> rs_obj = mod.attr("RandomState");
>
I believe you can replace the penultimate line with:
bp::object mod = bp::import("numpy.random");
But I can't think of any ways to Boost.Python-ize the rest; there really should be an "isinstance" wrapper in Boost.Python, but there isn't. You may also want to be a little careful with the return value of PyObject_IsInstance - I believe that it's psosible for it to raise an exception instead of simply returning 0, and in that case you'd want to use bp::throw_error_already_set() to propagate the exception to Python.
Jim
More information about the Cplusplus-sig
mailing list