[C++-sig] Returning None from __getitem__
Stefan Seefeld
seefeld at sympatico.ca
Fri Sep 19 14:07:46 CEST 2008
Hi Renji,
From a language / API design point of view, I think it would be best
(i.e., least surprising) to follow the expected behavior. Python's dict
type does have ways to handle what you want (and you can even set
default values to be returned for non-existent keys).
As for your particular case, where your C++ map throws an exception, but
you want the wrapper to return None, that's simple, too:
boost::python::object my_get_wrapper(PropSet &p, std::wstring const &k)
{
try { return p->get(k);} // implicitly convert valid value to python
object
catch (InvalidKeyException const &) { return
boost::python::object();} // on failure, return None
}
Then, you bind that as 'get':
class_<PropSet, ...> (...)
.def("get", my_get_wrapper);
HTH,
Stefan
--
...ich hab' noch einen Koffer in Berlin...
More information about the Cplusplus-sig
mailing list