[C++-sig] Returning None from __getitem__

Renji Panicker renjipanicker at gmail.com
Sat Sep 20 13:08:03 CEST 2008


Exactly what I wanted! Thanks a lot, Stefan!

On Fri, Sep 19, 2008 at 5:37 PM, Stefan Seefeld <seefeld at sympatico.ca> wrote:
> 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...
>
> _______________________________________________
> C++-sig mailing list
> C++-sig at python.org
> http://mail.python.org/mailman/listinfo/c++-sig
>



More information about the Cplusplus-sig mailing list