[C++-sig] Getting operator[]() to throw RangeError using py++

David Wolfe dwolfe at gforcetech.com
Sun Jan 6 09:45:42 CET 2008


Thanks, Roman, for those references.  I'll think about doing this in
python instead, since it'll be a lot easier.

I did figure out that what I really needed to do if I want to use C++
is:

   - Exclude operator[](), since it wasn't really doing the 'pythonic'
     thing

   - Create helper functions to get the vector length, get an item by
     index, and set an item by index

   - Expose these functions to python as __len__, __setitem__ and
     __getitem__.

Correction to my previous post: the C++ helper functions mapped to
__setitem__ and __getitem__ need to throw std::out_of_range(), which
gets automatically translated by Boost.Python to IndexError (not
RangeError).

So this works now, FWIW:

 >>> for p in osg.Vec3f(1,2,3):
...   print p
...
1.0
2.0
3.0
 >>> v[2]
3.0
 >>> v[3]
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
IndexError: vector index out of range

(Many thanks to Tim Shead: http://tinyurl.com/2kgzjo ...)






More information about the Cplusplus-sig mailing list