[C++-sig] checking passed arg is python type

Neal Becker ndbecker2 at gmail.com
Thu Mar 14 23:12:24 CET 2013


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");



More information about the Cplusplus-sig mailing list